Filterpost請求中文字符編碼的過濾器 --學習筆記
阿新 • • 發佈:2018-04-19
post請求中文字符編碼的過濾器java代碼:
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 LoginServlet1 extends HttpServlet { public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //request.setCharacterEncoding("utf-8"); String username = request.getParameter("username"); String passwrod = request.getParameter("passwrod"); //顯示 response.getWriter().write("用戶名 :"+username); response.getWriter().write("密碼:"+passwrod); } }
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; public class FilterDemo3 implements Filter { private FilterConfig filterConfig; public FilterDemo3() { } public void init(FilterConfig filterConfig) throws ServletException { this.filterConfig = filterConfig; } //Web容器調用 public void doFilter(ServletRequest request, ServletResponse response,FilterChain chain) throws IOException, ServletException { String encoding = filterConfig.getInitParameter("encoding"); //POST請求編碼設置 request.setCharacterEncoding(encoding); //響應編碼設置 response.setContentType("text/html;charset="+encoding); chain.doFilter(request,response); } public void destroy() { } }
login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>登陸頁面</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> <!-- <link rel="stylesheet" type="text/css" href="styles.css"> --> </head> <body> <form action="/day04/LoginServlet1" method="post"> <table border="1" align="center"> <caption>用戶登陸</caption> <tr> <th>用戶名</th> <td><input type="text" name="username"/> </td> </tr> <tr> <th>用戶密碼</th> <td><input type="password" name="passwrod"/> </td> </tr> <tr> <td colspan="5" align="center"> <input type="submit" value="提交"/> </td> </tr> </table> </form> </body> </html>
web.xml
<filter>
<filter-name>FilterDemo3</filter-name>
<filter-class>cn.web.servlet.filter.FilterDemo3</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>FilterDemo3</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
Filterpost請求中文字符編碼的過濾器 --學習筆記