1. 程式人生 > >【struts2重定向】中文亂碼解決方案

【struts2重定向】中文亂碼解決方案

首先,自然是先把struts2的環境配置好,配置好之後寫struts.xml檔案:

struts.xml

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
	"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
	"http://struts.apache.org/dtds/struts-2.3.dtd">

<struts>  
	<package name="cn" namespace="/test" extends="struts-default">
		<action name="list" class="cn.action.HelloWorldAction" method="execute" >
			<result name="success" type="redirect">/employeeAdd.jsp?username=${username }</result>
		</action>               
		
	</package>
	
</struts>
 
然後,就需要在cn.action包下邊建立HelloWorldAction.java檔案:

HelloWorldAction.java

package cn.itcast.action;

import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;


public class HelloWorldAction {
	
	private String username;
	
	public String execute() throws UnsupportedEncodingException{
		this.username = URLEncoder.encode("哈嘍,世界","UTF-8");
		
		return "success"; //返回success檢視
	}

	public String getUsername() {
		return username;
	}
}

繼續在WebRoot目錄下邊建立employeeAdd.jsp檔案

employeeAdd.jsp

<%@ page language="java" import="java.util.*,java.net.URLDecoder" pageEncoding="UTF-8"%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
  </head>
  
  <body>
  <%=URLDecoder.decode(new String(request.getParameter("username").getBytes("ISO8859-1"),"UTF-8")) %>
    <form action="/xxx">
    	姓名:<input type="text" name="xxx">
    </form>
  </body>
</html>
這是struts2重定向的一個例子。