Struts2 与 Ext 整合开发

最近一直想找一个Struts与Ext整合的一个比较规范的做法,个人觉得必然使用Struts的json,弄了一个晚上,不知道是否在符合大众的规范,配置如下:

Struts2从2.1.7开始便将json整合进去了,从Strtus2的lib包中可以片可以找到,名为struts2-json-plugin-2.x.x.x.jar

将json-plugin放入工程的lib中去后,便可以开始进行开发:

Action:

 

package com.bjsoft.oa.action.system; import nl.captcha.Captcha; import org.apache.commons.lang.xwork.StringUtils; import com.bjsoft.oa.model.User; import com.bjsoft.oa.service.UserService; import com.opensymphony.xwork2.ActionContext; import com.opensymphony.xwork2.ActionSupport; public class LoginAction extends ActionSupport { private static final long serialVersionUID = 2578893349737621315L; private UserService userService; private User user; private String simpleCaptcha; private boolean success; private String msg; @Override public String execute() throws Exception { success = false; msg = ""; Captcha _simpleCaptcha = (Captcha) ActionContext.getContext() .getSession().get("simpleCaptcha"); if (_simpleCaptcha.isCorrect(simpleCaptcha)) { String _userName = user.getUsername(); String _password = user.getPassword(); if (!StringUtils.isEmpty(_userName) && !StringUtils.isEmpty(_password)) { User u = this.userService.getUserByName(_userName); if(u != null){ if (StringUtils.equals(u.getPassword(), _password)) { success = true; } else { msg = "密码错误!"; } }else{ msg = "不存在的用户"; } } else { msg = StringUtils.isEmpty(_userName) ? "用户名不能为空" : "密码不能为空"; } } else { msg = "验证码错误!"; } return super.execute(); } public UserService getUserService() { return userService; } public void setUserService(UserService userService) { this.userService = userService; } public User getUser() { return user; } public void setUser(User user) { this.user = user; } public String getSimpleCaptcha() { return simpleCaptcha; } public void setSimpleCaptcha(String simpleCaptcha) { this.simpleCaptcha = simpleCaptcha; } public boolean isSuccess() { return success; } public void setSuccess(boolean success) { this.success = success; } public String getMsg() { return msg; } public void setMsg(String msg) { this.msg = msg; } }

 

strtus.xml

 

<struts> <package name="login" namespace="/" extends="json-default"> <action name="login" class="com.bjsoft.oa.action.system.LoginAction"> <result type="json"> <param name="includeProperties"> success,msg </param> </result> </action> </package> </struts>
这里的package一定要继承json-default,并且result type也是要json格式,同时另一个问题是没有参数的json result 将会把action中所有局部变量放在json格式的字符串返回给前端,这样似乎就造成了不必要的浪费,于是有两种解决办法,一种是上面的配置,告诉struts应该包含哪些变量,另一种是告诉struts不应该包含哪些变量,<!-- Result fragment --> <result type="json"> <param name="excludeProperties"> login.password, studentList.*\.sin </param> </result>
这样就可以了。

 

 

你可能感兴趣的:(java,json,ext,strtus2)