关闭

解决中文乱码

309人阅读 评论(0) 收藏 举报

package com.hygj.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class FilterServlet extends HttpServlet implements Filter {
  private FilterConfig filterConfig;
  //Handle the passed-in FilterConfig
  public void init(FilterConfig filterConfig) {
    this.filterConfig = filterConfig;
  }
  //Process the request/response pair
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) {
    try {
      //一次性解决所有叶面的中文问题
      //System.out.println("filter");
      //request.setCharacterEncoding("gb2312");
      filterChain.doFilter(request, response);
    }
    catch(ServletException sx) {
      filterConfig.getServletContext().log(sx.getMessage());
    }
    catch(IOException iox) {
      filterConfig.getServletContext().log(iox.getMessage());
    }
  }
  //Clean up resources
  public void destroy() {
  }
}

---------------------

package com.hygj.servlet;

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;

public class LoginServlet extends HttpServlet {
  private static final String CONTENT_TYPE = "text/html;charset=gb2312";
  //Initialize global variables
  public void init() throws ServletException {
  }
  //Process the HTTP Get request
  public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    //解决出的乱码
    response.setContentType(CONTENT_TYPE);
    PrintWriter out = response.getWriter();
    //解决请求中的乱码
    //request.setCharacterEncoding("GB2312");
    String user=request.getParameter("user");
    String pwd=request.getParameter("pwd");
    //通过字符串的重新格式化的方式解决乱麻
    user=new String(user.getBytes("ISO-8859-1"),"GB2312");
    pwd=new String(pwd.getBytes("ISO-8859-1"),"GB2312");


    System.out.println(user);
    System.out.println(pwd);
    out.println("<html>");
    out.println("<head><title>LoginServlet</title></head>");
    out.println("<body bgcolor=/"#ffffff/">");
    out.println("<p>The servlet has received a " + request.getMethod() + ". This is the reply.</p>");
    out.print("这是我的servlet");
    out.println("</body></html>");
  }
  //Process the HTTP Post request
  public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    doGet(request, response);
  }
  //Clean up resources
  public void destroy() {
  }
}

 
0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:3326次
    • 积分:91
    • 等级:
    • 排名:千里之外
    • 原创:6篇
    • 转载:0篇
    • 译文:0篇
    • 评论:0条
    文章分类
    文章存档