jsp頁面中文在web項目正常,在瀏覽器輸出亂碼

這種情況應該是沒設置請求和響應的編碼(只針對post請求有效,對get請求無效,下面再說get請求的)

		//設置請求的字符集編碼
		request.setCharacterEncoding("UTF-8");
		//設置響應的字符集編碼
		response.setContentType("text/html;charset=UTF-8");

例子:

<!--index.jsp-->
<%@ page language="java" import="java.util.*,java.text.*" pageEncoding="UTF-8" errorPage="error.jsp"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<%!	public String getDateStr(){
		SimpleDateFormat simpleDateFormat =new SimpleDateFormat("yyyy-MM-dd HH:mm:ss E");
		String strDate = simpleDateFormat.format(new Date());
		return strDate;
	} %>
<!DOCTYPE HTML>
<html>
  <head>
       <base href="<%=basePath%>">
    <title>My JSP 'index.jsp' starting page</title>
  </head>
  
  <body>
    	現在的日期時間:<%=getDateStr() %>
    	<form action="test.do" name="myform" method="post">
    	輸入要傳遞的信息:<input type="text" name="info"/>
    	<input type="submit" value="確定">
    	</form>
  </body>
</html>
//TestServlet
package servlets;

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 TestServlet extends HttpServlet {

	private static final long serialVersionUID = 1L;

	@Override
	protected void service(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		// TODO Auto-generated method stub
		//設置請求的字符集編碼
		request.setCharacterEncoding("UTF-8");
		
		System.out.println("請求到達服務端...");
		
		//接收客戶端的請求數據;
		String info=request.getParameter("info");
		System.out.println("服務端收到客戶端的數據:"+info);
		
		
		//設置響應的字符集編碼
		response.setContentType("text/html;charset=UTF-8");
		//將接收的消息,以響應的方式輸出到客戶端
		PrintWriter out =response.getWriter();
		out.println("info:"+info);
		//釋放資源
		out.flush();
		out.close();
	}

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <display-name>web_01</display-name>
  
  <servlet>
  	<servlet-name>TestServlet</servlet-name>
  	<servlet-class>servlets.TestServlet</servlet-class>
  </servlet>
  
  <servlet-mapping>
  		<servlet-name>TestServlet</servlet-name>
  		<url-pattern>/test.do</url-pattern>
  </servlet-mapping>
  
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

對於get請求,這種方法無效,可以採用以下:

在本機上找到Tomcat的安裝目錄 conf目錄下的server.xml文件,打開

找到下面這段,加上URIEncoding="UTF-8"

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章