将struts2的Action变成二级分发控制器以减少对strus2标签的依赖

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

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值