(jsp与servlet)解决乱码问题的方式

 1 package fengke.servlet;
 2 
 3 import java.io.IOException;
 4 import java.io.PrintWriter;
 5 
 6 import javax.servlet.ServletException;
 7 import javax.servlet.http.HttpServlet;
 8 import javax.servlet.http.HttpServletRequest;
 9 import javax.servlet.http.HttpServletResponse;
10 /**
11  * 解决乱码问题的方式
12  * @author 锋客
13  *
14  */
15 public class Character extends HttpServlet {
16 
17     public void doGet(HttpServletRequest request, HttpServletResponse response)
18             throws ServletException, IOException {
19 
20         response.setContentType("text/html");
21         this.doPost(request, response);
22     }
23 
24     
25     public void doPost(HttpServletRequest request, HttpServletResponse response)
26             throws ServletException, IOException {
27         
28         response.setContentType("text/html");
29         /*1.采用设置字符集的方式 
30          * request.setCharacterEncoding("utf-8");
31          */
32         /*2.设置过滤器 ====CoreFilter.java
33          *   配置web.xml
34          */
35         /*
36          * 3.采用转码的方式
37          * String s = new String(request.getParameter("c").getBytes("ISO8859-1"),"UTF-8");  
38          */
39         
40         String s = request.getParameter("c");
41         System.out.println(s);
42     }
43 
44     
45 }
 1 <%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
 2 
 3 <%
 4 String path = request.getContextPath();
 5 String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
 6 %>
 7 
 8 <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
 9 <html>
10   <head>
11     <base href="<%=basePath%>">
12     
13     <title>My JSP 'index.jsp' starting page</title>
14     <meta http-equiv="pragma" content="no-cache">
15     <meta http-equiv="cache-control" content="no-cache">
16     <meta http-equiv="expires" content="0">    
17     <meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
18     <meta http-equiv="description" content="This is my page">
19     <!--
20     <link rel="stylesheet" type="text/css" href="styles.css">
21     -->
22   </head>
23   <!-- 解决乱码问题 -->
24   <body>
25     <table>
26     <form action="Character" method="post" >
27     <tr>
28     <td><input type="text" name="c" value="中国"></td>
29     <td><input type="submit" value="提交"></td>
30     </tr>
31     </form>
32     </table>
33   </body>
34 </html>
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 3   <display-name>Character</display-name>
 4   <servlet>
 5     <description>This is the description of my J2EE component</description>
 6     <display-name>This is the display name of my J2EE component</display-name>
 7     <servlet-name>Character</servlet-name>
 8     <servlet-class>fengke.servlet.Character</servlet-class>
 9   </servlet>
10 
11   <servlet-mapping>
12     <servlet-name>Character</servlet-name>
13     <url-pattern>/Character</url-pattern>
14   </servlet-mapping>
15   <welcome-file-list>
16     <welcome-file>index.html</welcome-file>
17     <welcome-file>index.htm</welcome-file>
18     <welcome-file>index.jsp</welcome-file>
19     <welcome-file>default.html</welcome-file>
20     <welcome-file>default.htm</welcome-file>
21     <welcome-file>default.jsp</welcome-file>
22   </welcome-file-list>
23   <!--  
24   <filter>  
25    <filter-name>encodingFilter</filter-name>  
26       <filter-class>fengke.filter.CoreFilter</filter-class>  
27     <init-param>  
28        <param-name>encoding</param-name>  
29        <param-value>utf-8</param-value>  
30     </init-param>  
31    </filter>  
32       
33    <filter-mapping>  
34       <filter-name>encodingFilter</filter-name>  
35           <url-pattern>/*</url-pattern>  
36       </filter-mapping>  
37       -->
38 </web-app>
package fengke.filter;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
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.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;


//过滤器处理表单传到servlet的乱码问题
public class CoreFilter implements Filter{
    //自写一个request换掉原来的request,重写里面的getParemeter方法,可以设置编码
    class MyRequest extends HttpServletRequestWrapper{
        
        @Override
        public String getParameter(String param) {
            String value = null;
            try {
                //post
                super.setCharacterEncoding(encoding);//把编码转换为encoding
                value = super.getParameter(param);
                if(super.getMethod().equalsIgnoreCase("GET")){
                    if(value!=null){
                        value = new String(value.getBytes("iso8859-1"),encoding);
                    }
                }
            } catch (UnsupportedEncodingException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
            return value;
        }

        public MyRequest(HttpServletRequest request) {
            super(request);
        }
        
    }
    protected String encoding=null; 
    public void destroy() { //销毁
        // TODO Auto-generated method stub
        this.encoding=null;
    }
   //对编码问题进行转换
    public void doFilter(ServletRequest request, ServletResponse response,
            FilterChain chain) throws IOException, ServletException {
        // TODO Auto-generated method stub
        response.setContentType("text/html;charset="+encoding);
        //过滤未登录用户
        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        String path=req.getServletPath();
        String param=req.getQueryString();
        if(path!=null){
            path=path+"?"+param;//全请求路径
        }
        if(path.endsWith("myAddress")||path.endsWith("myJingDong")||path.indexOf("myShouCang")!=-1||path.endsWith("updateUser")||path.indexOf("showOrder")!=-1||path.indexOf("showValidOrder")!=-1||path.indexOf("showCancelOrder")!=-1||path.indexOf("fillOrder")!=-1){
            HttpSession session = req.getSession();
            String userName = (String) session.getAttribute("username");
            if(userName == null){
                session.setAttribute("url", path.replaceFirst("/", ""));
                System.out.println(session.getAttribute("url"));
                resp.sendRedirect("user.do?op=loginAction");
                return;
            }
        }
        //把过滤器给下一个过滤器或资源处理器
        chain.doFilter(new MyRequest((HttpServletRequest) request), response); 
    }

    public void init(FilterConfig filterConfig) throws ServletException {
        // TODO Auto-generated method stub
        this.encoding=filterConfig.getInitParameter("encoding");//encoding在web.xml中指定
    }

}
原文地址:https://www.cnblogs.com/fengke/p/4800269.html