Java Web---Login verification and character encoding filters

Source: Internet
Author: User

What is a filter?

In the Java Web, filters are filter. A filter interface (Javax.servlet.Filter) is provided in the Servlet API, and if you are developing a Web application, if you write a Java class that implements this interface, this Java class is called filter filter. Filter technology enables developers to intercept requests and responses to access before they access a target resource. Simply put, it is possible to implement a Web container for the pre-access interception of a resource before processing it, or to intercept a resource before it returns a response to the Web container.

Steps to create a filter

1. Create a filter processing class (implement Javax.servlet.Filter interface)
2. Configure the filter in the Web. xml file

Filter execution Process

1.Filter preprocessing of user requests
2. Submit the request to the servlet for processing and generate a response after processing
3. Last filter to post-process the server response

Character encoding Filters

Characterfilter.java

 PackageOrg. Labreserve.filter;ImportJava.io.IOException;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;ImportJavax.servlet.ServletException;ImportJavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse; Public  class characterfilter implements Filter {   //Implement filter interface    PrivateString character;//Save the type of character encoding    @Override     Public void Destroy() {//Before the filter is destroyed, the recovery of some resources is completed}@Override     Public void DoFilter(ServletRequest servletrequest, Servletresponse servletresponse, Filterchain filterchain)throwsIOException, servletexception {servletrequest.setcharacterencoding ("Utf-8");//You can set the encoding directlyServletresponse.setcharacterencoding (character);//can also read initialization parameters characterFilterchain.dofilter (ServletRequest, servletresponse);//Go to next filter}@Override     Public void Init(Filterconfig FC)throwsservletexception {//completion of initialization of the filter        //Read the initialization parameters of the filter configuration in Web. XMLcharacter = Fc.getinitparameter ("character"); }}

Configuration in the Web. xml file

<!--define a filter --    <filter>        <!--filter name--        <filter-name>Characterfilter</filter-name>        <!--Filter Implementation class--        <filter-class>Org. LabReserve.filter.CharacterFilter</filter-class>        <!--initialization parameters --        <init-param>            <!--parameter names --            <param-name>Character</param-name>            <!--parameter value, encoded as Utf-8--            <param-value>Utf-8</param-value>        </init-param>    </filter>    <!--define a filter to intercept the URL address--    <filter-mapping>        <!--filter name--        <filter-name>Characterfilter</filter-name>        <!--to intercept the URL, here is all blocked--        <url-pattern>/*</url-pattern>    </filter-mapping>
Login Verification Filter

Loginfilter.java

 PackageOrg. Labreserve.filter;ImportJava.io.IOException;ImportJavax.servlet.Filter;ImportJavax.servlet.FilterChain;ImportJavax.servlet.FilterConfig;ImportJavax.servlet.ServletException;ImportJavax.servlet.ServletRequest;ImportJavax.servlet.ServletResponse;ImportJavax.servlet.http.HttpServletRequest;ImportJavax.servlet.http.HttpServletResponse;ImportJavax.servlet.http.HttpSession; Public  class loginfilter implements Filter {    @Override     Public void Destroy() {    }@Override     Public void DoFilter(ServletRequest servletrequest, Servletresponse servletresponse, Filterchain filterchain)throwsIOException, Servletexception {//Convert to HTTP Request ObjectHttpServletRequest request = (httpservletrequest) servletrequest;//Translate to HTTP response objectHttpServletResponse response = (httpservletresponse) servletresponse;//Get the Session object corresponding to the requestHttpSession session = Request.getsession ();//Get the URI of the user requestString path = Request.getrequesturi ();//Do not verify login filtered pagesString[] Nocheckpages = {"index.jsp","findpassword.jsp","Loginservlet","Userservlet","CSS","Images","JS"};//int indexOf (int ch) returns the index of the specified character at the first occurrence of this string. If not found, return-1         for(inti =0; i < nocheckpages.length; ++i) {if(Path.indexof (Nocheckpages[i]) >-1) {//Go to next filterFilterchain.dofilter (ServletRequest, servletresponse);return;//No more filtering to prevent page redirection loops}        }//If session is NULL, the user is the first time to access        if(Session.getattribute ("UserId") !=NULL|| Session.getattribute ("Teacherid") !=NULL|| Session.getattribute ("Adminid") !=NULL) {//Go to next filterFilterchain.dofilter (request, response); }Else{//Redirect to homepageResponse.sendredirect ("index.jsp");return;//No more filtering to prevent page redirection loops}    }@Override     Public void Init(Filterconfig arg0)throwsServletexception {}}

Web. xml file Configuration

<filter>        <filter-name>LoginFilter</filter-name>        <filter-class>org.LabReserve.filter.LoginFilter</filter-class>    </filter>    <filter-mapping>        <filter-name>LoginFilter</filter-name>        <url-pattern>/*</url-pattern>    </filter-mapping>

Reference Link: http://lavasoft.blog.51cto.com/62575/275586/
Http://www.cnblogs.com/lyp3314/archive/2012/11/03/2752097.html

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

Java Web---Login verification and character encoding filters

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.