一、增加依赖库
// https://mvnrepository.com/artifact/org.apache.struts/struts2-json-plugincompile group: ‘org.apache.struts‘, name: ‘struts2-json-plugin‘, version: ‘2.5.16‘
二、struts.xml配置示例
<package name="default-json" extends="json-default"> ???????<action name="hello" class="com.sanro.strutsDemo.action.HelloAction" ???????????method="execute"> ???????????<result name="success">/pages/hello.jsp</result> ???????????<result name="errLogin" type="json"> ???????????????<!-- 这里指定将被Struts2序列化的属性,该属性在action中必须有对应的getter方法 --> ???????????????<param name="root">jsonData</param> ???????????????<!-- 指定是否序列化空的属性 --> ???????????????<param name="excludeNullProperties">true</param> ???????????</result> ???????</action> ???</package>
三、action部分
???private String name; ??????????????????//GET请求参数 ???private String password; ??????????????//GET请求参数 ???private Map<String, String> jsonData; ?//响应的数据结构(由strut-json插件自动转换成json格式) ???public String execute() { ???????logger.debug("name=" + name); ???????logger.debug("pwd=" + password); ???????if ("lings".equals(name)) { ???????????return SUCCESS; ???????} else { ???????????jsonData = new HashMap<String, String>(); ???????????jsonData.put("user", name); ???????????jsonData.put("password", password); ???????????return "errLogin"; ???????} ???} ???????//略去getter和setter方法
四、请求示例
http://localhost:8080/strutsDemo/hello?name=lings&password=123
五、响应示例
{"password":"123","user":"lings"}
struts系列:返回json格式的响应
原文地址:https://www.cnblogs.com/yoyotl/p/9325976.html