Struts2学习-json
Struts2 实现JSON输出有2种办法
1、把Action变成Servlet,使用传统做法
2、使用Struts 内置功能完成
二、
1.导入配置,pom.xml,要去struts2的官网下载mvnrepository.com
<dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>3.8.1</version> <scope>test</scope> </dependency> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-core</artifactId> <version>2.5.13</version> </dependency> <!-- https://mvnrepository.com/artifact/org.apache.struts/struts2-json-plugin --> <dependency> <groupId>org.apache.struts</groupId> <artifactId>struts2-json-plugin</artifactId> <version>2.5.13</version> </dependency> <!-- https://mvnrepository.com/artifact/com.google.code.gson/gson --> <dependency> <groupId>com.google.code.gson</groupId> <artifactId>gson</artifactId> <version>2.8.2</version> </dependency>
这些是配置文件的全部内容,第一个是配置好idea自动导入的;
2.一些问题
add添加,alt+enter
3.jps
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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>Insert title here</title> <script type="text/javascript" src="js/jquery-3.2.1.min.js"></script> <script type="text/javascript"> $(function(){ var MySuccess = function(result){ //alert(result); alert(result.hero); }; var MyError = function(){ alert('错误'); }; var myClick = function(){ $.ajax({ url:"testAction", type:'POST', //data: dataType:'json', success:MySuccess, timeout:3000, error:MyError }); }; $("#test01").click(myClick); }); </script> </head> <body> <div id="test01">获取服务器数据</div> </body> </html>
4.struts
<package name="mypackage" extends="struts-default,json-default"> <!--class一旦加入了spring后,就不再写具体类的路径、名字等--> <action name="testAction" class="com.nf.action.TestAction"> <!--把Action当Servlet来用,就没有result了--> </action> <action name="testAction2" class="com.nf.action.TestAction2"> <!--name="success" 可以不写--> <result type="json"> <param name="root">myJson=Map</param> </result> </action> </package>
地址:https://gitee.com/MuNianShi/user7.1.git