Java 前台后台数据传递、中文乱码解决方法

时间:2023-03-08 15:43:10

1.向前台传递数据;
2.向后台传递数据;
3.ajax post 提交数据到服务端时中文乱码解决方法;
4.数组类型参数传递;

1.向前台传递数据:
1.1 字符串数据传递:
  这种方式只是单一的向前台传递字符串(比如传递ajax 请求某个数据的结果),通过 response 实现;
 1.1.1 Action 类:

 public String getResult(){
HttpServletResponse response=ServletActionContext.getResponse();
response.setContentType("text/html;charset=GBK");//解决中文乱码
PrintStream out=null; //流
try {
out = new PrintStream(response.getOutputStream());
out.print("向前台传递一个字符串结果");
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally{
out.flush();
out.close();
}
return null; //最后返回null
}

1.1.2 struts 配置文件:

 <action name="testAction" class="testAction" method="getResult">
<result name="success"></result> <!-- 这里不用填写什么 -->
</action>

1.2 对象数据传输:
  对象数据通常是已json 格式传输,在 struts2 配置文件内引入 json-default(普通json 格式) 包或者 jackson-json-default(加强型json格式,在返回的json数据中包含对象类型,类似这样的结果("_javaType_":"com.action.TestAction");可以根据业务情况选用,随着业务系统的庞大,我一般用javascript 在前台绑定数据,这样当涉及到判断数据类型时就可以采用这个字段的值来处理:
1.2.1 Action 类:

     List<Student> lsStudent; //lsStudent 属性要有get\set方法
/**
* 根据班级ID 获得该班级的学生信息
* return 班级所有学生信息
*/
public String getStudentByClassId(){ HttpRequest request=ServletActionContext.getRequest();
String classId=request.getParameter("classId"); //班级ID /*
*这里的判断很容易出错,如果你用(id!=null)做判断条件,当没有获得值时,id 是一个空的String对象,空对象不能做判断,这就好像你在Java类中这样写代码: String tb;
if(tb==null||tb==""){// 错误:The local variable tb may not have been initialized
System.out.println(tb);
}
*/
if(null!=id ||!"".equals(id)){
lsStudent=TestStudent.getStudentById(id);
} return SUCCESS;
}

1.2.1 struts 配置文件:

   <action name="testAction" class="testAction" method="getResult">
<result name="success" type="strongtype-json">
<param name="root">
lsStudent <!-- 这里返回action 中要返回的对象(一定要有get/set方法) -->
</param>
</result>
</action>

最终前台会得到这样的json数据:

 [{"__javaType__":"com.base.Student","name":"张三","age":"10","homeAddr":null,"stuNum":0,"classNum":0},{"__javaType__":"com.base.Student","name":"李四","age":"20","homeAddr":null,"stuNum":0,"classNum":0}]      

1.2.3 前台js获得json数据:

    $.ajax({
type:"post",
url:"testAction.action",
data:{
classId:classId
},
success:function(rs){
var studentArray=[]; //前台创建个数组对象保存数据
$.each(rs,function(i,item){
var student;
student.name=item.name;
student.id=item.id;
student.age=item.age;
studentArray.push(student); //将student 对象信息保存到数组对象中
});
},
error:function(){
alert("获取数据时发生错误");
}
});

3.ajax post 提交数据到服务端时中文乱码解决方法:
  get 方式提交数据到服务端不会乱码,但对数据量有限制;post 可以提交大数据量,但中文会发生乱码,解决方法:
在JS上用使用 encodeURIComponent 对字符编码处理:

  studentRuselt=encodeURIComponent(JSON.stringify(result),"utf-8"); //这里用了json2 来将对象转换为json格式,然后在用encodeURIComponent来设置编码;

  $.ajax({
type:"post",
url:"saveExamQuestionAnswer.action",
cache:true,
async:true, //这里指定值时不能加双引号(会设置无效)
contentType: "application/x-www-form-urlencoded; charset=utf-8",
data: {
studentRuselt: studentRuselt
}
)};

Action类上用java.net.URLDecoder.URLDecoder.decode方法转码:

studentRuselt=URLDecoder.decode(studentRuselt,"UTF-8");    

这样得到的中文不会乱码,还有另外一个js组件:encodeURI也可以对字符进行处理,提交时它会使用jquery默认编码提交数据,但使用encodeURIComponent 组件指定编码,细节清晰,前台后台处理编码一致这样比较稳妥;

4.数组类型参数传递:
 若一个请求中包含多个值,如:(test.action?tid=1&tid=2&tid=3),参数都是同一个,只是指定多个值,这样请求时后台会发生解析错误,应先使用 tradititonal 格式化:

 $.ajax({
type:"post",
url:"test.action",
data:{
tid:[1,2,3]
},
traditional:true });