struts2,实现Ajax异步通信
生活随笔
收集整理的這篇文章主要介紹了
struts2,实现Ajax异步通信
小編覺得挺不錯的,現(xiàn)在分享給大家,幫大家做個參考.
用例需要依賴的jar:
用例代碼如下:
- 數(shù)據(jù)庫DDL語句
?無
- struts.xml
- java類
action類
BaseAction.java
1 package test.util; 2 import java.io.IOException; 3 import java.io.StringWriter; 4 import java.io.Writer; 5 import java.util.HashMap; 6 import java.util.Map; 7 import javax.servlet.ServletContext; 8 import javax.servlet.http.HttpServletRequest; 9 import javax.servlet.http.HttpServletResponse; 10 import org.apache.log4j.Logger; 11 import org.apache.struts2.ServletActionContext; 12 import org.codehaus.jackson.JsonGenerator; 13 import org.codehaus.jackson.JsonProcessingException; 14 import org.codehaus.jackson.map.ObjectMapper; 15 import com.opensymphony.xwork2.ActionSupport; 16 17 public class BaseAction extends ActionSupport { 18 19 private static final long serialVersionUID = 4271951142973483943L; 20 21 protected Logger logger = Logger.getLogger(getClass()); 22 23 // 獲取Attribute 24 public Object getAttribute(String name) { 25 return ServletActionContext.getRequest().getAttribute(name); 26 } 27 28 // 設置Attribute 29 public void setAttribute(String name, Object value) { 30 ServletActionContext.getRequest().setAttribute(name, value); 31 } 32 33 // 獲取Parameter 34 public String getParameter(String name) { 35 return getRequest().getParameter(name); 36 } 37 38 // 獲取Parameter數(shù)組 39 public String[] getParameterValues(String name) { 40 return getRequest().getParameterValues(name); 41 } 42 43 // 獲取Request 44 public HttpServletRequest getRequest() { 45 return ServletActionContext.getRequest(); 46 } 47 48 // 獲取Response 49 public HttpServletResponse getResponse() { 50 return ServletActionContext.getResponse(); 51 } 52 53 // 獲取Application 54 public ServletContext getApplication() { 55 return ServletActionContext.getServletContext(); 56 } 57 58 // AJAX輸出,返回null 59 public String ajax(String content, String type) { 60 try { 61 HttpServletResponse response = ServletActionContext.getResponse(); 62 response.setContentType(type + ";charset=UTF-8"); 63 response.setHeader("Pragma", "No-cache"); 64 response.setHeader("Cache-Control", "no-cache"); 65 response.setDateHeader("Expires", 0); 66 response.getWriter().write(content); 67 response.getWriter().flush(); 68 } catch (IOException e) { 69 e.printStackTrace(); 70 } 71 return null; 72 } 73 74 // AJAX輸出文本,返回null 75 public String ajaxText(String text) { 76 return ajax(text, "text/plain"); 77 } 78 79 // AJAX輸出HTML,返回null 80 public String ajaxHtml(String html) { 81 return ajax(html, "text/html"); 82 } 83 84 // AJAX輸出XML,返回null 85 public String ajaxXml(String xml) { 86 return ajax(xml, "text/xml"); 87 } 88 89 // 根據(jù)字符串輸出JSON,返回null 90 public String ajaxJson(String jsonString) { 91 return ajax(jsonString, "application/json"); 92 } 93 94 // 根據(jù)Map輸出JSON,返回null 95 public String ajaxJson(Map<String, String> jsonMap) { 96 return ajax(mapToJson(jsonMap), "application/json"); 97 } 98 99 // 輸出JSON成功消息,返回null 100 public String ajaxJsonSuccessMessage(String message) { 101 Map<String, String> jsonMap = new HashMap<String, String>(); 102 jsonMap.put("status", SUCCESS); 103 jsonMap.put("message", message); 104 return ajax(mapToJson(jsonMap), "application/json"); 105 } 106 107 // 輸出JSON錯誤消息,返回null 108 public String ajaxJsonErrorMessage(String message) { 109 Map<String, String> jsonMap = new HashMap<String, String>(); 110 jsonMap.put("status", ERROR); 111 jsonMap.put("message", message); 112 return ajax(mapToJson(jsonMap), "application/json"); 113 } 114 // map轉(zhuǎn)化為json數(shù)據(jù) 115 public String mapToJson(Map<String,String> map){ 116 ObjectMapper mapper = new ObjectMapper(); 117 Writer sw = new StringWriter(); 118 try { 119 JsonGenerator json = mapper.getJsonFactory().createJsonGenerator(sw); 120 json.writeObject(map); 121 sw.close(); 122 } catch (JsonProcessingException e) { 123 e.printStackTrace(); 124 } catch (IOException e) { 125 e.printStackTrace(); 126 } 127 return sw.toString(); 128 } 129 }Struts2AjaxAction.java
1 package test.action.ajax; 2 import java.io.UnsupportedEncodingException; 3 import java.util.HashMap; 4 import java.util.Map; 5 import org.apache.commons.lang3.StringUtils; 6 import org.apache.struts2.convention.annotation.Action; 7 import org.apache.struts2.convention.annotation.Namespace; 8 import org.apache.struts2.convention.annotation.ParentPackage; 9 import org.apache.struts2.convention.annotation.Result; 10 import test.util.BaseAction; 11 12 @ParentPackage("ajax") 13 @Namespace("/test") 14 public class Struts2AjaxAction extends BaseAction 15 { 16 /** 17 * struts2-ajax 用例 18 */ 19 private static final long serialVersionUID = -4227395311084215139L; 20 21 @Action(value = "gotoStruts2JsonPlugin", results = { 22 @Result(name = "success", location = "/WEB-INF/content/test/ajax/struts2JsonPlugin.jsp")}) 23 public String gotoStruts2JsonPlugin() 24 { 25 return SUCCESS; 26 } 27 28 @Action(value = "gotoStruts2Ajax_post", results = { 29 @Result(name = "success", location = "/WEB-INF/content/test/ajax/struts2Ajax_post.jsp")}) 30 public String struts2Ajax_post() 31 { 32 return SUCCESS; 33 } 34 35 @Action(value = "gotoStruts2Ajax_ajax", results = { 36 @Result(name = "success", location = "/WEB-INF/content/test/ajax/struts2Ajax_ajax.jsp")}) 37 public String struts2Ajax_ajax() 38 { 39 return SUCCESS; 40 } 41 42 @Action(value = "post") 43 public String post() 44 { 45 String f1 = StringUtils.defaultString(getRequest().getParameter("field1")); 46 String f2 = StringUtils.defaultString(getRequest().getParameter("field2")); 47 ajaxText(f1+",測試,"+f2); 48 return null; 49 } 50 51 @Action(value = "ajax") 52 public String ajax() throws UnsupportedEncodingException 53 { 54 String f1 = StringUtils.defaultString(getRequest().getParameter("field1")); 55 String f2 = StringUtils.defaultString(getRequest().getParameter("field2")); 56 57 Map<String, String> jsonMap = new HashMap<String, String>(); 58 jsonMap.put(f1, f1); 59 jsonMap.put(f2, f2); 60 jsonMap.put("status", SUCCESS); 61 super.ajaxJson(jsonMap); 62 return null; 63 } 64 }- jsp
struts2Ajax_post.jsp
<%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %> <%@ taglib prefix="s" uri="/struts-tags"%> <% request.setAttribute("cxtpath",request.getContextPath()); %> <!DOCTYPE html> <html> <head> <meta name="author" content="" /> <meta http-equiv="Content-Type" content="text/html; charset=GBK" /> <title>使用$.ajax提交Ajax請求</title> <s:property value="cxtpath"/> <script src="${cxtpath}/js/common/jquery-1.9.1.js" type="text/javascript"></script> <script type="text/javascript"> function ajax() {// 以form1表單封裝的請求參數(shù)發(fā)送請求。var val1 = $("#form1_field1").val();var val2 = $("#form1_field2").val();$.ajax({url: '${cxtpath}/test/ajax.action', data: {"field1": val1,"field2": val2},dataType: "json",async: false,type: "POST",success: function(data) {console.log("data:"+JSON.stringify(data));if (data.status == "success") {console.log("succ");}else{data;console.log("fail");}}}); } </script> </head> <body> <div>使用$.ajax提交Ajax請求 <s:form id="form1" method="post">field1:<s:textfield name="field1" label="field1"/><br/>field2:<s:textfield name="field2" label="field2"/><br/>field3:<s:textfield name="field3" label="field3"/><br/><tr><td colspan="2"><input type="button" value="提交" onClick="ajax();"/></td></tr> </s:form> </div> </body> </html>struts2Ajax_ajax.jsp
1 <%@ page contentType="text/html; charset=GBK" language="java" errorPage="" %> 2 <%@ taglib prefix="s" uri="/struts-tags"%> 3 <% 4 request.setAttribute("cxtpath",request.getContextPath()); 5 %> 6 <!DOCTYPE html> 7 <html> 8 <head> 9 <meta name="author" content="" /> 10 <meta http-equiv="Content-Type" content="text/html; charset=GBK" /> 11 <title>使用$.post提交Ajax請求</title> 12 <s:property value="cxtpath"/> 13 <script src="${cxtpath}/js/common/jquery-1.9.1.js" type="text/javascript"></script> 14 <script type="text/javascript"> 15 function post() 16 { 17 // 以form1表單封裝的請求參數(shù)發(fā)送請求。 18 $.post('${cxtpath}/test/post.action', $("#form1").serializeArray(), 19 // data代表服務器響應,此處只是把服務器響應顯示出來 20 function(data) { 21 console.log("data:"+JSON.stringify(data)); 22 } 23 ) 24 } 25 </script> 26 </head> 27 <body> 28 <div>使用$.post提交Ajax請求 29 <s:form id="form1" method="post"> 30 field1:<s:textfield name="field1" label="field1"/><br/> 31 field2:<s:textfield name="field2" label="field2"/><br/> 32 field3:<s:textfield name="field3" label="field3"/><br/> 33 <tr> 34 <td colspan="2"> 35 <input type="button" value="提交" onClick="post();"/></td> 36 </tr> 37 </s:form> 38 </div> 39 </body> 40 </html>?
環(huán)境:JDK1.6,MAVEN,tomcat,eclipse
源碼地址:http://files.cnblogs.com/files/xiluhua/struts2-Ajax.rar
?
轉(zhuǎn)載于:https://www.cnblogs.com/xiluhua/p/4390046.html
總結(jié)
以上是生活随笔為你收集整理的struts2,实现Ajax异步通信的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【转】在.Net中关于AOP的实现
- 下一篇: Ajax 生成流文件下载 以及复选框的实