带新手玩转MVC——不讲道理就是干(下)

来源:
网络
收录时间:
2021-04-08 11:11:24
科技 阅读 4222

摘要:package servlet;import domain.User;import java.util.List;String username = req.getParameter("username");String password = req.getParameter("password");String remember = req.getParameter("remember");Cookie cookie = new Cookie("username",username);cookie.setPath("/login.jsp");cookie.setMaxAge(60*60*24);resp.addCookie(cookie);req.getSession().setAttribute("user",user);resp.sendRedirect("/success.jsp");

带新手玩转MVC——不讲道理就是干(下)

前言:废话不多说,直接开干

 

完整案例演示

 

 

 

 

 

 

案例代码

LoginServlet

package servlet;

import domain.User;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

/*
* 用户登录的Servlet
* */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        req.setCharacterEncoding("utf-8");
        resp.setCharacterEncoding("utf-8");

        //接收数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        //从ServletContext域中获得保存用户信息集合
        List<User> list = (List<User>) this.getServletContext().getAttribute("list");
        for (User user:list){
            //判断用户名是否正确
            if (username.equals(user.getUsername())){
                //判断密码是否正确
                if (password.equals(user.getPassword())){
                    //用户名密码都正确
                    //登录成功
                    //判断记住用户名复选框是否勾选
                    String remember = req.getParameter("remember");
                    if ("true".equals(remember)){
                        //完成记住用户名的功能
                        Cookie cookie = new Cookie("username",username);
                        //设置有效路径
                        cookie.setPath("/login.jsp");
                        //设置有效时间
                        cookie.setMaxAge(60*60*24);
                        //将cookie回写到浏览器
                        resp.addCookie(cookie);
                    }
                    //将用户的信息保存到Session中
                    req.getSession().setAttribute("user",user);
                    resp.sendRedirect("/success.jsp");
                    return;
                }
            }
        }
        //登录失败
        req.setAttribute("msg","用户名或密码错误!");
        req.getRequestDispatcher("/login.jsp").forward(req,resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
查看全文
返回顶部