应用环境:
点击前台页面,执行某些操作。后台action/servlet 执行后,返回处理结果(成功、失败、原因、状态等)信息。在前台jsp进行弹窗显示,alert();
后台处理代码:(把要提示的数据放到session中。)
if(flag){
message="分类修改成功";
req.getSession().setAttribute("message", message);
resp.sendRedirect(req.getContextPath()+"/servlet/categoryListServlet");
}else{
message="分类修改失败";
req.getSession().setAttribute("message", message);
}
前台处理代码:
String mess=(String)session.getAttribute("message");
if("".equals(mess) && mess==null){
}
else{%>
alert("");
session.setAttribute("message", "");
上面的例子是把信息放入整个会话session中,这个session对整个用户请求都有效,在Session不过期时间之内都有效,其实有时候是要分别来对待的,比如新增、删除、修改、登陆成功等操作,我们操作成功后,是要重定向到目标页面,重定向request作用域不能延伸,所以我们要用Session存放弹框信息,但如果是转发到目标页面,我们就可以用request了
登陆实例:
index.jsp:
1
2
3 Stringpath=request.getContextPath();4 StringbasePath=request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";5 %>
6
7
8
9
10 ">
11
12
My JSP 'index.jsp' starting page13
14
15
16 This is my JSP page.
17
18 Objectmessage=request.getAttribute("message");19 if(message!=null &&!"".equals(message)){20
21 %>
22
23 alert("");24
25
26 /servlet/checkLogin"method="post">
27
28
29
30
31
CheckLogin.java(servlet):
1 packageservlet;2 importjava.io.IOException;3 importjava.net.InetSocketAddress;4 importjava.util.concurrent.Executor;5 importjavax.servlet.ServletException;6 importjavax.servlet.http.HttpServlet;7 importjavax.servlet.http.HttpServletRequest;8 importjavax.servlet.http.HttpServletResponse;9 importjavax.servlet.http.HttpSession;10 public class CheckLogin extendsHttpServlet{11 @Override12 protected voiddoGet(HttpServletRequest req, HttpServletResponse resp)13 throwsServletException, IOException {14 doPost(req, resp);15 }16 @Override17 protected voiddoPost(HttpServletRequest req, HttpServletResponse resp)18 throwsServletException, IOException {19 String username = req.getParameter("username");20 HttpSession session=req.getSession();21 if(username.equals("admin")){22 //登陆成功,我是重定向到其它页面,所以这里我要用session才可以把成功的信息传递给count.jsp
23 session.setAttribute("sucess", "登陆成功!");24 resp.sendRedirect(req.getContextPath()+"/count.jsp");25 }else{26 //登陆失败,我有的是转发,转发request作用域是连续的,所以我这里可以用request传递失败的信息给JSp页面
27 req.setAttribute("message", "登陆失败!");28 req.getRequestDispatcher("/index.jsp").forward(req, resp);29 }30 }31 @Override32 protected voidservice(HttpServletRequest req, HttpServletResponse resp)33 throwsServletException, IOException {34 super.service(req, resp);35 }36
37 }
web.xml
checkLogin
servlet.CheckLogin
checkLogin
/servlet/checkLogin
count.jsp(登陆成功目标页)
1
2 pageEncoding="UTF-8"%>
3
4
5
6
7
Insert title here8
9
10
11 Objectmessage=session.getAttribute("sucess");12 if(message!=null &&!"".equals(message)){13
14 %>
15
16 alert("");17
18
19 hello word!20
21