访问URL传递参数 一般有2种方式:post 、get
无论是JSP提交表单到servlet还是action还是其它 或者 a标签指定URL传递参数 出现的乱码问题可以按照访问方式来解决
1.对于POST访问方式可以设置过滤器过滤字符
----举个栗子----对访问根目录下的所有JSP页面之前设置字符过滤器,指定过滤后的编码为”UTF-8“
package com.smxy.lxz.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;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
/**
* Servlet Filter implementation class CharacterFilter
*/
@WebFilter(
urlPatterns="/*",
initParams={@WebInitParam(name="encoding",value="UTF-8")}
)
public class CharacterFilter implements Filter {
private String encoding;
/**
* Default constructor.
*/
public CharacterFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
System.out.println("CharacterFilter->doFilter");
if(encoding!=null){
request.setCharacterEncoding(encoding);
response.setContentType("text/html; charset="+encoding);
}
// pass the request along the filter chain
chain.doFilter(request, response);
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
encoding = fConfig.getInitParameter("encoding");
}
}
2.对于GET访问方式可以根据提交之前的编码和提交之后的编码进行互相转码
----举个栗子----假设提交方式是GET,且提交之前或者提交之后要默认的编码为 ”ISO8859-1“,而要设置的编码为“UTF-8” 则在获取参数前加如下代码
String username = new String(user.getUsername().getBytes("ISO8859-1"),"UTF-8");