Filter filter for automatic login

Source: Internet
Author: User
Tags button type

Filter Introduction
Question: What is filter and what can it do?
1. From two aspects to resolve what is a filter?
1. The function can help us to filter the request and response operation.
2. An interface defined by the technology sun Company, Javax.servlet.Filter

What can 2.Filter do?
Common examples:
1. Universal encoding filter.
2. Coarse-grained permission control (URL level)
3. Filter some sensitive words

Filter creation steps:
1. Create a class to implement the Javax.servlet.Filter interface.
2. Rewrite the filter interface in three methods init doFilter destroy.
3. Configure the filter in the Web. xml file

Why configure filter in the Web. xml file?
1.Filter is also a resource and will be loaded by the server, so configure it in the Web. xml file.

2. Another purpose of configuring filter in the Web. xml file is to set the filter to intercept what resources.


Example: Requirements: When the user check the automatic login box, when users log in again, automatically log in to the site.

Preparation: Simple simulation of the following page:

<%@ 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" >

<%@ page language= "java" import= "java.util.*" pageencoding= "UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" >

    filter:

public class Myfilter implements Filter {public void Destroy () {}public void DoFilter (ServletRequest request, SERVLETRESPO NSE Response,filterchain chain) throws IOException, servletexception {/** * get existuser from session * If not empty, the description is logged in and the browser is not closed , release * If an empty description is not logged in, gets the cookie of the specified name * * If the cookie is not found stating that the user does not have automatic login enabled, release * * If not empty, get the username and password from the cookie query from the database * * If not found, then the user name or password Changed, not processing release * * If found in the session, release * *///from the session to obtain the user existuserhttpservletrequest req = (httpservletrequest) request; HttpSession session = Req.getsession (); User Existuser = (user) Session.getattribute ("Existuser"), if (existuser!=null) {chain.dofilter (req, response);}        else {//is empty, stating that no login//Get specified cookie//gets the array cookie that holds the cookie []cookies =req.getcookies ();        Cookie cookie =mycookieutile.findcookiebyname (cookies, "autologin"); Determine if the cookie is empty if (cookie==null) {chain.dofilter (req, response);} else{//gets the value of the cookie, string value = Cookie.getvalue (); String username = value.split (":") [0]; String Password = value.split (":") [1];//get the username and password in the cookie to go to the database to check Userdao DAO = new Userdao (); try {User user = Dao.checkuser (username, password); if (user= =null) {Chain.dofilter (req, response);} else{//description successful, automatic login Session.setattribute ("Existuser", user);//Release Chain.dofilter (req, response);}}               catch (SQLException e) {//TODO auto-generated catch Blocke.printstacktrace ();}} }}public void init (Filterconfig filterconfig) throws servletexception {}}
       
public class Mycookieutile {/** * to find a cookie from the incoming cookie array by the incoming cookie name * If the array is empty, no return is found for null * If not empty, find return cookie * @param COO Kies * @param cookiename * @return */public static cookie Findcookiebyname (cookie []cookies,string cookiename) {if (cookies ==null) {return null;} Else{for (Cookie cookie:cookies) {//Get the name of the cookie and the name of the passed-in comparison if (Cookiename.equals (Cookie.getname ())) {//the same returns return Cookie;}} return null;}}}

servlet:

public class Loginservlet extends HttpServlet {public void doget (HttpServletRequest request, HttpServletResponse Response) throws Servletexception, IOException {/** * Receive parameters * Query database based on username and password * If successful, return to content page * If unsuccessful, return to login page continue login *///solve Chinese garbled question Title request.setcharacterencoding ("UTF-8"); String username = request.getparameter ("username"); String Password = request.getparameter ("password");//Call DAO layer query Userdao DAO = new Userdao (); try {User existuser = Dao.checku Ser (username, password), if (existuser==null) {Request.setattribute ("msg", "User name or password error"); Request.getrequestdispatcher ("/login.jsp"). Forward (request, response);} else{//Login Successful//writeback cookiestring autologin = Request.getparameter ("Autologin"); equals (AUTO_OK)) {String Value = username+ ":" +password; Cookie cookie = new Cookie ("Autologin", value);//Set valid time Cookie.setmaxage (60*60);//Set valid path Cookie.setpath ("/");// Write back to Client Response.addcookie (cookie);} Request.getsession (). SetAttribute ("Existuser", existuser);//Redirect to content page Response.sendredirect (Request.getcoNtextpath () + "/content.jsp");}} catch (SQLException e) {e.printstacktrace ();}} public void DoPost (HttpServletRequest request, httpservletresponse response) throws Servletexception, IOException { This.doget (request, Response);}}


Finally, configure filter in the Web. xml file in the configuration file. This allows the user to automatically log in to the website once they have checked in automatically and then close the browser.

When we create a filter, to rewrite the method in the interface, there is a method Dofilter, which is the method used to intercept the operation. When configuring the filter, you can specify what resources to intercept, and when the browser accesses the resource, the filter's Dofilter method performs the interception operation.

If we are in filter, its Dofilter method executes, representing the intercept operation, and if you want it to continue to access the resource down, you need to filterchain the type through the third parameter of the Dofilter method. Call its Dofilter method to complete the down operation.

Summarize:

1. The specific interception operation in filter is performed by the Dofilter method. If you want to access resources, you need to Chain.dofilter () release.
2. Intercept what resources are determined by the filter configured in the Web. xml file.



Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Filter filter for automatic 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.