Java Web 怎样修改request的参数值
1个回答
2016-05-13
展开全部
用过滤器就可以实现,现在web.xml文件中配置好过滤器,自定义个一个过滤器,实现Filter接口,在doFilter中实现自己的过滤逻辑,我这里有个设置所有请求中的字符编码,你可以参考一下:
Java code
web.xml配置如下:
<filter>
<!--过滤器名称,随便定义-->
<filter-name>UrlFilter</filter-name>
<!--filter-class指向自定义的过滤器,完整的包名+类名-->
<filter-class>
com.wgh.common.SetCharacterEncodingFilter
</filter-class>
<!--过滤器中的默认参数,默认的字符编码是GBK-->
<init-param>
<param-name>defaultEncoding</param-name>
<param-value>GBK</param-value>
</init-param>
</filter>
<!--filter和filter-mapping是成对出现的-->
<filter-mapping>
<!--过滤器名称,一定要和上面的一样,-->
<filter-name>UrlFilter</filter-name>
<!--表示拦截所有的请求-->
<url-pattern>/*</url-pattern>
</filter-mapping>
SetCharacterEncodingFilter过滤器类:
package com.wgh.common;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.List;
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.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SetCharacterEncodingFilter implements Filter {
private static String log = "ksURL_log";
private static String web_xml_url;
protected static String defaultEncoding = null;
protected FilterConfig filterConfig = null;
protected boolean ignore = true;
public void destroy() {
this.defaultEncoding = null;
this.filterConfig = null;
this.web_xml_url = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (ignore || (request.getCharacterEncoding() == null)) {
String defaultEncoding = selectEncoding(request);
HttpServletRequest req = (HttpServletRequest) request;
if (defaultEncoding != null){
String uri = req.getRequestURI();
String url_suffix = uri.substring(uri.lastIndexOf("/")+1);
request.setCharacterEncoding(defaultEncoding);
}
}
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.defaultEncoding = filterConfig.getInitParameter("defaultEncoding");
String value = filterConfig.getInitParameter("ignore");
if (value == null)
this.ignore = true;
else if (value.equalsIgnoreCase("true"))
this.ignore = true;
else if (value.equalsIgnoreCase("yes"))
this.ignore = true;
else
this.ignore = false;
}
protected String selectEncoding(ServletRequest request) {
return (this.defaultEncoding);
}
}
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询