第一步要创建一个登录界面
<form action="/servlet/login" method="post"> <input type="text" name="username"> <input type="submit" name="提交"> </form>
提交到/servlet/login跟xml的mapping对应
然后提交到LoginServlet去验证输入的用户名
如果用户名正确将session的id保存到session中
如果不正确跳转到另一个界面/error.jsp中
public class LoginServlet extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //获取前端请求的参数 String username = req.getParameter("username"); if(username.equals("admin")){//登录成功 req.getSession().setAttribute("user-session",req.getSession().getId()); resp.sendRedirect("/sys/success.jsp"); }else {//登录失败 resp.sendRedirect("/error.jsp"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
登录成功界面里边设置一个注销session的servlet
如果点击注销到LoginOut.java中,
首先要获取在登录成功的时候保存的session的id
然后判断是否存在如果不为空则存在,调用req.getSession.removeAttribute进行删除
接着跳转回原来的界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h1>主页</h1> <a href="/servlet/logout">注销</a> </body> </html>
public class LoginOut extends HttpServlet { @Override protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Object user_name = req.getSession().getAttribute("user-session"); if (user_name!=null){ req.getSession().removeAttribute("user_name"); resp.sendRedirect("/Login.jsp"); }else { resp.sendRedirect("/Login.jsp"); } } @Override protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }
最重要的是过滤器
public class SysFilter implements Filter { public void init(FilterConfig filterConfig) throws ServletException { } public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { HttpServletRequest servletRequest1= (HttpServletRequest) servletRequest; HttpServletResponse servletResponse1 = (HttpServletResponse) servletResponse; if (servletRequest1.getSession().getAttribute("user_session")==null){ ((HttpServletResponse) servletResponse).sendRedirect("/error.jsp"); } filterChain.doFilter(servletRequest,servletResponse); } public void destroy() { } }
因为是不是HttpServletRequest所以要进行一下强转
然后进行判断是否存在
如果不存在的话就直接拦截住让他去没有权限的那个界面