在页面建个表单
<form action="login.do" method="post">
<input type="text" name="username" />
<input type="submit" value="确定" />
</form>
建个servlet
web.xml
<servlet>
<servlet-name>LoginServlert</servlet-name>
<servlet-class>servlet.LoginServlert</servlet-class>
</servlet> <servlet-mapping>
<servlet-name>LoginServlert</servlet-name>
<url-pattern>/login.do</url-pattern>
</servlet-mapping>
package servlet; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class LoginServlert extends HttpServlet {
public LoginServlert() {
super();
}
public void destroy() {
super.destroy();
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String username = request.getParameter("username");
System.out.println("获取的username:>>>>>>"+username);
}
public void init() throws ServletException {
}
}
后台情况是这样的:
乱码了.
可以通过过滤器来解决
新建一个过滤器EncodingFilter.java
package 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.http.HttpServletRequest; public class EncodingFilter implements Filter{
private String encoding = "";
private String filterName = ""; public void init(FilterConfig filterConfig) throws ServletException {
encoding = filterConfig.getInitParameter("encoding");
filterName = filterConfig.getFilterName();
if (encoding == null || "".equals(encoding)) {
encoding = "UTF-8";
}
System.out.println("获得编码值......"); } public void doFilter(ServletRequest request, ServletResponse res,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request;
System.out.println("请求被" + filterName + "过滤了.......");
// 分别对请求和响应进行编码设置
request.setCharacterEncoding(encoding);
res.setCharacterEncoding(encoding);
chain.doFilter(req, res);
System.out.println("响应被被" + filterName + "过滤了.......");
} public void destroy() {
System.out.println("请求被销毁......");
}
}
在web.xml中配置filter
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>filter.EncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
跑起来:
正常了.
我们换在地址栏里输入汉字,看看是否乱码.
结果是这样的
过滤器不起作用了,怎么办.
其实request.setCharacterEncoding(encoding);只对消息体中的数据起作用,对url中的参数不起作用了.
对上面的过滤器进行优化.
编写RequestEncodingWrapper.java
package filter; import java.io.UnsupportedEncodingException; import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper; public class RequestEncodingWrapper extends HttpServletRequestWrapper {
private String encoding = ""; public RequestEncodingWrapper(HttpServletRequest request) {
// 必须调用父类构造方法
super(request);
}
public RequestEncodingWrapper(HttpServletRequest request,String encoding){
// 必须调用父类构造方法
super(request);
this.encoding=encoding;
} @Override
public String getParameter(String name) {
String value=getRequest().getParameter(name);
try {
//将参数值进行编码转换
if(value!=null&&!"".equals(value)){
value=new String(value.trim().getBytes("iso-8859-1"),encoding);
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
return value;
} }
优化EncodingFilter.java后
package 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.http.HttpServletRequest; public class EncodingFilter implements Filter {
private String encoding = "";
private String filterName = ""; public void init(FilterConfig filterConfig) throws ServletException {
encoding = filterConfig.getInitParameter("encoding");
filterName = filterConfig.getFilterName();
if (encoding == null || "".equals(encoding)) {
encoding = "UTF-8";
}
System.out.println("获得编码值......"); } public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletRequest req=(HttpServletRequest)request;
System.out.println("请求被" + filterName + "过滤了.......");
if("GET".equals(req.getMethod())){
req=new RequestEncodingWrapper(req,encoding);
}else {
request.setCharacterEncoding(encoding);
}
// 分别对请求和响应进行编码设置
response.setCharacterEncoding(encoding);
chain.doFilter(req, response);
System.out.println("响应被被" + filterName + "过滤了.......");
} public void destroy() {
System.out.println("请求被销毁......");
} }
好了.
Filter接口有三个方法:
init(FilterConfig filterConfig) 初始化过滤器,filterConfig参数可以得到过滤器初始化的配置参数信息.
doFilter(ServletRequest request, ServletResponse res,FilterChain chain)
request表示客户端的请求,rewponse表示对应请求的响应,chain是过滤器对象,.在该方法中的特定过滤器完成后,
可调用doFilter请求传给过滤器中的下一个过滤器,也可以直接返回响应内容,还可以将目标重定向.
destroy():释放过滤器中使用的资源.
参数FilterConfig filterConfig有四个方法:
public String getFilterName() 得到过滤器的名字
public String getInitParameter(String name) 得到过滤器中初始化的参数值.
publi Enumeration getInitParameterNames() 得到过滤器配置中的所有初始化参数名字的枚举类型.
publi ServletContext getServlet() 得到Servlet上下文对象.
说完了请求,我们再来说说响应.
我们经常需要在向浏览器输出内容时,过滤一些敏感词汇.
新建一个内容替换的封装器ResponseReplaeWrapper.java
package filter; import java.io.CharArrayWriter;
import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper; public class ResponseReplaeWrapper extends HttpServletResponseWrapper {
private CharArrayWriter charWriter = new CharArrayWriter();
public ResponseReplaeWrapper(HttpServletResponse response){
//必须调用父类构造方法
super(response);
}
public PrintWriter getWriter() throws IOException{
//返回字符数组Writer,缓存内容
return new PrintWriter(charWriter);
}
public CharArrayWriter getCharWriter(){
return charWriter;
} }
过滤器:
package filter; import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Properties; 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.HttpServletResponse; public class ReplaceFilter implements Filter {
private Properties propert = new Properties(); public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("ReplaceFilter init....."); // 通过filterConfig获得初始胡文件名
String filePath = filterConfig.getInitParameter("filePath");
try {
// 导入资源文件
propert.load(ReplaceFilter.class.getClassLoader()
.getResourceAsStream(filePath)); } catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
} public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
HttpServletResponse res = (HttpServletResponse) response;
// 实例化响应器包装类
ResponseReplaeWrapper resp = new ResponseReplaeWrapper(res);
chain.doFilter(request, resp);
// 缓存输出字符
String outString = resp.getCharWriter().toString();
// 循环替换不合法的字符
for (Object o : propert.keySet()) {
String key = (String) o;
outString = outString.replace(key, propert.getProperty(key));
}
// 利用原先的HttpServletResponse输出字符
PrintWriter out = res.getWriter();
out.write(outString);
} public void destroy() {
System.out.println("ReplaceFilter destroy......");
} }
在web.xml中配置过滤器
<filter>
<filter-name>ReplaceFilter</filter-name>
<filter-class>filter.ReplaceFilter</filter-class>
<init-param>
<param-name>filePath</param-name>
<param-value>/replace_ZH.properties</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>ReplaceFilter</filter-name>
<url-pattern>*.do</url-pattern>
</filter-mapping>
在src下新建配置文件replace_ZH.properties
建个测试的servlet
package servlet; import java.io.IOException;
import java.io.PrintWriter; import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse; public class ResponseServlet extends HttpServlet {
public ResponseServlet() {
super();
} public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
} public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.println("思思博士<br/>色情<br/>赌博<br/>dfdffddf");
/*out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");*/
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException { response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
} public void init() throws ServletException {
} }