以前寫servlet時就用到這個,但是現在學了springMVC+hibernate后就不知道怎么實現了,后來在網上找了好多,看了好多,最后經過自己實踐成功的如下:
1.首先是Controller控制類接受處理路徑下的那個方法參數要傳入:
HttpServletResponse response對象,這個對象用來實現響應。
2.接下來要在方法內編寫你的響應信息的文本格式和編碼方式:
response.setContentType("text/html;charset=gb2312");
這個可根據你工程的編碼確定,不然會出現亂碼。
然后就是通過response對象獲取回寫輸出的PrintWriter對象:
PrintWriter out = response.getWriter();
3.接下來就是你要跳轉后彈出的提醒內容信息:
out.print("<script language=\"javascript\">alert('恭喜你成功了!');window.location.href='/你的工程名/user/index'</script>");
后面必須要加上window.location.href='/你的工程名/user/index',這個是你跳轉到的目標地址,
4.最后就是你要在url地址欄顯示的正確路徑:
return "/user/index";
--------------------------------------一個完整的例子--------------------------------
@RequestMapping(value = "/user/index", method = RequestMethod.POST)
public String checkLogin(@RequestParam("userName") String userName,
@RequestParam("password") String password,
HttpServletResponse response) throws IOException {
//根據用戶名userName和密碼password查看是否是非法用戶,此處代碼略。。。。
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
if(非法用戶){
out.print("<script language=\"javascript\">alert('登錄失敗!');window.location.href='/你的工程名/login'</script>");
return "/login";
}
return "/user/index";
}