乱码问题:
>获取请求参数中的乱码问题;
>> POST请求:request.setCharacterEncoding(“utf-8”);
>>GET请求:newString(request.getParameter(“xxx”).getBytes(“iso-8859-1”), “utf-8”);
> 响应的乱码问题:response.setContextType(“text/html;charset=utf-8”)。
技术:装饰resuest,调包request
index.jep
<a href="<c:url value='/AServlet?username=张三' />">点击这里</a>
<form action="<c:url value='/AServlet' />" method="post">
用户名:<input type="text" name="username" value="李四"/><br />
<input type="submit" value="提交" />
</form>
public class AServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String username=request.getParameter("username");
response.getWriter().print(username);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=utf-8");
String username=request.getParameter("username");
response.getWriter().print(username);
}
在AFilter中,对post编码和get编码做了处理,在处理get编码时,用到了调包request
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//处理Post请求编码
request.setCharacterEncoding("utf-8");
HttpServletRequest req=(HttpServletRequest) request;
//处理get请求编码
if(req.getMethod().equals("GET")){ //注意是大写
EncodingRequest er=new EncodingRequest(req);
chain.doFilter(er, response);
}
else if(req.getMethod().equals("POST")){
chain.doFilter(request, response);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.security.Principal;
import java.util.Enumeration;
import java.util.Locale;
import java.util.Map;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletInputStream;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpSession;
public class EncodingRequest extends HttpServletRequestWrapper {
private HttpServletRequest req;
public EncodingRequest(HttpServletRequest request) {
super(request);
this.req=request; //保留底层request
// TODO Auto-generated constructor stub
}
public String getParameter(String name) {
String value=req.getParameter(name);
try {
value=new String(value.getBytes("ISO-8859-1"),"utf-8");
} catch (UnsupportedEncodingException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
return value;
}
}