如何自定义HttpServletRequest、HttpServletResponse?

如何自定义一个HttpServletRequest呢?

比如spring mvc,我们通常写成

@RequestMapping(value = "/helloworld", method = RequestMethod.GET)
public ModelAndView test(HttpServletRequest req, HttpServletResponse res) {
   return new ModelAndView("index.jsp");
}

一直在想,能不能不用HttpServletRequest、和HttpServletResponse 呢?最终给我研究出来了下面的写法。

@RequestMapping(value = "/helloworld", method = RequestMethod.GET)
public ModelAndView test(WebRequest req, WebResponse res) {
    return new ModelAndView("index.jsp");
}

其实就是filter、拦截器, 着象了。

public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
    HttpServletRequest httpRequest = (HttpServletRequest) request;
    if(!(httpRequest instanceof WebRequest))
    {
        httpRequest = new WebRequest(httpRequest);
    }
    HttpServletResponse httpResponse = (HttpServletResponse) response;
    if(!(httpResponse instanceof WebResponse))
    {
        httpResponse = new WebResponse(httpResponse);
    }
    filterChain.doFilter(httpRequest, httpResponse);
}

原理就是在web.xml里自定义一个拦截器,拦截所有url并把httpservletrequest交给ServletRequest。

private ServletRequest request;

public ServletRequestWrapper(ServletRequest request) {
    if(request == null) {
        throw new IllegalArgumentException("Request cannot be null");
    } else {
        this.request = request;
    }
}

附上代码好了(各位可以直接粘贴-哈哈-我的最爱):

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

    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

    <!-- 设置Spring容器加载配置文件路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring-*.xml</param-value>
    </context-param>

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>

    <filter>
        <filter-name>interceptAllFilter</filter-name>
        <filter-class>com.test.filter.RequestFilter</filter-class>
    </filter>

    <filter-mapping>
        <filter-name>interceptAllFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>Test</groupId>
  <artifactId>test</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>com.test Maven Webapp</name>
  <url>http://maven.apache.org</url>
    <dependencies>
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.6</version>
        </dependency>

        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>4.0.1.RELEASE</version>
            <type>jar</type>
        </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-core</artifactId>
        <version>4.0.1.RELEASE</version>
        <type>jar</type>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>4.0.1.RELEASE</version>
        <type>jar</type>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context-support</artifactId>
        <version>4.0.1.RELEASE</version>
      </dependency>

      <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>4.0.1.RELEASE</version>
      </dependency>

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
    </dependencies>

  <build>
    <finalName>test</finalName>
      <pluginManagement>
          <plugins>
              <plugin>
                  <groupId>org.apache.tomcat.maven</groupId>
                  <artifactId>tomcat6-maven-plugin</artifactId>
                  <version>2.2</version>
              </plugin>
              <plugin>
                  <groupId>org.apache.tomcat.maven</groupId>
                  <artifactId>tomcat7-maven-plugin</artifactId>
                  <version>2.2</version>
              </plugin>
          </plugins>
      </pluginManagement>
  </build>
</project>

WebRequest.java

/**
 * Created by shaoyongyang on 2015/6/5.
 */
package com.test.core;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;

public class WebRequest extends HttpServletRequestWrapper {

    public WebRequest(HttpServletRequest request) {
        super(request);
    }
}

WebResponse.java

/**
 * Created by shaoyongyang on 2015/6/5.
 */
package com.test.core;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

public class WebResponse extends HttpServletResponseWrapper {

    public WebResponse(HttpServletResponse response) {
        super(response);
    }
}

RequestFilter.java

/**
 * Created by shaoyongyang on 2015/6/5.
 */
package com.test.filter;

import com.test.core.WebRequest;
import com.test.core.WebResponse;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class RequestFilter implements Filter {
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest httpRequest = (HttpServletRequest) request;
        if(!(httpRequest instanceof WebRequest))
        {
            httpRequest = new WebRequest(httpRequest);
        }

        HttpServletResponse httpResponse = (HttpServletResponse) response;
        if(!(httpResponse instanceof WebResponse))
        {
            httpResponse = new WebResponse(httpResponse);
        }
        filterChain.doFilter(httpRequest, httpResponse);
    }

    public void destroy() {

    }
}

TestController.java

/**
 * Created by shaoyongyang on 2015/6/5.
 */
package com.test.action;

import com.alibaba.fastjson.JSONObject;
import com.test.core.WebRequest;
import com.test.core.WebResponse;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;

@Controller
public class TestController{

    @RequestMapping(value = "/helloworld", method = RequestMethod.GET)
    public ModelAndView test(WebRequest req, WebResponse res) {
        return new ModelAndView("index.jsp");
    }
}

springmvc-servlet.xml 位于WEB-INF

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
   xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:util="http://www.springframework.org/schema/util"  
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
   xsi:schemaLocation="http://www.springframework.org/schema/beans 
   http://www.springframework.org/schema/beans/spring-beans-3.0.xsd 
   http://www.springframework.org/schema/context 
   http://www.springframework.org/schema/context/spring-context-3.0.xsd 
   http://www.springframework.org/schema/mvc 
   http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd
   http://www.springframework.org/schema/util        
    http://www.springframework.org/schema/util/spring-util-3.0.xsd">

    <mvc:annotation-driven />
    <!-- 自动扫描controller包下的所有类,使其认为spring mvc的控制器 -->
   <context:component-scan base-package="com.test.action" />
</beans>

代码拷贝的多了,其实关键的还是在上头。在RequestFilter里面。

maven项目可直接 mvn tomcat:run

参考了github上一位外国老兄写的代码、附上地址:https://github.com/surenrao/nsr-bookstore/tree/1a7e56d306819e9939d9d67bd12ee2043e8997ce/java/bookstore-web

时间: 2024-10-09 15:00:26

如何自定义HttpServletRequest、HttpServletResponse?的相关文章

“The code of method _jspService(HttpServletRequest, HttpServletResponse) is exceeding the 65535 bytes limit” 的我之解決办法 (转)

“The code of method _jspService(HttpServletRequest, HttpServletResponse) is exceeding the 65535 bytes limit” 的我之解決辦法 - 兔子吃南瓜 - 博客频道 - CSDN.NET http://blog.csdn.net/rabbiteatpumpkin/article/details/4743104 昨天,我遇到了一个让我很头疼的问题. 我做了一个共通的jsp,单只测它是ok的,可是,放在

HttpServletRequest /HttpServletResponse

一.HttpServletRequest接口     定义     public   interface   HttpServletRequest   extends   ServletRequest;     用来处理一个对Servlet的HTTP格式的请求信息.     方法     1.getAuthType     public   String   getAuthType();     返回这个请求的身份验证模式.     2.getCookies     public   Cooki

【明哥报错簿】之【 &quot;javax.servlet.http.HttpServlet&quot; was not found on the Java Build Path || HttpServletRequest/HttpServletResponse cannot be resolved to a type】

The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path login.jsp /day12_estore/WebRoot line 1 JSP Problem 解决: 1. 我们遇到的错误显示如下: 2.我们右击有错误提示的文件夹,如下: 3.我们点击"配置构建路径",如下: 4.我们再点击"添加库",如下: 5.我们选中上图中标出的选

The code of method _jspService(HttpServletRequest, HttpServletResponse) is exceeding the 65535 bytes limit

解法: 修改tomcat下的web.xml,     搜索:JspServlet, 增加: <init-param> <param-name>mappedfile</param-name> <param-value>false</param-value> </init-param>

HttpServletRequest/HttpServletResponse乱码问题解决

1.request.setCharacterEncoding只对POST请求起作用.GET请求用new String(paramterData.getBytes("iso8859-1"),"UTF-8"); 2.response.setContentType指定HTTP 响应的编码,同时指定了浏览器显示的编码. 等价于response.setCharacterEncoding指定HTTP 响应的编码和response.setHeader("contentT

自定义httpservletrequest解析参数

3.添加参数解析器 4.注册 原文地址:https://www.cnblogs.com/a1304908180/p/12066973.html

14SpringMvc_在业务控制方法中写入HttpServletRequest,HttpServletResponse等传统web参数(这个知识点知道就好了,不推荐这么去做)

这篇文章解决的问题是怎么在业务方法里面引入我们熟悉的HttpServletRequest和HttpServletRespon? 答案:这种引入传统的web参数的做法不推荐去做,因为这么做会实行高度耦合. 但还是说一下这种做法: 在Action修改代码如下: package com.guigu.shen.Action7; import java.io.IOException; import javax.servlet.http.HttpServletRequest; import javax.se

[原创]java WEB学习笔记45:自定义HttpFilter类,理解多个Filter 代码的执行顺序,Filterdemo:禁用浏览器缓存的Filter,字符编码的Filter,检查用户是否登陆过的Filter

本博客为原创:综合 尚硅谷(http://www.atguigu.com)的系统教程(深表感谢)和 网络上的现有资源(博客,文档,图书等),资源的出处我会标明 本博客的目的:①总结自己的学习过程,相当于学习笔记 ②将自己的经验分享给大家,相互学习,互相交流,不可商用 内容难免出现问题,欢迎指正,交流,探讨,可以留言,也可以通过以下方式联系. 本人互联网技术爱好者,互联网技术发烧友 微博:伊直都在0221 QQ:951226918 ---------------------------------

自定义简单的(tomcat)web服务器

自从JSP发布之后,推出了各式各样的JSP引擎.Apache Group在完成GNUJSP1.0的开发以后,开始考虑在SUN的JSWDK基础上开发一个可以直接提供Web服务的JSP服务器,当然同时也支持Servlet, 这样Tomcat就诞生了.Tomcat是jakarta项目中的一个重要的子项目,其被JavaWorld杂志的编辑选为2001年度最具创新的java产品,同时它又是sun公司官方推荐的servlet和jsp容器,因此其越来越多的受到软件公司和开发人员的喜爱.servlet和jsp的