Java Web Filter Login Verification

Source: Internet
Author: User

First do the site need to login verification, turn from: http://blog.csdn.net/daguanjia11/article/details/48995789Filter:

Filter is a server-side component that is used to filter Web requests. When a Web request occurs, the Web container first checks that the requested URL has a filter set, and if so, executes the Dofilter method of the filter. All filter implements the Javax.servlet.Filter interface, and Dofilter is the most important method defined in the interface.

The most common examples of using filters are: Login access page validation, error logging, encoding conversion, and so on.

You can also set multiple filters on a URL, which will form a filter chain, and the process of filtering the chain is actually a chain of responsibility mode.

Login Verification Sample Code

Today I use a verification login example, so that you have a preliminary understanding of filter (filter). This example contains a index.jsp page, a login.jsp page, and a loginfilter. I specify in the configuration file that Loginfilter is used for index.jsp, and when the user accesses the index.jsp page, redirects to login.jsp to sign in if they are not logged in.

Add a index.jsp page

The code is as follows:

<%@ page language="Java" contenttype="Text/html; Charset=utf-8 "pageencoding="UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" ><Html><head>< meta http-equiv= "Content-Type" Span class= "Hljs-attribute" >content=<title>insert title here </title></ head><body> <h1> Welcome to Home </ h1></body> </HTML>         
Add a login.jsp page
<%@ page language="Java" contenttype="Text/html; Charset=utf-8 "pageencoding="UTF-8"%><! DOCTYPE HTML PUBLIC "-//w3c//dtd HTML 4.01 transitional//en" "HTTP://WWW.W3.ORG/TR/HTML4/LOOSE.DTD" ><Html><head>< meta http-equiv= "Content-Type" Span class= "Hljs-attribute" >content=<title>insert title here </title></ head><body> <h1> please login </ h1></body> </HTML>         
Add a Loginfilter class

Add a new Loginfilter class, implement the Javax.servlet.Filter interface, verify in the Dofilter method whether the session contains the username attribute, or redirect to login.jsp if it is not included. The code is as follows:

Package com.zdk.test;Import java.io.IOException;Import Javax.servlet.Filter;Import Javax.servlet.FilterChain;Import Javax.servlet.FilterConfig;Import javax.servlet.ServletException;Import Javax.servlet.ServletRequest;Import Javax.servlet.ServletResponse;Import Javax.servlet.http.HttpServletRequest;Import Javax.servlet.http.HttpServletResponse;Import javax.servlet.http.HttpSession;PublicClassLoginfilterImplementsFilter {@OverridePublicvoidDestroy () {}@OverridePublicvoid dofilter (ServletRequest request, servletresponse response , Filterchain chain) throws IOException, servletexception {httpservletrequest httpRequest= (httpservletrequest) Request; HttpServletResponse httpresponse= (httpservletresponse) response; HttpSession session=httprequest.getsession (); if (Session.getattribute ( "username")! = null) {Chain.dofilter (request, response);} else{Httpresponse.sendredirect (Httprequest.getcontextpath () +  "/login.jsp"); }}  @Override public void init (filterconfig arg0) throws servletexception {}}   
Configure Filter

In Web. XML, apply Loginfilter to the index.jsp page

<?xml version= "1.0" encoding= "UTF-8"?><Web-appXmlns:xsi="Http://www.w3.org/2001/XMLSchema-instance"xmlns="Http://java.sun.com/xml/ns/javaee"xsi:schemalocation="Http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0" ><Display-name>helloworld</Display-name><Welcome-file-list><Welcome-file>index.html</Welcome-file><Welcome-file>index.htm</Welcome-file><welcome-file>index.jsp</Welcome-file><Welcome-file>default.html</Welcome-file><Welcome-file>default.htm</Welcome-file><welcome-file>default.jsp</Welcome-file></Welcome-file-list><Filter><Filter-name>loginfilter</filter-name> <filter-class>com.zdk.test.loginfilter</filter-class> </filter> <filter-mapping> <filter-name>loginfilter</  Filter-name> <url-pattern>/index.jsp</url-pattern> </  filter-mapping></web-app>           

Then, publish the site, start Tomcat, enter localhost:8080:{projectname}/index.jsp in the browser, and replace {projectname} with the project name of your Web projet. The page will be redirected to login.jsp because we cannot read the login information on the index.jsp page.

Using loginfilter for multiple pages

If it goes well, our loginfilter has been able to finish the work here. But we can not only one page login verification, it is not possible to all the pages are login verification, how to set it flexibly?

We want to modify the scope of the login verification and login verification for all pages except login.jsp,page2.jsp. First, we modify the Web. xml

<Filter><Filter-name>loginfilter</Filter-name><Filter-class>com.zdk.test.loginfilter</Filter-class><Init-param><param-name>passurl</param-name > <param-value>login.jsp;page2.jsp; </param-value> </init-param > </filter> < filter-mapping> <filter-name> Loginfilter</filter-name> << Span class= "Hljs-title" >url-pattern>/*</url-pattern> Span class= "Hljs-tag" ></FILTER-MAPPING>       

We specified a passurl parameter for Loginfilter and then set the Url-pattern of the filter to/*. This means that Loginfilter will be used for all requests except those written in Passurl. Of course, the logic of neglect requires our own implementation. The following is the modified Loginfilter class

Package com.zdk.test;Import java.io.IOException;Import Javax.servlet.Filter;Import Javax.servlet.FilterChain;Import Javax.servlet.FilterConfig;Import javax.servlet.ServletException;Import Javax.servlet.ServletRequest;Import Javax.servlet.ServletResponse;Import Javax.servlet.http.HttpServletRequest;Import Javax.servlet.http.HttpServletResponse;Import javax.servlet.http.HttpSession;PublicClassLoginfilterImplementsFilter {@OverridePublicvoidDestroy () {} String Passurl ="";@OverridePublicvoidDoFilter (ServletRequest request, servletresponse response, Filterchain chain)Throws IOException, servletexception {httpservletrequest HttpRequest = (httpservletrequest) request; HttpServletResponse HttpResponse = (httpservletresponse) response; string[] Strarray = Passurl.split (";");for (String Str:strarray) {if (Str.equals (continue; if (Httprequest.getrequesturl (). indexOf (str) >= 0) { Chain.dofilter (request, response); return;} } HttpSession session = Httprequest.getsession (); if (Session.getattribute ( "username")! = null) {Chain.dofilter (request, response);} else {httpresponse.sendredirect (Httprequest.getcontextpath () +  "/login.jsp"); }}  @Override public void init (filterconfig arg0) throws servletexception {passUrl = Arg0.getinitparameter ( "Passurl");}} 

first read the Passurl we set in the Init method and save it to the variable. If the URL of the current request is contained in Passurl, it is not checked for login.

Java Web Filter Login Verification

Related Article

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.