struts2返回json数据的方法二 使用jackson

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/zhouhua0104/article/details/84360293
public class BaseAction extends ActionSupport {

    private static final long serialVersionUID = 4260238422873356334L;

    /**
     * 返回json数据
     * @param object
     * @return
     */
    public String jsonOut(Object object){
        ObjectMapper objectMapper=new ObjectMapper();
        try {
            String jsonString=objectMapper.writeValueAsString(object);
            HttpServletResponse response=ServletActionContext.getResponse();
            response.setContentType("text/json;charset=UTF8");
            response.getWriter().print(jsonString);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }
}
 
public class TestAction extends BaseAction {

    private String userName;

    /**
     * @return the userName
     */
    public String getUserName() {
        return userName;
    }

    /**
     * @param userName the userName to set
     */
    public void setUserName(String userName) {
        this.userName = userName;
    }

    @SuppressWarnings({ "unchecked", "rawtypes" })
    public String login() {
        Map jsonMap = new HashMap();
        if ("admin".equals(userName)) {
            jsonMap.put("msg", "登陆成功!!!");
        } else {
            jsonMap.put("msg", "登陆失败!!!");
        }

        return jsonOut(jsonMap);
    }

}
 
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
  <package name="struts" extends="struts-default" namespace="/">
   <action name="testAction" class="com.acca.action.TestAction" method="login">
   </action>
  </package>
</struts>  
 
<%@ page language="java" contentType="text/html; charset=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;">
<title>Insert title here</title>
<script type="text/javascript" src="jquery/jquery-1.7.2.min.js"></script>
<script type="text/javascript">
function doSubmit() {
    $.ajax({
    type: "post",
    data:{"userName":"admin"},
    url: "testAction",
    dataType: "json",
    cache: false,
    success: function(data) {
      $.each(data, function(key, val) {
        if (key == "msg" && val != ''){
          $("#mes").html(val);
            return false;
        }
      });
    }
  });
  }
</script>
</head>
<body>
<div id="mes"></div>
<input type="button" value="提交" οnclick="doSubmit()">
</body>
</html>
展开阅读全文

没有更多推荐了,返回首页