ParameterizableViewController

   

    

控制器是mvc模式中非常重要的部分。

Spring中org.springframework.web.portlet.mvc 包有10种controller : 



Spring中org.springframework.web.servlet.mvc包有13种controller : 



一 :Controller接口

Spring中最基本的是org.springframework.mvc.Controller接口。

 public   interface  Controller  {
          ModelAndView handleRequest( HttpServletRequest request, HttpServletResponse response)  throws  Exception;
}

这个接口非常的简单,只有一个可以返回适当Model和View的请求处理方法。除了这个接口Spring还提供了一些该接口的实现,包括了一些常用的功能方法。

二 :抽象类 AbstractController

 public   abstract   class  AbstractController  extends  WebContentGenerator  implements  Controller  {
           .
        protected   abstract  ModelAndView  handleRequestInternal  (HttpServletRequest request, HttpServletResponse response)  throws  Exception;
}

AbstractController提供了一个构建Controller的基础。AbstractController继承了WebContentGenerator并实现了Controller接口。这样,在AbstractController中就具备了以下的功能。

 ww.dlog

如果你使用AbstractController来做为一个基类的话(不推荐),你需要override一下handleRequestInternal方法,填充你的代码,返回一个ModelAndView对象。例如:

 public   class  SampleController  extends  AbstractController  {
     public  ModelAndView handleRequestInternal( HttpServletRequest request, HttpServletResponse response)  throws  Exception  {
                   ModelAndView mav  =   new  ModelAndView( " foo " ,  new  HashMap());
                       return mav;
    } 
}

 < bean id = " sampleController "   class = " samples.SampleController " > 
             < property name = " cacheSeconds " >< value > 120 </ value </ property > 
 </ bean >


三 :类  ParameterizableViewController

 public   class  ParameterizableViewController  extends  AbstractController  {

 ParameterizableViewController,根据指定的View名称,返回View。

 protected  ModelAndView handleRequestInternal(HttpServletRequest request, HttpServletResponse response)  throws  Exception  {
     return   new  ModelAndView( this .viewName);
}


四 :类 UrlFilenameViewController

 public   class  UrlFilenameViewController  extends  AbstractUrlViewController  {

UrlFilenameViewController,从请求URL中得到FileName。

 public  ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response)  {
     String uri  =  request.getRequestURI();
      int  begin  =  uri.lastIndexOf( ' / ' );
      if  (begin  ==   - 1 )  {
        begin  =   0 ;
     } else   {
        begin ++ ;
     } 
      int  end;
      if  (uri.indexOf( " ; " )  !=   - 1 )  {
        end  =  uri.indexOf( " ; " );
     } else   if  (uri.indexOf( " ? " )  !=   - 1 )  {
        end  =  uri.indexOf( " ? " );
     } else   {
        end  =  uri.length();
     } 
     String fileName  =  uri.substring(begin, end);
      if  (fileName.indexOf( " . " )  !=   - 1 )  {
        fileName  =  fileName.substring( 0 , fileName.lastIndexOf( " . " ));
     } 
 
      return   new  ModelAndView(fileName);
}

五 :类 MultiActionController

这个Controller在一个独立的包中,org.springframework.web.mvc.multiaction。

 public   class  MultiActionController  extends  AbstractController  implements  LastModified   {

}

你可以把多个动作集中到这个Controller中。当你需要大量公用的功能在一个Controller中时,这个Controller是很好的选择。你可以子类化MultiActionController,也可以使用MethodNameResolver。

MethodNameResolver : 

当接受请求的时候MultiActionController需要调用一个处理该请求的方法,你可以自己定义个解决方法,通过配置文件中指定的参数名称找到这个方法,方法定义必需使用以下格式:

 ModelAndView actionName(HttpServletRequest, HttpServletResponse);

此外你也可以自己定义一个异常类来处理异常,格式为:

 ModelAndView anyMeaningfulName(HttpServletRequest, HttpServletResponse, ExceptionClass);

Spring提供了MethodNameResolver的三种方式:

1 : ParameterMethodNameResolver,这个可以根据请求的参数来确定一个需要调用的方法。
例如,http://www.sf.net/index.view?testParam=testIt,这个请求会调用名称为testIt的处理方法。

2 : InternalPathMethodNameResolver,这个可以根据请求的路径名称来调用相应的方法。
例如,http://www.sf.net/testing.view,这个请求会调用testing方法。

3 : PropertiesMethodNameResolver,这个可以根据一个URLs 映射列表来调用相应的方法。
例如,如果定义了/index/welcome.html=doIt,那么当请求为/index/welcome.html时,会调用doIt方法。在定义URLs时可以使用通配符。/**/welcom?.html

例1 :

<bean id="paramMultiController" class="org.springframework.web.servlet.mvc.multiaction.MultiActionController">
    <property name="methodNameResolver"><ref bean="paramResolver"/></property>
    <property name="delegate"><ref bean="sampleDelegate"/>
</bean>

<bean id="paramResolver" class="org.springframework.web.servlet.mvc.multiaction.ParameterMethodNameResolver">
    <property name="paramName"><value>method</value></property>
</bean>

<bean id="sampleDelegate" class="samples.SampleDelegate"/>

SampleDelegate.java 代码

public class SampleDelegate {

    public ModelAndView retrieveIndex( HttpServletRequest req, HttpServletResponse resp) {
        rerurn new ModelAndView("index", "date", new Long(System.currentTimeMillis()));
    }

}

例3 :

<bean id="paramMultiController" class="org.springframework.web.servlet.mvc.multiaction.MultiActionController">
    <property name="methodNameResolver"><ref bean="propsResolver"/></property>
    <property name="delegate"><ref bean="sampleDelegate"/>
</bean>

<bean id="propsResolver" class="org.springframework.web.servlet.mvc.multiaction.PropertiesMethodNameResolver">
    <property name="mappings">
        <props>
            <prop key="/index/welcome.html">retrieveIndex</prop>
            <prop key="/**/notwelcome.html">retrieveIndex</prop>
            <prop key="/*/user?.html">retrieveIndex</prop>
        </props>
    </property>
</bean>



六 :抽象类 BaseCommandController

public abstract class BaseCommandController extends AbstractController {

这个控制器简化了struts中的操作,可以直接和数据对象进行交互。例如把HttpServletRequest得到的参数动态绑定到dataobject上。
AbstractCommandController,通过这个可以创建你自己的Command Comtroller。它继承了BaseCommandController,可以设置commandObject来保存数据,可以指定验证类。

 


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
@Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception { String method = request.getMethod(); String requestURI = request.getRequestURI(); if (o instanceof ResourceHttpRequestHandler || o instanceof ParameterizableViewController) { return true; } String accessName = "无"; HandlerMethod handlerMethod = (HandlerMethod) o; ApiOperation methodAnnotation = handlerMethod.getMethodAnnotation(ApiOperation.class); if (Validator.valid(methodAnnotation)) { accessName = methodAnnotation.value(); log.warn("########## requestURI: {} , method: {} , HandlerMethod: {} , IP: {} ##########", requestURI, method, accessName, IPUtil.getIPAddress(request)); } else { log.error("########## requestURI: {} , HandlerMethod: {} , IP: {} ##########", requestURI, method, IPUtil.getIPAddress(request)); } for (String url : passUrl) { if (UrlUtils.isLike(requestURI, url)) { return !method.equals("OPTIONS"); } } boolean hasPerm = false; if (!method.equals("OPTIONS")) { try { String token = request.getHeader("token"); System.out.println("token -------->>>>>> " + token); if (!Validator.valid(token)) { throw new BusinessException(CommonErrorCode.TOKEN_REMIND, "token不能为空"); } token = (String) permRedisManager.get(token); if (!Validator.valid(token)) { throw new BusinessException(CommonErrorCode.TOKEN_REMIND, "请重新登录"); } Map<String, Claim> result = JWTBuilder.parseJWT(token); if (Validator.valid(result.get(AuthUtil.SYS_EMPLOYEE_NAME))) { // hasPerm = true; DepositBox depositBox = setAttribute(request, result, AuthUtil.SYS_EMPLOYEE_NAME, token); //操作记录 String finalAccessName = accessName; } else if ((Validator.valid(result.get(AuthUtil.MEMBER_NAME)))) { if (requestURI.startsWith("/bg")) { throw new BusinessException(CommonErrorCode.NO_SESSION); } hasPerm = true; setAttribute(request, result, AuthUtil.MEMBER_NAME, token); } } catch (BusinessException e) { throw e; } catch (Exception e) { if (e instanceof NullPointerException) { throw new BusinessException(CommonE rrorCode.TOKEN_REMIND, "token无效"); } else if (e instanceof JWTDecodeException) { throw new BusinessException(CommonErrorCode.TOKEN_REMIND, "token信息不完整"); } else { throw new BusinessException(e.toString()); } } } if (!method.equals("OPTIONS") && !hasPerm) { throw new BusinessException(CommonErrorCode.NO_SESSION); } return !method.equals("OPTIONS"); }解释代码
最新发布
06-09
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值