过滤器实现字符编码
2020-11-23 本文已影响0人
Jianbaozi
image.png
image.png
image.png
image.png
image.png
CharactorFilter
package com.baozi;
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;
public class CharactorFilter implements Filter {
private String encoding=null;
public void init(FilterConfig fConfig) throws ServletException {
encoding=fConfig.getInitParameter("encoding");
}
public CharactorFilter() {
// TODO Auto-generated constructor stub
}
public void destroy() {
encoding=null;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding(encoding);
response.setContentType("text/html;charset="+encoding);
chain.doFilter(request, response);
}
}
AddServlet
package com.baozi;
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 AddServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public AddServlet() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request,response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
String id=request.getParameter("id");
String name=request.getParameter("name");
String author=request.getParameter("author");
String price=request.getParameter("price");
out.print("<h2>图书信息添加成功</h2><hr>");
out.print("图书编号:"+id+"<br>图书名称:"+name+"<br>图书作者:"+author+"<br> 图书价格:"+price);
}
}