SSH系列:(27)添加投诉
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了SSH系列:(27)添加投诉相关的知识,希望对你有一定的参考价值。
在工作主页中的“我要投诉”,点击后弹出,投诉的新增页面,保存后到投诉受理后台管理进行处理。在这边添加时候需要使用到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 style="width:1%;float:left;"> </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 style="width:1%;float:left;"> </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()
以上是关于SSH系列:(27)添加投诉的主要内容,如果未能解决你的问题,请参考以下文章