Struts2---->中文乱码

1、<form action="user!add" method="post"> 必表单提交方法必须为post,如果是get就出错

Action1.java

package com.ncepu.struts2;

public class Action1 {

	private String name;
	private String password; //传递参数的时候  用的是方法 而不是赋给属性,
	                       //所以说将password改成userpassword下面方法setPassword不变也可以。	                       

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String add() {
		
        System.out.println("添加的name="+name+"添加的password="+password);
		return ("success");
	}

}

struts.xml

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

<struts>
	<constant name="struts.devMode" value="true" />
	<package name="default" namespace="/" extends="struts-default">
		<action name="user" class="com.ncepu.struts2.Action1">
			<result name="success">
				/add.jsp
            </result>
		</action>
	</package>
</struts>

index.jsp

<body>
			<!--必须为post-->
		<form action="user!add" method="get">
			姓名2
			<input type="text" name="name">
			密码1
			<input type="text" name="password">
			<input type="submit" value="submit" />
		</form>
	</body>

后台输出为:添加的name=°?????·?添加的password= °?·??÷

解决方法:
1、必须将<form action="user!add" method="post"> 必表单提交方法必须为post才正确。

2、对请求参数重新编码(参照http://blog.csdn.net/ncepustrong/article/details/7927027)

String name = new String(request.getParameter("name").getBytes("ISO8859-1"));
String password= new String(request.getParameter("password").getBytes("ISO8859-1"));

在此使用到了request,必须得到。

package com.ncepu.struts2;

import java.io.UnsupportedEncodingException;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts2.ServletActionContext;

import com.opensymphony.xwork2.ActionSupport;

public class Action1 extends ActionSupport {

	private static final long serialVersionUID = 1L;
	HttpServletRequest request;
	private String name;
	private String password; // 传递参数的时候 用的是方法 而不是赋给属性,

	// 所以说将password改成userpassword下面方法setPassword不变也可以。

	public String getName() {
		return name;
	}

	public Action1() {
		request = ServletActionContext.getRequest();

	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String add() throws UnsupportedEncodingException {
		name = new String(request.getParameter("name").getBytes("ISO8859-1"));
		password = new String(request.getParameter("password").getBytes("ISO8859-1"));
		System.out.println("添加的name=" + name + "添加的password=" + password);
		return ("success");
	}

}


 

 

posted on 2012-08-30 17:07  小强斋太  阅读(242)  评论(0编辑  收藏  举报

导航