看到别人用了Struts2和JSON,自己也想练练手。记录下练习过程中遇到的问题,以便参考。
使用Maven新建项目:
先挂上pom.xml
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.sk</groupId>
<artifactId>struts</artifactId>
<packaging>war</packaging>
<version>0.0.1-SNAPSHOT</version>
<name>struts Maven Webapp</name>
<url>http://maven.apache.org</url>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>3.8.1</version>
<scope>test</scope>
</dependency>
<!-- Log -->
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.0-beta7</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.0-beta7</version>
</dependency> <!-- Struts2 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-core</artifactId>
<version>2.3.1.2</version>
</dependency>
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts-taglib</artifactId>
<version>1.3.10</version>
</dependency> <!-- servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency> <!-- JSON LIB -->
<dependency>
<groupId>net.sf.json-lib</groupId>
<artifactId>json-lib</artifactId>
<version>2.2.3</version>
<classifier>jdk15</classifier>
</dependency>
<!-- 如果缺少这个插件的话机会报: Unable to find parent packages json-default 这个错误折磨了我大半天,后来自己仔细看看tomcate启动日志发现了这个错误,经查询,是缺少了
struts2-json-plugin-2.1.8.1.jar 这个包,因为struts2默认是以插件形式进行加载的,所以是少加载的json处理的包。加入这个包运行正常。如果没有这个包的话。
运行时会报There is no Action mapped for namespace·······所有的Action都不能运行。 -->
<dependency>
<groupId>org.apache.struts</groupId>
<artifactId>struts2-json-plugin</artifactId>
<version>2.3.15</version>
</dependency> </dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.0</version>
<configuration>
<source>1.7</source>
<target>1.7</target>
</configuration>
</plugin>
</plugins>
</build> </project>
再整个VO:User.java
package com.sk.struts2.bean; import java.io.Serializable; public class User implements Serializable { private String id;
private String username;
private String pwd;
// 省略setter和getter
}
然后是action:JSONAction.java
package com.sk.struts2.action; import net.sf.json.JSONObject; import com.opensymphony.xwork2.ActionSupport;
import com.sk.struts2.bean.User; public class JSONAction extends ActionSupport { private static final long serialVersionUID = -795596058695827298L; private User user;
private String jsonString; @Override
public String execute() throws Exception {
JSONObject jsonObject = null;
if(user != null){
jsonObject = JSONObject.fromObject(user);
jsonString = jsonObject.toString();
System.out.println(jsonString);
}
return SUCCESS;
} public User getUser() {
return user;
} public void setUser(User user) {
this.user = user;
} public String getJsonString() {
return jsonString;
} public void setJsonString(String jsonString) {
this.jsonString = jsonString;
} }
接着是View:json.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="ISO-8859-1"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Hello World!</title>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript" src="<%= request.getContextPath() %>/resources/js/json.js"></script>
</head>
<body>
<form>
ID:<input type="text" name="user.id"/><br />
username:<input type="text" name="user.username"/><br />
pwd:<input type="text" name="user.pwd"/> <input id="btn" type="button" value="submit" />
</form> <h2>Here is result:</h2>
<div id="result"></div>
</body>
</html>
还有JS:json.js
$(function(){
$('#btn').click(function(){
var params=$("input").serialize();
var actionPath = getRootPath() + "/jsonTest/jsonAction"; $.ajax({
url: actionPath,
// 数据发送方式
type: "post",
// 接受数据格式
dataType : "json",
// 要传递的数据
data : params,
// 回调函数,接受服务器端返回给客户端的值,即result值
success : show
}).always(function(){alert('done');});
});
}); function show(result){
//测试result是否从服务器端返回给客户端
//alert(result);
//解析json对象
var json = eval("("+result+")");
var obj = "编号: "+json.id+" 用户名: "+json.username+" 密码: "+json.pwd;
$("#result").html(obj);
} //js获取项目根路径,如: http://localhost:8083/uimcardprj
function getRootPath(){
//获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp
var curWwwPath=window.document.location.href;
//获取主机地址之后的目录,如: uimcardprj/share/meun.jsp
var pathName=window.document.location.pathname;
var pos=curWwwPath.indexOf(pathName);
//获取主机地址,如: http://localhost:8083
var localhostPaht=curWwwPath.substring(0,pos);
//获取带"/"的项目名,如:/uimcardprj
var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
return(localhostPaht+projectName);
}
最后奉上: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="test" namespace="/jsonTest" extends="json-default">
<action name="jsonAction" class="com.sk.struts2.action.JSONAction">
<result type="json">
<!-- 此处将reslut的值返回给客户端,root的值对应要返回的值的属性result.注意:root为固定写法,否则不会把result的值返回给客户端 -->
<param name="root">jsonString</param>
</result>
</action>
</package> </struts>
ok,all done.下面测试哈:
最后给个目录结构:
OK.Enjoy!