要用转发机制:比如一个登录页面:
登录
服务器端代码:
public class ActionServlet extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uri = request.getRequestURI();
String action = uri.substring(
uri.lastIndexOf("/"),uri.lastIndexOf("."));
if(action.equals("/login3")){
//
String number1 = request
.getParameter("number");
HttpSession session = request.getSession();
String number2 = (String) session
.getAttribute("number");
if(!number1.equals(number2)){
//
request.setAttribute("checkcode_error",
".......");
request.getRequestDispatcher("login.jsp")
.forward(request, response);
return;
}
String username = request.getParameter("username");
String pwd = request.getParameter("pwd");
UserDAO dao = new UserDAO();
try {
User user = dao.findByUsername(username);
if(user!=null && user.getPwd().equals(
DigesterUtil.digester(pwd))){
//
System.out.println("id1:" + session.getId());
session.setAttribute("user", user);
//
response.sendRedirect("main.jsp");
}else{
//
request.setAttribute("login_error",
"fghfghfgh");
request.getRequestDispatcher("login.jsp")
.forward(request, response);
}
} catch (Exception e) {
e.printStackTrace();
throw new ServletException(e);
}
}