Java EE use filter to implement login (user automatic login secure login Cancel Automatic login black user prohibit login) _java

Source: Internet
Author: User

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

The main introduction of the user's automatic login and cancellation of automatic login, as well as the implementation of a day automatic login or n-day automatic login, when the user IP was added to the blacklist, directly using the filter to return a warning page.

The function of the filter is very powerful, we only need to do after the written front of the servlet and then add to achieve this function

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

Foreground 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" >  public void DoPost (HttpServletRequest request, httpservletresponse response) throws 
Vletexception, 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 at will, you should go to Servvice-->dao to access the database//here is to assume the login was successful, 
We deposit the information in 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 can not 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 to intercept redirects, forwarding is the internal direct forwarding, but the filter, not easy to do, 
However, it is only necessary to configure it in Web.xml. 
}else{request.getsession (). setattribute ("Error", "1"); 
Response.sendredirect (Request.getcontextpath () + "/index.jsp"); } 
} 

So far, all feel no technology, and the previous code one, now is the role of filter.

Secure Login:

Before we used dynamic import to secure login, to prevent users from entering the project, do not need to 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 this is not logged in, directly to the login interface, no, then release

Code present:

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, each time before each need in the servlet dopost () inside itself manually input, request.setcharacterencoding ("Utf-8"); each servlet needs input, too troublesome, we use the filter to achieve;

Code present:

<span style= "FONT-SIZE:18PX;" >public void Dofilter (ServletRequest request, servletresponse response, 
Filterchain chain) throws IOException, servletexception { 
request.setcharacterencoding (character);//Go to client-received encoding 
Response.setcontenttype ("text/ Html;charset=utf-8 ");/set the emitted encoding 
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 to global variable, </span><span style= "FONT-SIZE:18PX;" > 

The above character is defined as a global variable, and the initial value is configured in Web.xml.

Web.xml Code:

<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> 

Login automatically:

Main idea: Automatic login need to judge the session inside is the value, there are, then logged in, no, go to the local cookie lookup, existence, to the database matching, if the match succeeds, the session container added value.

Code present:

 public void Dofilter (ServletRequest request, servletresponse response, Filterchain chain) Throws IOException, Servletexception {//automatic login, you must set the session inside is all have a value, there, then currently logged in, no, must go to the cookie inside the data, cookies inside the data/ 
Whether and the match inside the database, is, will the value of the session inside set, no, let go httpservletrequest req= (httpservletrequest) request; 
HttpServletResponse resp = (httpservletresponse) response; 
String session = (string) req.getsession (). getattribute ("user"); 
if (session==null) {//indicates that the Cookie cs[]=req.getcookies () is not currently logged in; if (Cs!=null) {for (Cookie C:cs) {if (C.getname (). Equals ("Autologin")) {String value=c.getvalue ();//This is encrypted, 
But we're just connecting with commas. String[] Strs=value.split (",");//In Logserlvet It is encoded first and 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 access to the database, we are here just casually write if (Name.equals (pwd)) {req.getsession (). setattribute ("user", name); 
Set the parameter break within the session; 
}}} chain.dofilter (req, resp);/must let go. } 

Blacklist users

Blacklist user, no login, just tell it the result

Code present:

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 IP; 
System.out.println (ip+ "Iipp"); 
if (Set.contains (IP)) {//Within the blacklist 
System.out.println ("set"); 
Resp.getwriter (). Print ("You belong to the Blacklist.") <a href= ' "+req.getcontextpath () +"/index.jsp ' > Return </a> "); 
Return is also not possible, because the index to the server when the request directly intercepted 
}else{ 
chain.dofilter (req, resp); 
} 

Blacklist return the type of the best, I am here to manually add, I should be from writing a tool class from the database read, not only can check, but also can be deleted-blacklist.

Code present:

HashSet is defined as a global variable, and set contains contain, which is highly efficient.

public void init (Filterconfig arg0) throws Servletexception { 
//This is the blacklist list, which is fetched from the database. Here is simply simulated under the 
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 Logon

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

As we know before, automatic login depends on the technology stored in the cookie, so here we just need to delete the cookie.

Because canceling automatic logons is a hyperlink, it is written in a servlet.

Code present:

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

These can be achieved by these simple functions.

The above is a small set to introduce the detailed description of Java EE using filters to achieve user automatic login security login to cancel automatic login black users of the relevant knowledge, hope to help, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

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.