Struts2+JSON+JQUERY DEMO

看到别人用了Struts2和JSON,自己也想练练手。记录下练习过程中遇到的问题,以便参考。

使用Maven新建项目:

先挂上pom.xml

 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2     xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 3     <modelVersion>4.0.0</modelVersion>
 4     <groupId>com.sk</groupId>
 5     <artifactId>struts</artifactId>
 6     <packaging>war</packaging>
 7     <version>0.0.1-SNAPSHOT</version>
 8     <name>struts Maven Webapp</name>
 9     <url>http://maven.apache.org</url>
10     <dependencies>
11         <dependency>
12             <groupId>junit</groupId>
13             <artifactId>junit</artifactId>
14             <version>3.8.1</version>
15             <scope>test</scope>
16         </dependency>
17         <!-- Log -->
18         <dependency>
19             <groupId>org.apache.logging.log4j</groupId>
20             <artifactId>log4j-api</artifactId>
21             <version>2.0-beta7</version>
22         </dependency>
23         <dependency>
24             <groupId>org.apache.logging.log4j</groupId>
25             <artifactId>log4j-core</artifactId>
26             <version>2.0-beta7</version>
27         </dependency>
28 
29         <!-- Struts2 -->
30         <dependency>
31             <groupId>org.apache.struts</groupId>
32             <artifactId>struts2-core</artifactId>
33             <version>2.3.1.2</version>
34         </dependency>
35         <dependency>
36             <groupId>org.apache.struts</groupId>
37             <artifactId>struts-taglib</artifactId>
38             <version>1.3.10</version>
39         </dependency>
40 
41         <!-- servlet -->
42         <dependency>
43             <groupId>javax.servlet</groupId>
44             <artifactId>servlet-api</artifactId>
45             <version>2.5</version>
46         </dependency>
47 
48         <!-- JSON LIB -->
49         <dependency>
50             <groupId>net.sf.json-lib</groupId>
51             <artifactId>json-lib</artifactId>
52             <version>2.2.3</version>
53             <classifier>jdk15</classifier>
54         </dependency>
55         <!-- 如果缺少这个插件的话机会报: Unable to find parent packages json-default 这个错误折磨了我大半天,后来自己仔细看看tomcate启动日志发现了这个错误,经查询,是缺少了 
56             struts2-json-plugin-2.1.8.1.jar 这个包,因为struts2默认是以插件形式进行加载的,所以是少加载的json处理的包。加入这个包运行正常。如果没有这个包的话。 
57             运行时会报There is no Action mapped for namespace·······所有的Action都不能运行。 -->
58         <dependency>
59             <groupId>org.apache.struts</groupId>
60             <artifactId>struts2-json-plugin</artifactId>
61             <version>2.3.15</version>
62         </dependency>
63 
64 
65 
66 
67     </dependencies>
68     <build>
69         <plugins>
70             <plugin>
71                 <groupId>org.apache.maven.plugins</groupId>
72                 <artifactId>maven-compiler-plugin</artifactId>
73                 <version>3.0</version>
74                 <configuration>
75                     <source>1.7</source>
76                     <target>1.7</target>
77                 </configuration>
78             </plugin>
79         </plugins>
80     </build>
81 
82 </project>

再整个VO:User.java

 1 package com.sk.struts2.bean;
 2 
 3 import java.io.Serializable;
 4 
 5 public class User implements Serializable {
 6 
 7     private String id;
 8     private String username;
 9     private String pwd;
10         // 省略setter和getter
11 }

然后是action:JSONAction.java

 1 package com.sk.struts2.action;
 2 
 3 import net.sf.json.JSONObject;
 4 
 5 import com.opensymphony.xwork2.ActionSupport;
 6 import com.sk.struts2.bean.User;
 7 
 8 public class JSONAction extends ActionSupport {
 9 
10     private static final long serialVersionUID = -795596058695827298L;
11     
12     private User user;
13     private String jsonString;
14 
15     @Override
16     public String execute() throws Exception {
17         JSONObject jsonObject = null;
18         if(user != null){
19             jsonObject = JSONObject.fromObject(user);
20             jsonString = jsonObject.toString();
21             System.out.println(jsonString);
22         }
23         return SUCCESS;
24     }
25 
26     public User getUser() {
27         return user;
28     }
29 
30     public void setUser(User user) {
31         this.user = user;
32     }
33 
34     public String getJsonString() {
35         return jsonString;
36     }
37 
38     public void setJsonString(String jsonString) {
39         this.jsonString = jsonString;
40     }
41     
42 }

接着是View:json.jsp

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="ISO-8859-1"%>
 3 <%@ taglib prefix="s" uri="/struts-tags" %>
 4 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 5 <html>
 6 <head>
 7 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 8 <title>Hello World!</title>
 9 <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
10 <script type="text/javascript" src="<%= request.getContextPath() %>/resources/js/json.js"></script>
11 </head>
12 <body>
13     <form> 
14         ID:<input type="text" name="user.id"/><br />
15         username:<input type="text" name="user.username"/><br />
16         pwd:<input type="text" name="user.pwd"/>
17         
18         <input id="btn" type="button" value="submit" />
19     </form> 
20     
21     <h2>Here is result:</h2>
22     <div id="result"></div>
23 </body>
24 </html>

还有JS:json.js

 1 $(function(){
 2     $('#btn').click(function(){
 3         var params=$("input").serialize();
 4         var actionPath = getRootPath() + "/jsonTest/jsonAction";
 5         
 6         $.ajax({
 7             url: actionPath,
 8             // 数据发送方式
 9             type: "post",
10             // 接受数据格式
11             dataType : "json",
12             // 要传递的数据
13             data : params,
14             // 回调函数,接受服务器端返回给客户端的值,即result值
15             success : show   
16         }).always(function(){alert('done');});
17     });
18 });
19 
20 function show(result){
21     //测试result是否从服务器端返回给客户端
22     //alert(result);
23     //解析json对象
24     var json = eval("("+result+")");
25     var obj = "编号: "+json.id+"  用户名: "+json.username+"  密码: "+json.pwd;
26     $("#result").html(obj);
27 }
28 
29 //js获取项目根路径,如: http://localhost:8083/uimcardprj
30 function getRootPath(){
31     //获取当前网址,如: http://localhost:8083/uimcardprj/share/meun.jsp
32     var curWwwPath=window.document.location.href;
33     //获取主机地址之后的目录,如: uimcardprj/share/meun.jsp
34     var pathName=window.document.location.pathname;
35     var pos=curWwwPath.indexOf(pathName);
36     //获取主机地址,如: http://localhost:8083
37     var localhostPaht=curWwwPath.substring(0,pos);
38     //获取带"/"的项目名,如:/uimcardprj
39     var projectName=pathName.substring(0,pathName.substr(1).indexOf('/')+1);
40     return(localhostPaht+projectName);
41 }

最后奉上:struts.xml

 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
 4     "http://struts.apache.org/dtds/struts-2.0.dtd">
 5 
 6 <struts>
 7 
 8     <constant name="struts.devMode" value="true" />
 9     
10     <package name="test" namespace="/jsonTest" extends="json-default">
11         <action name="jsonAction" class="com.sk.struts2.action.JSONAction">
12             <result type="json">
13                 <!-- 此处将reslut的值返回给客户端,root的值对应要返回的值的属性result.注意:root为固定写法,否则不会把result的值返回给客户端 -->
14                 <param name="root">jsonString</param>
15             </result>
16         </action>
17     </package>
18 
19 </struts>

ok,all done.下面测试哈:

最后给个目录结构:

OK.Enjoy!

posted @ 2013-08-15 13:57  daveztong  阅读(821)  评论(0编辑  收藏  举报