Chapter 2 _ Request and response Decoration

Source: Internet
Author: User
12.1. decorator Mode

Even if the source code of a class does not have an object, even if the class is declared as final, the decorator mode and wrapper mode allow the object to be decorated or wrapped.

The decorator mode applies to situations where inheritance cannot be used (for example, the class of the object referred to is final), or you don't want to create an object yourself, but want to get it from another subsystem. For example, the servlet container creates a servletrequest and a servletresponse, and passes them to the servlet service method. The only way to change the behavior of servletrequest and servletresponse is to package them into other objects. The only condition that must be met is that the class of the decorated object must implement an interface and the method to be packaged must inherit from this interface.

 

12.2 servlet Wrapper class

Servlet APIs provide four classes that are rarely used, but are very powerful: servletrequestwrapper, servletresponsewrapper, and httpservletrequestwrapper and httpservletresponsewrapper.

Servletrequestwrapper is very convenient to use because it provides default implementation for every method that calls the equivalent method in the encapsulated servletrequest. Through inheritance, We have to directly implement servletrequest and provide implementation for every method in the interface.

 

12.3. Example: AutoCorrect Filter

In Web applications, users often add spaces before or after a value, or even redundant spaces between words. You do not want to check and delete unnecessary spaces in the servlet of the application one by one. The features of the AutoCorrect filter introduced in this session can help you complete these tasks. This filter contains a subclass of httpservletrequestwrapper, named autocorrecthttpservletrequestwrapper, and overwrites the following methods to return one or more parameter values: getparameter, getparametervalues, and getparametermap.

Autocorrectfilter. Java

package filter;import java.io.IOException;import java.util.ArrayList;import java.util.Collection;import java.util.HashSet;import java.util.Map;import java.util.Set;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.annotation.WebFilter;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletRequestWrapper;@WebFilter(filterName = "AutoCorrectFilter", urlPatterns = {"/*"})public class AutoCorrectFilter implements Filter{@Overridepublic void destroy() {// TODO Auto-generated method stub}@Overridepublic void init(FilterConfig arg0) throws ServletException {// TODO Auto-generated method stub}@Overridepublic void doFilter(ServletRequest request, ServletResponse response,FilterChain filterChain) throws IOException, ServletException {HttpServletRequest httpServletRequest = (HttpServletRequest)request ;AutoCorrectHttpServletRequestWrapper wrapper = new AutoCorrectHttpServletRequestWrapper(httpServletRequest) ;filterChain.doFilter(wrapper, response);}class AutoCorrectHttpServletRequestWrapper extends HttpServletRequestWrapper{private HttpServletRequest httpServletRequest ;public AutoCorrectHttpServletRequestWrapper(HttpServletRequest httpServletRequest) {super(httpServletRequest);this.httpServletRequest = httpServletRequest ;}@Overridepublic String getParameter(String name) {return autoCorrect(httpServletRequest.getParameter(name)) ;}@Overridepublic String[] getParameterValues(String name) {// TODO Auto-generated method stubreturn autoCorrect(httpServletRequest.getParameterValues(name));}@Overridepublic Map<String, String[]> getParameterMap() {// TODO Auto-generated method stubfinal Map<String, String[]> parameterMap = httpServletRequest.getParameterMap() ;Map<String, String[]> newMap = new Map<String, String[]>(){@Overridepublic int size() {return parameterMap.size();}@Overridepublic boolean isEmpty() {return parameterMap.isEmpty();}@Overridepublic boolean containsKey(Object key) {return parameterMap.containsKey(key);}@Overridepublic boolean containsValue(Object value) {return parameterMap.containsValue(value);}@Overridepublic String[] get(Object key) {return autoCorrect(parameterMap.get(key));}@Overridepublic String[] put(String key, String[] value) {return parameterMap.put(key, value);}@Overridepublic String[] remove(Object key) {return parameterMap.remove(key);}@Overridepublic void putAll(Map<? extends String, ? extends String[]> m) {parameterMap.putAll(m);}@Overridepublic void clear() {parameterMap.clear();}@Overridepublic Set<String> keySet() {return parameterMap.keySet();}@Overridepublic Collection<String[]> values() {return autoCorrect(parameterMap.values());}@Overridepublic Set<java.util.Map.Entry<String, String[]>> entrySet() {return autoCorrect(parameterMap.entrySet());}} ;return newMap ;}} private String autoCorrect(String value){if(value == null){return null ;}value = value.trim() ;int length = value.length() ;StringBuilder temp = new StringBuilder() ;boolean lastCharWasSpace = false ;for(int i = 0; i<length; i++){char c = value.charAt(i) ;if(c == ' '){if(!lastCharWasSpace){temp.append(c) ;}lastCharWasSpace = true ;}else{temp.append(c) ;lastCharWasSpace = false ;}}return temp.toString() ;}private String[] autoCorrect(String[] values){if(values != null){int length = values.length ;for(int i=0; i<length; i++){values[i] = autoCorrect(values[i]) ;}return values ;}return null ;}@SuppressWarnings("unused")private Collection<String[]> autoCorrect(Collection<String[]> valueCollection){Collection<String[]> newCollection = new ArrayList<String[]>() ;for(String[] values : valueCollection){newCollection.add(autoCorrect(values)) ;}return newCollection ;}private Set<Map.Entry<String, String[]>> autoCorrect(Set<Map.Entry<String, String[]>> entrySet){Set<Map.Entry<String, String[]>> newSet = new HashSet<Map.Entry<String, String[]>>() ;for(final Map.Entry<String, String[]> entry : entrySet){Map.Entry<String, String[]> newEntry = new Map.Entry<String, String[]>() {@Overridepublic String getKey() {return entry.getKey();}@Overridepublic String[] getValue() {return autoCorrect(entry.getValue());}@Overridepublic String[] setValue(String[] value) {return entry.setValue(value);}};newSet.add(newEntry) ;}return newSet ;}}

Test1.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">Test2.jsp

<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">

Running result:



Chapter 2 _ Request and response Decoration

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.