Java EE--------The use of filters to achieve user automatic login, secure login, cancel automatic logon black user no login

Source: Internet
Author: User

In our lives, the automatic login for the account is already very common, so the use of filters to achieve this function

Mainly describes the user's automatic login and cancel automatic login, as well as the implementation of automatic logon day or N-day automatic login, when the user IP is added to the blacklist, directly using the filter to return a warning page.

The function of the filter is very powerful, we just need to add it after the well-written foreground servlet to implement this function

Ps: This is just a demonstration, inside the access to the database part, their own random simulation under, mainly to highlight the function of automatic login.

Front Code:

The foreground code is either successful or not displayed on this page. Technology used:JSTL tag Application, session read 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" >


implementation code for the servlet:as in the previous code, only responsible for interacting with the foreground: the technology used in the URL code , the value exists in the cookie, there is a session inside, page jump (forward)
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 freely here, Should go to Servvice-->dao to access the database in the back//here assume that the login is successful, we put the information into the session request.getsession (). SetAttribute ("user", name);//compatible with Chinese, We need to encode Name=urlencoder.encode (name, "Utf-8");p Wd=urlencoder.encode (pwd, "utf-8"); Cookie C =new Cookie ("Autologin", name+ "," +pwd);//This value cannot be used in this way, security considerations, we must know to use encryption, or two times 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 intercept redirection, forwarding is the internal direct forwarding, but the filter is not good, but only need to be configured in Web. Xml. }else{request.getsession (). SetAttribute ("Error", "1"); Response.sendredirect (Request.getcontextpath () + "/ Index.jsp ");}}
So far, there is no technology, and the previous code one, now is the role of filter.
Secure Login:before we used dynamic import to secure login, prevent users from entering the project, no login, arbitrary input can enter the interface, dynamic import can achieve this function, but the use of filters better. in the filter is generally written dofilter (), only need to determine whether the session container is NULL, NULL This means that it is not logged in, directly kicked back to the login interface, no, then release
Code submission:
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 ("non-normal login"); Resp.sendredirect (Req.getcontextpath () + "/index.jsp");} ELSE{SYSTEM.OUT.PRINTLN ("successful login"); Chain.dofilter (req, resp);}}

character encoding:the problem of character encoding, which needs to be entered manually in the servlet's Dopost (), request.setcharacterencoding ("Utf-8") each time, each servlet needs to be entered, Too troublesome, we adopt filter to realize;Code submission:
<span style= "FONT-SIZE:18PX;" >public void DoFilter (ServletRequest request, Servletresponse Response,filterchain chain) throws IOException, servletexception {request.setcharacterencoding (character);//go to the client to receive the encoding Response.setcontenttype ("Text/html;charset =utf-8 ");//set out the encoded Chain.dofilter (request, response);} @Overridepublic void init (filterconfig config) throws servletexception {Character=config.getinitparameter ("character ");//a</span><span style=" font-size:18px; Font-family:arial, Helvetica, Sans-serif; >haracter  is set to global variable, </span><span style= "FONT-SIZE:18PX;" >}</span>
Top up again. the character 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 needs to determine the session inside is the value, there is, then login, no, go to local cookie search, exist, go to database matching, if the match succeeds, the session container added value.
Code submission:
public void DoFilter (ServletRequest request, Servletresponse Response,filterchain chain) throws IOException, servletexception {//Auto login, you must set the session inside is all have values, there, then the current login, no, will go to access the data inside the cookie, the data in the cookie//whether and the database inside the match, is, Set the value in the session here, no, let go of HttpServletRequest req= (httpservletrequest) request; HttpServletResponse resp = (httpservletresponse) response; String session = (string) req.getsession (). getattribute ("user"); if (session==null) {//indicates that a cookie is not currently logged in 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 connect it with commas. String[] Strs=value.split (",");//The Logserlvet is encoded first, then comma-connected, we need to reverse string Name=urldecoder.decode (Strs[0], " Utf-8 "); String Pwd=urldecoder.decode (strs[1], "utf-8");//NAME,PWD data to the background to access the database, we are just casually write if (Name.equals (pwd)) { Req.getsession (). SetAttribute ("user", name);//Set argument break in Session;}}}} Chain.dofilter (req, resp);//must be put away oh. }

blacklisted usersblacklist user, no login, tell it directly the result Code submission:
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 access to the IP; System.out.println (ip+ "Iipp"), if (Set.contains (IP)) {//Within the blacklist System.out.println ("Set"), Resp.getwriter (). Print (" You are blacklisted. <a href= ' "+req.getcontextpath () +"/index.jsp ' > Return </a> ");//return is not possible, because the index to the server when the request is directly intercepted}else{ Chain.dofilter (req, resp);}}

blacklist returned by the type of list is the best, I am here to manually add, originally should be written from a tool class from the database read, not only to check, but also to increase the deletion-blacklist. code presented:Hashset defined as a global variable, set contains contain, high efficiency.
public void init (Filterconfig arg0) throws Servletexception {//Here is the Blacklist list, which is extracted from the database. Here is just a simple simulation under Set.add ("192.132.0.12");//This is the black IP, this is from the background database to get. Set.add ("localhost"); Set.add ("192.132.32.4"); Set.add ("127.0.0.1");}


Cancel Automatic Login

When automatic login is considered unsafe, so we set no automatic login

Previously we knew that automatic login relies on the technology stored in cookies, so here we just need to delete the cookie.

Because canceling automatic login is a hyperlink, the servlet is written.

Code submission:

public void DoPost (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException {Cookie cc=new Cookie ("Autologin", "");//The method of deleting a cookie, establishing a connkie with the same name, and then setting the cookie setmaxage=0;cc.setmaxage (0); Cc.setpath ( Req.getcontextpath ()); Resp.addcookie (cc); Resp.sendredirect (Req.getcontextpath () + "/index.jsp");}

These simple functions can be achieved by the above.

Specific resources I have uploaded click to open the link, you are welcome to discuss together and learn together.



Java EE--------The use of filters to achieve user automatic login, secure login, cancel automatic logon black user no login

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.