struts2是MVC框架,其中org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter过滤器是前端控制器
使用Action类模拟二级分发控制器来实现减少对s2标签的依赖,这样的话对模板原型的破坏会比较小,实现方式如下
public class _Base extends ActionSupport{ private String action =""; private String message =""; public void setAction(String action){this.action=action;} public String getAction(){return this.action;} public void setMessage(String message){this.message=message;} public String getMessage(return this.message); public String dispatcher(){ String _action = this.getAction(); String _invokeAction ="doIndex"; if(StringUtils.isBlank(_action)){ }else{ _invokeAction = _action; } String _result = SUCCESS; try{ Object obj = org.apache.commons.beanutils.MethodUtils.invokeMethod(this, _action, new Object[]{}); if(obj!=null){ _result = obj.toString(); } }catch(Exception e){ this.setMessage(e.getMessage()); } return _result; } public String doIndex(){ return SUCCESS; } }
public class Login extends _Base{ private String username=""; private String password=""; public void setUsername(String username){this.username=username;} public String getUsername(){return this.username;} public void setPassword(String password){this.password=password;} public String getPassword(){return this.password;} public String doLogin(){ try{ //invoke service return "home"; }catch(Exception e){ } retrun INPUT; } public String doLogout(){ //clear session return SUCCESS; } }
struts.xml
<action name="Login" class="Login" method="dispatcher"> <result name="success" type="freemarker">/WEB-INF/content/Login.ftl</result> <result name="input" type="freemarker">/WEB-INF/content/Login.ftl</result> <result name="home" type="redirectAction">Home</result> </action>
Login.ftl
<html><head><title></title></head><body> <form> <input type="hidden" name="action" value="doLogin"/><!--此隐藏域作为分发器的分发标志--> <input type="text" name="username" value="${username}"/> <input type="text" name="password" value="${password}"/> <input type="submit" value="登陆"/> </form> </body></html>
登出的链接则产生 Login.do?action=doLogout
此思想来源于php的mvc实现,在php中实现MVC的框架一般都是有一个前端控制器如
index.php,通过传参调用不同的控制器和action,如
index.php?ctrl=Login&action=defaultView
index.php?ctrl=Login&action=doLogin
index.php?ctrl=Login&action=doLogout