In our lives, it is already very common for automatic login to accounts, so we use filters to implement this function.
It mainly introduces the user's automatic login and cancelled automatic login, as well as the realization of automatic login in one day or n days. After the user's IP is added to the blacklist, it directly uses the filter to return to a warning page.
The function of the filter is very powerful. We only need to add the servlet after the written front-end backend to realize this function.
Ps: This is just a demonstration. I simulated the part of the access database by myself, mainly focusing on the realization of automatic login function.
Front Desk Code:
Whether the foreground code is successful or not is displayed on this page. Techniques used: application of jstl tags, session reading value
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <%@taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> </head> <body> <c:if test="${!empty sessionScope.error }"> Your password or username is wrong. <!-- After displaying, you need to remove the value inside--> <c:remove var="error" scope="session"/> </c:if> <c:if test="${empty sessionScope.user }" var="boo"> <h2>This is the page for login</h2> <form action="<c:url value='/LoginServlet'//>" method="post"> NAME:<input type="text" name="name" /><br/> PWD:<input type="text" name="pwd" /><br/> Not automatically logged in:<input type="radio" name="time" value="0" /><br/> One day:<input type="radio" name="time" value="1" /><br/> Seven days:<input type="radio" name="time" value="7" /><br/> <input type="submit" value="submit" /> </form> </c:if> <c:if test="${!boo }"> Welcome, ${sessionScope.user }, successfully logged in <a href="">Module 1</a> <a href="">Module 2 </a> <a href="<c:url value='/CancelAutoLogin'//>">CancelAutoLogin</a> </c:if> </body> </html>The implementation code of servlet:
Like the previous code, it is only responsible for interacting with the front desk: the technology used in it includes url encoding, the value is in the cookie, the session is in the page, and the page is jumped (forwarded)
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { String name=request.getParameter("name"); String pwd=request.getParameter("pwd"); String time=request.getParameter("time"); if(name!=null && pwd!=null && name.equals(pwd)){//Write here as you like, you should go to service-->dao to access the database later//Assuming that the login is successful, we store the information into the session request.getSession().setAttribute("user", name); //Compatible with Chinese, we need to encode name=URLEncoder.encode(name, "utf-8"); pwd=URLEncoder.encode(pwd, "utf-8"); Cookie c =new Cookie("autologin", name+","+pwd);//This value cannot be used in this way. For security considerations, we must know to use encryption or secondary encryption, int _time=60*60*24*Integer.valueOf(time); c.setMaxAge(_time); response.addCookie(c); response.sendRedirect(request.getContextPath()+"/index.jsp");//The default setting in the filter is to intercept redirection, and forwarding is direct internal forwarding. However, the filter is not easy to deal with, but you only need to configure it in web.xml. }else{ request.getSession().setAttribute("error", "1"); response.sendRedirect(request.getContextPath()+"/index.jsp"); } }Until now, I feel that there is no technology. The same code as the previous ones is now the function of Filter.
Secure login:
We used dynamic import to log in safely before, so as to prevent users from logging in without logging in after entering the project. You can enter the interface at will by entering the project. Dynamic import can achieve this function, but it is better to use filters.
Generally, dofilter() is written in the filter; you only need to determine whether the session container is null. This means that this is not logged in. Just kick back to the login interface. Otherwise, let it go
The code is presented:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req=(HttpServletRequest) request; HttpServletResponse resp=(HttpServletResponse) response; String session=(String) req.getSession().getAttribute("user"); if(session==null){ System.out.println("Abnormal login"); resp.sendRedirect(req.getContextPath()+"/index.jsp"); }else{ System.out.println("Successful login"); chain.doFilter(req, resp); } }Character encoding:
The problem of character encoding. In the past, I had to manually enter it in the dopost() of the servlet every time, request.setCharacterEncoding("utf-8"); every servlet needs input, which is too troublesome, so we use filters to implement it;
The code is presented:
<span style="font-size:18px;">public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { request.setCharacterEncoding(character);//Remove the encoding received by the client.setContentType("text/html;charset=utf-8");//Set the sent out chain.doFilter(request, response); } @Override public void init(FilterConfig config) throws ServletException { character=config.getInitParameter("character");//a</span><span style="font-size: 18px; font-family: Arial, Helvetica, sans-serif;">haracter Set as a global variable, </span><span style="font-size:18px;"> }</span>The character above is defined as a global variable, and the initial value is configured in web.xml.
The web.xml code is presented:
<filter> <filter-name>character</filter-name> <filter-class>cn.hncu.Filter.CharacterFilter</filter-class> <init-param> <param-name>character</param-name> <param-value>UTF-8</param-value> </init-param> </filter>
Automatic login:
Main idea: Automatic login requires determining that the session has values. If there is, then after logging in, if there is no, go to the local cookie to find it, exist, and match the database. If the match is successful, add the session container.
The code is presented:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { //Automatically log in, you must set that there are values in the session. If there is, then you have logged in and no, you must access the data in the cookie. The data in the cookie//Whether it matches the database? Yes, set the value in the session here, no, let HttpServletRequest req=(HttpServletRequest) request; HttpServletResponse resp =(HttpServletResponse) response; String session =(String) req.getSession().getAttribute("user"); if(session==null){//Indicates that no cookie has been logged in at present cs[]=req.getCookies(); if(cs!=null){ for(Cookie c:cs){ if(c.getName().equals("autologin")){ String value=c.getValue();//This is encrypted, but we just connected with commas. String[] strs=value.split(",");//In logserlvet, we use encoding first, and then comma connection. We need to reverse String name=URLDecoder.decode(strs[0], "utf-8"); String pwd=URLDecoder.decode(strs[1], "utf-8"); //Get name, pwd data to the background to access the database, we just write if(name.equals(pwd)){ req.getSession().setAttribute("user", name);//Set the parameters break in session; } } } } } chain.doFilter(req, resp);//You must let go. . }Blacklisted users
Blacklisted users, not log in, just tell them the result
The code is presented:
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { HttpServletRequest req=(HttpServletRequest) request; HttpServletResponse resp=(HttpServletResponse) response; String ip=req.getRemoteAddr();//Get accessed ip; System.out.println(ip+"IIPP"); if(set.contains(ip)){//Inside the blacklist System.out.println("set"); resp.getWriter().print("You are in the blacklist..<a href='"+req.getContextPath()+"/index.jsp'>return</a>"); //Return is not possible, because index directly intercepts when requesting from the server}else{ chain.doFilter(req, resp); } } The type returned by the blacklist is the best. I added it manually here. I originally should read it from the database by writing a tool class. It can not only be checked, but also add, delete and modify - blacklist.
The code is presented:
Hashset is defined as a global variable, and set contains contains, which is very efficient.
public void init(FilterConfig arg0) throws ServletException { //Here is a blacklist list, retrieved from the database. Here is just a simple simulation set.add("192.132.0.12");//This is a black IP, which is obtained from the background database. set.add("localhost"); set.add("192.132.32.4"); set.add("127.0.0.1"); }Cancel automatic login
When the automatic login is always considered unsafe, we set that no automatic login
We knew before that automatic login relies on the technology stored in cookies, so here we only need to delete the cookies.
Because canceling automatic login is a hyperlink, it is written as a servlet.
The code is presented:
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { Cookie cc=new Cookie("autologin", "");//The method to delete the cookie is to create a connkie with the same name, and then set the cookie's setmaxage=0; cc.setMaxAge(0); cc.setPath(req.getContextPath()); resp.addCookie(cc); resp.sendRedirect(req.getContextPath()+"/index.jsp"); }The above can realize these short answer functions.
The above is a detailed explanation of the relevant knowledge introduced by the editor to JavaEE using filters to achieve automatic login and secure login to cancel automatic login. I hope it will be helpful to everyone. If you have any questions, please leave me a message and the editor will reply to everyone in time. Thank you very much for your support to Wulin.com website!