Use filtering to realize permission verification
Train of thought analysis:
1. When the user is not logged in
In addition to accessing the login interface and registration login interface and login You can't access other pages except do. If you visit other pages, you will enter the login interface
2. When the user logs in
1) There is user information in the cookie. Click login to log in directly
2) There is no user information in the cookie. Judge whether the user logs in for the second time
3) If there is no user information in the cookie or session, the user needs to enter the account password for authentication
The account and password are correct: the login is successful, and the information is saved in the session object at the same time
If no login for three days is checked, the information is saved in the cookie
Account and password error: return to the login interface and log in again
Implementation steps:
1. Create project DServlet and arrange the running environment
2. Create a new lib folder under WEB-INF under the web and import the required third-party jar package
3. Create com. Under src jrt. web. filter. UserRequestFilter
Business logic:
Inherit the ServletException class, first forcibly convert it to the HttpServlet type parameter, and then obtain the username value. If the user logs in successfully, there is a value in the session. If he has logged in, he can directly enter the index interface. If there is no login, judge again whether it will jump to login except (login.jsp,register.jsp,loginServlet.do) JSP interface to log in and realize filtering.
4. Create com. Under src jrt. web. servlet. LoginServlet
Business logic:
First, confirm whether there are users in the cookie. If there are users who can log in directly without entering, obtain all cookies for circular judgment, and then judge whether they log in for the second time. If neither of the two cases is true, enter the user name and password for verification. During the verification process, pay attention to whether the user checks three-day login free. If so, save the information in the cookie
5. Write the front page index jsp
6. Write the front page login jsp
Set in the form to enable users to enter user name and password, and set the three-day login free option.
7. Write the front page, register JSP users can also enter this page without logging in.
UserRequestFilter.java
package com.jrt.web.filter; import javax.servlet.*; import javax.servlet.annotation.WebFilter; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import java.io.IOException; import java.util.HashSet; import java.util.Set; @WebFilter(urlPatterns = {"*.do","*.jsp"}) public class UserRequestFilter implements Filter { @Override public void init(FilterConfig filterConfig) throws ServletException { Filter.super.init(filterConfig); } @Override public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException { //1. Forced rotation HttpServletRequest request=(HttpServletRequest)servletRequest; HttpServletResponse response=(HttpServletResponse)servletResponse; //2. If the user has successfully logged in, there is a value in the session. Judge whether to log in by judging the username String username=(String)request.getSession().getAttribute("username"); System.out.println("username="+username); System.out.println(">>>"+request.getRequestURI()); //3. If you have logged in if(username!=null){ request.getRequestDispatcher("index.jsp").forward(request,response); return; } //4. If not logged in. There are only two ways to go to the login interface or registration interface if(username==null && !isCheck(request.getRequestURI())){ System.out.println("in....."); request.getRequestDispatcher("login.jsp").forward(request,response); return; } //Release filterChain.doFilter(request,response); } public boolean isCheck(String requsetURI){ boolean flag=false; Set<String> sets=new HashSet<>(); sets.add("register.jsp"); sets.add("login.jsp"); sets.add("loginServlet.do"); for(String uri:sets){ if(requsetURI.endsWith(uri)){ flag=true; break; } } return flag; } @Override public void destroy() { Filter.super.destroy(); } }
loginServlet.java
package com.jrt.web.servlet; import javax.servlet.ServletException; import javax.servlet.annotation.WebServlet; import javax.servlet.http.*; import java.io.IOException; @WebServlet("/loginServlet.do") public class LoginServlet extends HttpServlet { @Override protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { //1. First, confirm whether there is a user in the cookie, so you don't have to log in //Get all cookies Cookie[] cs=req.getCookies(); //Be sure to judge whether this is empty if(cs!=null){ System.out.println("conduct cookie judge"); for(Cookie cookie:cs){ String name=cookie.getName(); String value=cookie.getValue(); //value= URLDecoder.decode(value,"utf-8"); if("username".equals(name)){ System.out.println("cookies Inside name: "+name); req.getSession().setAttribute("username",value); req.getRequestDispatcher("index.jsp").forward(req,resp); return; } } } //2. It is not necessary to judge whether to log in for the second time, because the filter has been released when the username value is not empty String uname=(String) req.getSession().getAttribute("username"); if(uname!=null){ req.getRequestDispatcher("index.jsp").forward(req,resp); return; } //There is no cookie, nor is it the second login. You can only enter the account password for judgment req.setCharacterEncoding("utf-8"); String username =req.getParameter("username"); System.out.println(username); String password =req.getParameter("pwd"); System.out.println(password); if("zhangsan".equals(username)&&"123456".equals(password)){ //Judge whether he chose three-day login free if("auto".equals(req.getParameter("auto"))){ Cookie cookie1=new Cookie("username",username); Cookie cookie2=new Cookie("password",password); cookie1.setMaxAge(24*60*60*3); cookie2.setMaxAge(24*60*60*3); resp.addCookie(cookie1); resp.addCookie(cookie2); } String success="Login succeeded"; req.setAttribute("success",success); HttpSession session = req.getSession(); session.setAttribute("username",username); req.getRequestDispatcher("index.jsp").forward(req,resp); }else{ resp.sendRedirect("login.jsp"); } } }
login.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <h2 align="center">User login authentication</h2> <form method="post" action="loginServlet.do" > user name:<input type="text" name="username" id="username"><br> password:<input type="text" name="pwd" id="pwd"><br> <input type="submit" value="Sign in"><br> <input type="checkbox" name="auto" value="auto" id="auto">Three day login free <a href="register.jsp">Go and register</a> </form> </body> </html>
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>$Title$</title> </head> <body> Here is index </body> </html>
register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> This is the registration page </body> </html>