<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="disp.jsp"> <!-- 相当于使用get -->
<input type="text" name="info">
<input type="submit" value="submit">
</form>
</body>
</html>
display.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://www.mldn.cn/jst/core" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%=request.getParameter("info") %>
</body>
</html>
我使用了filter,代码如下:
package org.lxh.filterdemo; import java.io.IOException;
import java.nio.charset.Charset; 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 CharacterEncodingFilter implements Filter {
protected String encoding = null;
protected FilterConfig filterConfig = null;
protected boolean enable = false;
public void destroy() {
this.encoding = null;
this.filterConfig = null;
}
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
if (this.enable) {
String encoding = this.selectEncoding(request);
if (encoding != null && !encoding.equals("")) {
System.out.println("~~" + this + ": request :" + encoding);
request.setCharacterEncoding(encoding); //Overrides the name of the character encoding used in the body of this request. This method must be called prior to reading request parameters or reading input using getReader().
// response.setCharacterEncoding(encoding); // 暂时不太清楚
}
}
// Pass control on to the next filter
chain.doFilter(request, response);
if (this.enable) {
String encoding = this.selectEncoding(request);
if (encoding != null && !encoding.equals("")) {
System.out.println("~~" + this + ": response :" + encoding);
response.setCharacterEncoding(encoding);
}
}
}
public void init(FilterConfig filterConfig) throws ServletException {
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding");
if (!Charset.isSupported(encoding)) {
encoding = null;
}
String enableString = filterConfig.getInitParameter("enable");
if (enableString.equalsIgnoreCase("true")) {
this.enable = true;
} else {
this.enable = false;
}
}
protected String selectEncoding(ServletRequest request) {
return (this.encoding);
}
}
filter开启,但是仍然有乱码问题,把method="post"添加上就好了
主要的问题在于对get和post理解的不透彻: