Java basics --- Servlet filter, basics --- servlet

Source: Internet
Author: User

Java basics --- Servlet filter, basics --- servlet

Servlet filters are literally understood as landscape-level filtering to meet the requirements of use. In fact, Servlet filters are the middle layer components of server and client requests and responses, in actual project development, Servlet filters are mainly used to filter browser requests and forward filtered requests to the next resource.

Basic concepts of filters

Filter is a new feature added after Servlet 2.3. It can be used to restrict user access to certain resources or process certain resources in advance when processing requests. A filter is bound to a WEB application in the form of a component. Unlike other WEB application components, a filter is processed in a chain. Implement a Filter in Servlet. If you want to define a Filter, you can directly implement the javax. servlet. Filter interface for a class. This interface defines three operation methods:
  • Public void init (FilterConfig filterConfig) throws ServletException
  • Public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException
  • Public void destroy ()
The main function of the FilterChain interface is to pass user requests down to other filters or Servlets:
  • Public void doFilter (ServletRequest request, ServletResponse response) throws IOException, ServletException
The same doFilter () method is still defined in the FilterChain interface, because another filter may exist behind a filter or the final target of the request (Servlet ), in this way, a "filter chain" operation is formed through FilterChain. The so-called filter chain is similar to the drum-and-teaser game played in life, defining a simple filter-SimpleFilter. java
Package com. oumyye. filter; 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; public class SimpleFilter implements Filter {public void init (FilterConfig config) throws ServletException {// initialize the Filter String initParam = config . GetInitParameter ("ref"); // obtain the initialization parameter System. out. println ("** filter initialization, initialization parameter =" + initParam);} public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, servletException {// execute the filter System. out. println ("** before executing the doFilter () method. "); Chain. doFilter (request, response); // after the System. out. println (" ** executes the doFilter () method. ");} Public void destroy () {// destroy filter System. out. println (" ** the filter is destroyed. ");}}

Configure web. xml

<Filter> <filter-name> simple </filter-name> <filter-class> com. oumyye. filter. SimpleFilter </filter-class>
<Init-param>
<Param-name> ref </param-name>
<Param-value> HELLOMLDN </param-value>
</Init-param>
</Filter>
<Filter-mapping>
<Filter-name> simple </filter-name>
<Url-pattern>/* </url-pattern>
</Filter-mapping>

Application of the filter-encoding Filtering

In WEB development, encoding filtering is an essential operation. If you follow the previous practice, repeat the "request. the setCharacterEncoding ("UTF-8") Statement is certainly not desirable, will cause a large number of code duplication, then you can complete this encoding filter through the filter.
Package com. oumyye. filter; 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; public class EncodingFilter implements Filter {private String charSet; // set the character encoding public void init (FilterConfig config) throws ServletException {this. charSet = config. getInitParameter ("charset"); // get initialization parameter} public void doFilter (ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {request. setCharacterEncoding (this. charSet); // set unified encoding} public void destroy (){
}}

Configure the web. xml file

<Filter> <filter-name> encoding </filter-name> <filter-class> com. oumyye. filter. encodingFilter </filter-class> <init-param> <param-name> charset </param-name> <param-value> UTF-8 </param-value> </init- param> </filter> <filter-mapping> <filter-name> encoding </filter-name> <url-pattern>/* </url-pattern> </filter- mapping>

Filter Application-login verification

Login verification is an indispensable part of all WEB development. The earliest practice is to verify the session, but if every page does this, it will certainly lead to a large number of code duplicates, and this repetitive operation can be avoided through the filter method. It should be noted that the session itself belongs to the scope of the HTTP protocol, but the doFilter () method defines objects of the ServletRequest type, so to get the session, then, you must perform a downward transformation to change ServletRequest to the HttpServletRequest interface object to get the session object through the getSession () method.
Package com. oumyye. filter; import javax. servlet. *; import javax. servlet. http. *; import java. io. *; import java. util. *; public class FilterLogin extends HttpServlet implements Filter {private FilterConfig filterConfig; public void init (FilterConfig filterConfig) throws ServletException {this. filterConfig = filterConfig;} public void doFilter (ServletRequest request, ServletResponse response, FilterChain fi LterChain) throws ServletException, IOException {HttpSession session = (HttpServletRequest) request ). getSession (); response. setCharacterEncoding ("gb2312"); // response client type if (session. getAttribute ("user") = null) {// determines whether the user object PrintWriter out = response exists in the session. getWriter (); // create an output stream. // if it is null, the output prompt is displayed through the javaScript script and the index is redirected. jsp page out. print ("<script language = javascript> alert ('You have not logged on !!! '); Window. location. href = '.. /index. jsp '; </script> ");} else {filterChain. doFilter (request, response); // otherwise, continue to execute.} public void destroy (){}}

User. java

package com.mr.filter;public class User {    private String username;    private String password;    public String getUsername() {        return username;    }    public String getPassword() {        return password;    }    public void setUsername(String username) {        this.username = username;    }    public void setPassword(String password) {        this.password = password;    }}

Configure web. XML

<? Xml version = "1.0" encoding = "UTF-8"?> <Web-app version = "2.5" xmlns = "http://java.sun.com/xml/ns/javaee" xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance" xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <welcome-file-list> <welcome-file> index. jsp </welcome-file> </welcome-file-list> <filter-name> filterUser </filter-name> <filter-class> com. oumyye. filter. filterLogin </filter-class> </filter> <filter-mapping> <filter-name> filterUser </filter-name> <url-pattern>/* </url-pattern> </filter-mapping> </web-app>

Jsp page:

Index. jsp

<% @ Page contentType = "text/html; charset = gb2312" language = "java" import = "java. SQL. * "errorPage =" "%> 

Loginresult. jsp

<% @ Page contentType = "text/html; charset = gb2312" language = "java" import = "java. SQL. * "%> <% @ page import =" com. mr. filter. user "%> 

Loginsuccee. jsp

<% @ Page contentType = "text/html; charset = gb2312" language = "java" import = "java. SQL. * "errorPage =" "%> <% @ page import =" com. mr. filter. user "%> 

Backtrack. jsp

<%session.invalidate();out.print("<script language='javascript'>window.location.href='../index.jsp';</script>");%>

Summary:

The filter is an automatically executed Servlet. The filter still needs to be configured in the web. xml file. A common function of the filter is to complete encoding filtering and login verification.

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.