向filter过滤器中的request对象添加额外的参数

有时候我们会遇到这么一些需求,在filter中获取一些参数进行处理,同时将处理好的参数重新添加到request对象中,这时候我们在filter中直接使用request.setAttribute()是无效的。我们怎么来解决这个问题呢,j2ee已经给我们提供了解决的办法,使用HttpServletRequestWrapper类来解决向request添加额外参数的功能。

环境:spring boot

新建一个类

新建一个类,这个类继承自HttpServletRequestWrapper

package com.spring.common.filter;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import java.util.HashMap;
import java.util.Map;

/**
 * com.hw.myp2c.common.filter
 * Administrator
 * 2017/10/18
 **/
public class RequestParameterWrapper extends HttpServletRequestWrapper {

    private Map<String, String[]> params = new HashMap<String, String[]>();

    public RequestParameterWrapper(HttpServletRequest request) {
        super(request);
        //将现有parameter传递给params
        this.params.putAll(request.getParameterMap());
    }

    /**
     * 重载构造函数
     * @param request
     * @param extraParams
     */
    public RequestParameterWrapper(HttpServletRequest request, Map<String, Object> extraParams) {
        this(request);
        addParameters(extraParams);
    }

    public void addParameters(Map<String, Object> extraParams) {
        for (Map.Entry<String, Object> entry : extraParams.entrySet()) {
            addParameter(entry.getKey(), entry.getValue());
        }
    }

    /**
     * 重写getParameter,代表参数从当前类中的map获取
     * @param name
     * @return
     */
    @Override
    public String getParameter(String name) {
        String[]values = params.get(name);
        if(values == null || values.length == 0) {
            return null;
        }
        return values[0];
    }

    /**
     * 同上
     * @param name
     * @return
     */
    @Override
    public String[] getParameterValues(String name) {
        return params.get(name);
    }

    /**
     * 添加参数
     * @param name
     * @param value
     */
    public void addParameter(String name, Object value) {
        if (value != null) {
            System.out.println(value);
            if (value instanceof String[]) {
                params.put(name, (String[]) value);
            } else if (value instanceof String) {
                params.put(name, new String[]{(String) value});
            } else {
                params.put(name, new String[]{String.valueOf(value)});
            }
        }
    }
}

通过建立这个类我们就能完成向request对象添加自己想要的参数了。

添加自定义参数

我们实现一个filter,这个filter实现一个功能,获取用户浏览器所访问的域名,并且将用户访问的域名构建为一个新的参数添加到request对象中去。

package com.hw.myp2c.common.filter;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;

/**
 * com.hw.myp2c.common.filter
 * Administrator
 * 2017/10/18
 **/
public class RequestFilter implements Filter {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        // dn                                   :域名
        //
        String dn = request.getServerName();
        Map<String, Object> extraParams = new HashMap<String, Object>();
        extraParams.put("dn", dn);
        //利用原始的request对象创建自己扩展的request对象并添加自定义参数
        RequestParameterWrapper requestParameterWrapper = new RequestParameterWrapper(request);
        requestParameterWrapper.addParameters(extraParams);
        filterChain.doFilter(requestParameterWrapper, servletResponse);
    }

    @Override
    public void destroy() {

    }
}

spring boot配置filter

我们在完成了添加自定义参数之后就需要在spring boot配置我们定义filter了,具体代码如下

package com.hw.myp2c;

import com.hw.myp2c.common.filter.RequestFilter;
import org.springframework.boot.builder.SpringApplicationBuilder;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.boot.web.support.SpringBootServletInitializer;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.servlet.Filter;

@Configuration
@ServletComponentScan
public class ServletInitializer extends SpringBootServletInitializer {

    @Override
    protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {
        return application.sources(Myp2cMainApplication.class);
    }

    @Bean
    public FilterRegistrationBean contextFilterRegistrationBean() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean();
        registrationBean.setFilter(requestFilter());
        registrationBean.addUrlPatterns("/");
        registrationBean.setName("requestFilter");
        registrationBean.setOrder(1);
        return registrationBean;
    }

    @Bean
    public Filter requestFilter() {
        return new RequestFilter();
    }
}

这样我们就实现了向request对象中添加我们自定义好了的参数了。

展开阅读全文

httpservletrequest中的request添加一个实例的类

03-25
重写了doPost方法,其中Student是一个学生信息类(包含set,get方法),studentDAO是一个sql处理语句方法类。我想把得到的结果Student类直接传出去,再用get方法调用,而不是先取出Student中的数据再传递数据。 所以我直接把得到的Student作为属性值添加进了request。 ``` request.setCharacterEncoding("utf-8"); int id=Integer.parseInt(request.getParameter("idd")); String name=request.getParameter("name"); String sex=request.getParameter("sex"); int age=Integer.parseInt(request.getParameter("age")); float weight=Float.parseFloat(request.getParameter("weight")); float hight=Float.parseFloat(request.getParameter("hight")); Student stu=new Student(id,name,sex,age,weight,hight); studentDAO s=new studentDAO(); Student stu2=null; try{stu2=s.find(stu); }catch(Exception e){ e.printStackTrace(); } request.setAttribute("student",stu2); request.getRequestDispatcher("/test.jsp").forward(request, response); ``` 然后在test.jsp中取出Student类: ``` <%request.setCharacterEncoding("utf-8"); Student stu=null; try{ stu=(Student)request.getAttribute("student"); if(stu!=null){out.print("1");} }catch(Exception e){ e.printStackTrace();} %> ** <%=stu.toString() %>** <table border="0" width="238" height="252"> <tr><td>学号</td><td><%=stu.getId() %></td></tr> <tr><td>姓名</td><td><%=stu.getName() %></td></tr> <tr><td>性别</td><td><%=stu.getSex() %></td></tr> <tr><td>年龄</td><td><%=stu.getAge() %></td></tr> <tr><td>体重</td><td><%=stu.getWeigth() %></td></tr> <tr><td>身高</td><td><%=stu.getHight() %></td></tr> </table> ``` 结果运行的时候出现以下错误: ``` org.apache.jasper.JasperException: An exception occurred processing JSP page /test.jsp at line 36(加粗的哪一行) Stacktrace: org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:584) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:481) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) ** servlet.find.doPost(find.java:71)** javax.servlet.http.HttpServlet.service(HttpServlet.java:648) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) root cause java.lang.NullPointerException org.apache.jsp.test_jsp._jspService(test_jsp.java:156) org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:443) org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:385) org.apache.jasper.servlet.JspServlet.service(JspServlet.java:329) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) servlet.find.doPost(find.java:71) javax.servlet.http.HttpServlet.service(HttpServlet.java:648) javax.servlet.http.HttpServlet.service(HttpServlet.java:729) org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52) note The full stack trace of the root cause is available in the Apache Tomcat/8.5.11 logs. ``` 加粗的哪一行对应: ``` request.getRequestDispatcher("/test.jsp").forward(request, response); ``` 我看到有个空指针异常,是不是因为request不能保存实例类?
©️2020 CSDN 皮肤主题: 大白 设计师: CSDN官方博客 返回首页
实付0元
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、C币套餐、付费专栏及课程。

余额充值