zoukankan      html  css  js  c++  java
  • servlet乱码 解决方法 2种方法

    
    
    public class ResponseDemo1 extends HttpServlet {
    	public  void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    		test1(resp);
    	}
    
      
      //方法1: public void test1(HttpServletResponse resp) throws IOException, UnsupportedEncodingException { resp.setHeader("Content-type", "text/html;charset=utf-8"); String data = "中国"; OutputStream output = resp.getOutputStream(); //程序以什么编码输出,那么一定要设置浏览为相对应的编码打开. output.write(data.getBytes("utf-8")); }   //方法2: //模拟meta标签,设置charset为utf-8,这个方法也行. //用html技术中的meta标签模拟了一个http响应头,来控制浏览器的行为 public void test2(HttpServletResponse response) throws Exception{ String data = "中国_第二个"; OutputStream output= response.getOutputStream(); output.write("<meta http-equiv='content-type' content='text/html;charset=UTF-8'>".getBytes()); output.write(data.getBytes()); }
    public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException { doGet(req, resp); } }

     //********************************情况2:*************************************

    public class ResponseDemo2 extends HttpServlet {
    	private static final long serialVersionUID = 1L;
    
    	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		test1(response);
    
    	}
    
    	public void test1(HttpServletResponse response) throws IOException {
    		// 方法1:
    		// 要设置response,所使用的码表,以控制reponse以什么码表向浏览器写入数据
    		// response.setCharacterEncoding("utf-8");
    		// 同时设置浏览器以何种码表打开,指定浏览以什么 码表打开服务器发送的数据 
    		// response.setHeader("content-type", "text/html;charset=utf-8");
    		//  方法2:
    		response.setContentType("text/html;charset=utf-8");
    
    		String data = "中国";
    		PrintWriter outputStream = response.getWriter();
    		outputStream.write(data);
    	}
    
    	public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    		doGet(request, response);
    
    	}
    
    }
    
  • 相关阅读:
    Maven中的依赖相关总结
    Redis(序)应用场景
    Java并发专栏(一)—— Process vs Thread
    Java中转换为二进制的几种实现
    Java中转换为十六进制的几种实现
    oracle日期格式和java日期格式区别 HH24:mm:ss和HH24:mi:ss的区别
    远程教学的一些准备
    将latex的beamer做的幻灯片转换为ppt格式后的一些问题
    最近看过的雨课堂和智慧树的笔记
    关于在线授课的探索
  • 原文地址:https://www.cnblogs.com/amosli/p/3315961.html
Copyright © 2011-2022 走看看