您好,登錄后才能下訂單哦!
在工作主頁中的“我要投訴”,點擊后彈出,投訴的新增頁面,保存后到投訴受理后臺管理進行處理。在這邊添加時候需要使用到Ajax根據部門名稱級聯查詢部門人員;查詢到部門對應的人員列表后,需要將這些人員信息轉換為json字符串。
1、HomeAction
(1)按照講義中寫的應該是引入3個jar,分別是: commons-beanutils-1.8.0.jar ezmorph-1.0.6.jar json-lib-2.3-jdk15.jar 我猜測,是為了進行JSON轉換,但我寫代碼并沒有成功 public void getUserJson(){ try { //1、獲取部門 String dept = ServletActionContext.getRequest().getParameter("dept"); if(StringUtils.isNotBlank(dept)){ QueryHelper queryHelper = new QueryHelper(User.class, "u"); queryHelper.addCondition("u.dept like ?", "%" + dept); //2、根據部門查詢用戶列表 List<User> userList = userService.findObjects(queryHelper); //創建Json對象 JSONObject jso = new JSONObject(); jso.put("msg", "success"); jso.accumulate("userList", userList); //3、輸出用戶列表以json格式字符串形式輸出 HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html"); ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(jso.toString().getBytes("utf-8")); outputStream.close(); } } catch (Exception e) { e.printStackTrace(); } } 之后,我只能用gson來完成,當我想刪除添加之前添加的jar包時,卻無法刪除,因此也沒有辦法判斷這幾個jar包對JSON字符串的功能 |
(2)使用struts2-json-plugin-2.x.jar 包,由struts將action中的變量組裝成Json對象。 |
HomeAction.java
package com.rk.home.action; import java.io.IOException; import java.io.UnsupportedEncodingException; import java.sql.Timestamp; import java.util.Date; import java.util.HashMap; import java.util.List; import java.util.Map; import javax.annotation.Resource; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import net.sf.json.JSONObject; import org.apache.commons.lang3.StringUtils; import org.apache.struts2.ServletActionContext; import com.google.gson.Gson; import com.google.gson.GsonBuilder; import com.opensymphony.xwork2.Action; import com.opensymphony.xwork2.ActionSupport; import com.rk.core.entity.JsonResult; import com.rk.core.utils.QueryHelper; import com.rk.tax.entity.Complain; import com.rk.tax.entity.User; import com.rk.tax.service.ComplainService; import com.rk.tax.service.UserService; public class HomeAction extends ActionSupport { private Map<String, Object> return_map; private Complain comp; @Resource private UserService userService; @Resource private ComplainService complainService; //跳轉到首頁 @Override public String execute() throws Exception { return "home"; } //跳轉到我要投訴 public String complainAddUI(){ return "complainAddUI"; } public void getUserJson(){ try { //1、獲取部門 String dept = ServletActionContext.getRequest().getParameter("dept"); if(StringUtils.isNotBlank(dept)){ QueryHelper queryHelper = new QueryHelper(User.class, "u"); queryHelper.addCondition("u.dept like ?", "%"+dept); // FIXME 這里為什么是%+dept呢? //2、根據部門查詢用戶列表 List<User> userList = userService.findList(queryHelper); //創建Json對象 JsonResult result = new JsonResult(); result.setStatus(JsonResult.SUCCESS); result.setData(userList); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); String strJson = gson.toJson(result); //3、輸出用戶列表,以JSON格式字符串形式輸出 HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html"); ServletOutputStream outputStream = response.getOutputStream(); outputStream.write(strJson.getBytes("utf-8")); outputStream.close(); } } catch (Exception e) { e.printStackTrace(); } } public String getUserJson2(){ //1、獲取部門 String dept = ServletActionContext.getRequest().getParameter("dept"); if(StringUtils.isNotBlank(dept)){ QueryHelper queryHelper = new QueryHelper(User.class, "u"); queryHelper.addCondition("u.dept like ?", "%"+dept); //2、根據部門查詢用戶列表 return_map = new HashMap<String, Object>(); return_map.put("status", "success"); return_map.put("data", userService.findList(queryHelper)); } return Action.SUCCESS; } //保存投訴 public void complainAdd(){ try { if(comp != null){ //設置默寫投訴狀態為 待受理 comp.setState(Complain.COMPLAIN_STATE_UNDONE); comp.setCompTime(new Timestamp(new Date().getTime())); complainService.save(comp); //輸出投訴結果 HttpServletResponse response = ServletActionContext.getResponse(); response.setContentType("text/html"); ServletOutputStream outputStream = response.getOutputStream(); outputStream.write("success".getBytes("utf-8")); outputStream.close(); } } catch (Exception e) { e.printStackTrace(); } } public Map<String, Object> getReturn_map() { return return_map; } public void setReturn_map(Map<String, Object> return_map) { this.return_map = return_map; } public Complain getComp() { return comp; } public void setComp(Complain comp) { this.comp = comp; } }
JsonResult.java
package com.rk.core.entity; import com.google.gson.Gson; import com.google.gson.GsonBuilder; public class JsonResult { private String status; private Object data; public static final String OK = "ok"; public static final String SUCCESS = "success"; public static final String ERROR = "error"; public String getStatus() { return status; } public void setStatus(String status) { this.status = status; } public Object getData() { return data; } public void setData(Object data) { this.data = data; } @Override public String toString() { //Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd HH:mm:ss").create(); Gson gson = new GsonBuilder().setDateFormat("yyyy-MM-dd").create(); return gson.toJson(this); } }
struts-home.xml
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="home_package" namespace="/sys" extends="base-default"> <action name="home_*" class="com.rk.home.action.HomeAction" method="{1}"> <result name="home">/WEB-INF/jsp/home/home.jsp</result> <result name="{1}">/WEB-INF/jsp/home/{1}.jsp</result> </action> <action name="login_*" class="loginAction" method="{1}"> <result name="{1}">/WEB-INF/jsp/{1}.jsp</result> <result name="loginUI">/WEB-INF/jsp/loginUI.jsp</result> <result name="noPermissionUI">/WEB-INF/jsp/noPermissionUI.jsp</result> <result name="home" type="redirectAction"> <param name="actionName">home</param> </result> <result name="toLoginUI" type="redirectAction"> <param name="actionName">toLoginUI</param> </result> </action> </package> <package name="sysHomeJson-action" namespace="/sys" extends="json-default"> <action name="home_getUserJson2" class="com.rk.home.action.HomeAction" method="getUserJson2"> <result type="json"> <param name="root">return_map</param> </result> </action> </package> </struts>
知識點(1):json-default
struts2-json-plugin-2.3.29.jar內有一個struts-plugin.xml文件
在struts-plugin.xml文件中定義了json-default,而它繼承自struts-default包。struts-plugin.xml文件內容如下:
<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd"> <struts> <package name="json-default" extends="struts-default"> <result-types> <result-type name="json" class="org.apache.struts2.json.JSONResult"/> <result-type name="jsonActionRedirect" class="org.apache.struts2.json.JSONActionRedirectResult"/> </result-types> <interceptors> <interceptor name="json" class="org.apache.struts2.json.JSONInterceptor"/> <interceptor name="jsonValidation" class="org.apache.struts2.json.JSONValidationInterceptor"/> <!-- Sample JSON validation stack --> <interceptor-stack name="jsonValidationWorkflowStack"> <interceptor-ref name="basicStack"/> <interceptor-ref name="validation"> <param name="excludeMethods">input,back,cancel</param> </interceptor-ref> <interceptor-ref name="jsonValidation"/> <interceptor-ref name="workflow"/> </interceptor-stack> </interceptors> </package> </struts>
注意:<pagekage>中的extends="base-default",如果有多個,中間可以用“,”分隔。
<package name="" extends="json-default,struts-default">
這樣的繼承,要確保父包里面不能有重復的 action名,要不然,子包不知道 調用那個。
2、JSP頁面
在主頁面home.jsp中添加鏈接,會在空白頁面打開
<s:a action="home_complainAddUI" namespace="/sys" target="_blank">我要投訴</s:a>
complainAddUI.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <%@include file="/common/header.jsp"%> <title>我要投訴</title> <script type="text/javascript" src="${basePath}/js/ueditor/ueditor.config.js"></script> <script type="text/javascript" src="${basePath}/js/ueditor/ueditor.all.js"></script> <script type="text/javascript" src="${basePath}/js/ueditor/lang/zh-cn/zh-cn.js"></script> <script type="text/javascript"> window.UEDITOR_HOME_URL = "${basePath}/js/ueditor"; window.onload = function(){ var ue = UE.getEditor("editor"); } //根據部門查詢該部門下的用戶列表 function doSelectDept(){ //1、獲取部門 var dept = $('#toCompDept option:selected').val(); if(dept != ""){ //2、根據部門查詢列表 $.ajax({ url:"${basePath}/sys/home_getUserJson2.action", data:{"dept":dept}, type:"post", dataType:"json",//返回數據類型 success:function(result){ //2.1、將用戶列表設置到被投訴人下拉框中 if(result != null && result != "" && result != undefined){ if("success" == result.status){ var toCompName = $('#toCompName'); toCompName.empty(); $.each(result.data,function(index,user){ toCompName.append("<option value='" + user.name + "'>"+user.name+"</option>"); }); } else{ alert("獲取被投訴人列表失敗"); } } else{ alert("被投訴人列表似乎不存在"); } }, error:function(){ alert("獲取被投訴人列表:AJAX請求失敗!"); } }); } else{ //清空被投訴人列表下拉框 $('#toCompName').empty(); } } //提交表單 function doSubmit(){ //1、提交表單并保存 $.ajax({ url:"${basePath}/sys/home_complainAdd.action", data:$('#form').serialize(), type:"post", ansy:false, success:function(result){ if(result == "success"){ //2、提示用戶投訴成功 alert("投訴成功!"); //3、刷新父窗口 window.opener.parent.location.reload(true); //4、關閉當前窗口 window.close(); } else{ alert("投訴失敗!"); } }, error:function(){ alert("投訴:AJAX請求失敗"); } }); } </script> </head> <body> <form id="form" name="form" action="" method="post" enctype="multipart/form-data"> <div class="vp_d_1"> <div > </div> <div class="vp_d_1_1"> <div class="content_info"> <div class="c_crumbs"><div><b></b><strong>工作主頁</strong> - 我要投訴</div></div> <div class="tableH2">我要投訴</div> <table id="baseInfo" width="100%" align="center" class="list" border="0" cellpadding="0" cellspacing="0" > <tr> <td class="tdBg" width="250px">投訴標題:</td> <td><s:textfield name="comp.compTitle"/></td> </tr> <tr> <td class="tdBg">被投訴人部門:</td> <td> <s:select id="toCompDept" name="user.dept" list="#{'':'請選擇','部門A':'部門A','部門B':'部門B'}" onchange="doSelectDept()"></s:select> </td> </tr> <tr> <td class="tdBg">被投訴人姓名:</td> <td> <select id="toCompName" name="comp.toCompName"> </select> </td> </tr> <tr> <td class="tdBg">投訴內容:</td> <td><s:textarea id="editor" name="comp.compContent" cssStyle="width:90%;height:160px;" /></td> </tr> <tr> <td class="tdBg">是否匿名投訴:</td> <td><s:radio name="comp.isAnonymous" list="#{'false':'非匿名投訴','true':'匿名投訴' }" value="true"/></td> </tr> </table> <s:hidden name="comp.compCompany" value="%{#session.SYS_USER.dept}"/> <s:hidden name="comp.compName" value="%{#session.SYS_USER.name}"/> <s:hidden name="comp.compMobile" value="%{#session.SYS_USER.mobile}"/> <div class="tc mt20"> <input type="button" class="btnB2" value="保存" onclick="doSubmit()"/> <input type="button" onclick="javascript:window.close()" class="btnB2" value="關閉" /> </div> </div></div> <div > </div> </div> </form> </body> </html>
知識點(1):獲取select的值
var dept = $('#toCompDept option:selected').val();
知識點(2):清空、迭代
var toCompName = $('#toCompName'); toCompName.empty(); $.each(result.data,function(index,user){ toCompName.append("<option value='" + user.name + "'>"+user.name+"</option>"); });
知識點(3):原窗口的刷新
window.opener.parent.location.reload(true);
知識點(4):表單元素的序列化
$('#form').serialize()
免責聲明:本站發布的內容(圖片、視頻和文字)以原創、轉載和分享為主,文章觀點不代表本網站立場,如果涉及侵權請聯系站長郵箱:is@yisu.com進行舉報,并提供相關證據,一經查實,將立刻刪除涉嫌侵權內容。