session实战应用

 
loginServlet
@WebServlet("/login")
public class login extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("UTF-8");      //解决乱码
        resp.setContentType("text/html;charset=utf-8");
        PrintWriter printWriter =resp.getWriter();
        String id = req.getParameter("id");
        String password = req.getParameter("password");
        User user = null;
        Userdao userdao = new Userdao();
        user = userdao.select(id);
        if(user != null){
            if(user.getPassword().equals(password)){
                HttpSession session = req.getSession();
                session.setAttribute("user",user);
                session.setMaxInactiveInterval(10);
                resp.sendRedirect("/cookie_war_exploded/index.jsp");
            }else {
                printWriter.println("密码错误");
                resp.sendRedirect("/cookie_war_exploded/login.jsp");
            }
        }else {
            printWriter.println("账号不存在");
            resp.sendRedirect("/cookie_war_exploded/login.jsp");
        }
    }

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
  HttpSession session1 = request.getSession();
  User user = (User) session1.getAttribute("user");
//  System.out.println(user);
%>
<html>
  <head>
    <title>主页</title>
  </head>
  <body>
  <%
    if(user == null){
      response.sendRedirect("/cookie_war_exploded/login.jsp");
    }
    else {
  %>
    欢迎来到你的主页<%=user.getName()%>
  <%
    }
  %>
  </body>
</html>

 

posted @ 2022-04-27 09:09  软工小蜗牛  阅读(66)  评论(0编辑  收藏  举报