您的位置:68399皇家赌场 > 集群主机 > SpringMVC入门知识2

SpringMVC入门知识2

发布时间:2019-10-06 04:55编辑:集群主机浏览(75)

    与原先的管理程序不一致的是,基于注解允许更加灵活的配备。不独有无需在XML进行各类繁琐的陈设,一旦U福特ExplorerL很多的事态下,想象一下XML,各类头大,以后经过申明,我们能够把一条路上分化岔口的U奥迪Q5L在一个controller里进行摄取管理就好。当配置文件中定义<mvc:annotation-driven/>时,此管理程序将被激活。其它,为了更加细粒度的管理controller评释,我们能够透过增多<context:annotation-config />和<context:component-scan base-package =“path.with.my.services.and.controllers”/>来启用它们。

    HttpServletResponse

    spring-webmvc-4.1.4.RELEASE.jar

    非注明的微管理器映射器
    SimpleUrlHandlerMapping:简单url映射
    能够完毕对url的汇分安排
    八个映射器能够存活,前端调节器会去判定url能让哪个映射器管理,就让正确的映射器实行管理
    微型计算机映射器将bean的name作为url进行检索,必要在布署Handler时钦点beanname(正是url)
    具有的映射器都将落实handlerMapping接口
    非评释的适配器:
    SimpleControllerHandlerAdapter
    须求编辑的Handler达成Controller接口
    HTTPRequesthandlerAdapter
    务求编辑的Handler达成HTTPRequestHandler接口
    选用此方式能够通过修改response,设置响应的多寡格式,比如响应json数据
    映射器想用哪个就用哪个,不是配成对应用的
    DispatcherServlet.properties:
    前面多个调节器会从这么些文件中加载管理映射器、适配器、视图深入分析器等零件,假若不在SpringMVC.xml中布署,就动用暗中认可加载了
    注明的Computer映射器和适配器
    在Spring3.1以前使用org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping注明映射器
    在Spring3.1之后选拔org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping注脚映射器
    在Spring3.1以前运用的笺注适配器org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping
    在Spring3.1之后采取的笺注适配器org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter
    安顿注脚的映射器和适配器
    使用MVC的注释驱动能够代替上面多个评释映射器和适配器的配置
    mvc:annotation-driven暗中认可加载了多数的参数的绑定的措施,举例json的调换的深入分析器,
    假诺运用mvc:annotation-driven,就毫无配置RequestMappingHandlerAdapter和RequestMappingHandlerMapping
    实际支付时利用mvc:annotation-driven
    支出证明的Handler
    @Controller使用那个申明来标记是三个调控器
    开采Handler的时候利用注脚的映射器和注释的适配器(评释的映射器和注释的适配器必需配对使用)
    @RequestMapping完毕格局和url举行映射,四个主意对应一个url
    在Spring容器中加载Handler
    对于表明的Handler能够单个配置
    事实上支付中国建工业总会公司议使用组件扫描context:component-scan
    可以扫描Controller、service
    源码剖判:
    透过前端调控器源码深入分析SpringMVC的实施进程
    1、前端调整器接收诉求
    调用doDispatch
    2、前端调节器调用管理器映射器查找handler
    3、调用管理器适配器去实践Handler,获得施行的结果ModelAndView
    4、视图渲染,将Model的数码填充到request域
    视图深入分析,获得view,调用view的渲染方法,将model的数据填充到request域
    入门程序总结:
    透过入门程序理解SpringMVC前端调整器、管理器映射器、管理器适配器、视图深入分析器的用法
    前面一个调节器:
    布署url-pattern的二种方法
    微型Computer映射器:
    非申明的微型计算机映射器
    申明的管理器映射器
    对标识有Controller类中标志有RequestMapping方法开展览放映射,在RequestMapping定义了炫丽的url
    运用评释的映射器不用在xml中部署url和Handler的投射关系
    管理器适配器:
    非注脚的Computer适配器
    批注的微型计算机适配器
    注明的管理器适配器和注释的Computer映射器是配对应用的,通晓为无法动用非证明的映射器进行映射
    MVC评释驱动标签:
    能够代替声明适配器和注释映射器的配备
    视图分析器:
    默许加载jstl
    路子在视图分析器中配备了jsp路线的前缀和jsp路线的后缀,就足以在地点里只写文件名
    次第中毫无内定前缀和后缀

    Spring Web应用程序的主旨站是DispatcherServlet(具体请查看Spring5源码剖析-论Spring DispatcherServlet的生命周期)。那是有着传入央浼的基本入口。但万一未有但一旦未有过多的handlers,大家照例无法做任何事情。

    # Default implementation classes for DispatcherServlet s strategy interfaces.
    # Used as fallback when no matching beans are found in the DispatcherServlet context.
    # Not meant to be customized by application developers.

    spring-core-4.1.4.RELEASE.jar

    唯独,在SimpleUrlHandlerMapping中,管理多少复杂U哈弗L也是八个胃痛的标题。那也是干什么我们要用DefaultAnnotationHandlerMapping大概在风行的Spring版本中动用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping的案由。

    Model //public abstract interface org.springframework.ui.Model

    spring-aop-4.1.4.RELEASE.jar

    @Controllerpublic class TestController { private static final Logger LOGGER = LoggerFactory.getLogger(TestController.class); @DumberRequestMapping(value = "/test") public String testSession(HttpServletRequest request) { LOGGER.debug("Is dumber request ?" request.getAttribute("isDumber")); LOGGER.debug("Handled time ?" request.getAttribute("handledTime")); return "testTemplate"; }}
    

    -- void

    spring-web-4.1.4.RELEASE.jar

    第一,在Spring的世界中,那个handler到底做了些什么。简单来讲,这几个就和大家听见一句话只怕看见有些场景,然后有有关的反应是同等的,由好些个拍卖最终转造成大家大脑皮层所能了解的事物。从机器语言的角度正是词法解析,语法深入分析,好咯,我们知道编写翻译语言的入眼相当于基础的注重了吧,回到框架中来,对于Spring来说,那么些管理程序就是一种将客商操作转变为Spring能够知晓的要素。提起客户操作,大家能够设想像 controller代码都知情,处理程序能够搜索@RequestMapping的注释,并检讨哪些映射与/login 这几个U锐界L相配。由上一篇作品大家得以掌握,这些管理程序将要DispatcherServlet的内被调用。

    拜访的时候

    @RequestMapping(value="/updateUser" ,method=RequestMethod.POST) 
    @RequestMapping(value="/updateUser" ,method={RequestMethod.POST,RequestMethod.GET}) 
    
    <bean > <property name="mappings"> <props> <prop key="/friends.html">FriendsController</props> </property></bean>
    

    √能大约的实行Web层的单元测量检验;

    比如

    但这里要介怀的是,在Spring版本中有局地重大调换。作为DefaultAnnotationHandlerMapping,AnnotationMethodHandlerAdapter或AnnotationMethodHandlerExceptionResolver的处理程序适配器自Spring 3.2版本的话已经放任,在Spring4.x里还足以阅览,在Spring5内已经删除掉了,取代品为RequestMappingHandlerMapping,RequestMappingHandlerAdapter和ExceptionHandlerExceptionResolver。通过那些新类以便于自定义映射。别的,通过在since 3.1 版本中org.springframework.web.method.HandlerMethod类中引进,来将所管理的对象调换为其艺术表示。大家可以透过那几个点子来推断目的回来的项目或许怎么着参数是我们所企盼的(望着拗口的话请打开源码查看此类注释)。

    <body>
    <c:forEach var="u" items="${userList }">
       ${u.id } | ${u.userName } | ${u.password }  <br />
    </c:forEach>
    </body>
    

    包裹档案的次序

    在写那一个handler在此之前,让我们写个自定义的@RequestMapping的笺注:

    --method 钦点诉求的method类型 (GET,POST,PUT,DELETE等)

    org.springframework.web.servlet.HandlerExceptionResolver=
    org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerExceptionResolver,
    org.springframework.web.servlet.mvc.annotation.ResponseStatusExceptionResolver,
    org.springframework.web.servlet.mvc.support.DefaultHandlerExceptionResolver

    大家能够看见, handler mapping是Spring生态系统中的三个最首要概念。全数的U福特ExplorerL都由相应的管理程序管理,由此,Spring能够包容传入的HTTP恳求和所加申明配置的controller的艺术。我们也见到了如何依照不一致法则来过滤央求,举个例子:Content-Type,Accept或任何headers 或HTTP方法。大家还编写了贰个poor版本的Spring的RequestMappingInfoHandlerMapping,它阻挡一些U奥德赛L管理并将结果通过视图输出给顾客。计算起来正是,通过一定的点子鲜明相应央求的拍卖地点(我们常见经过注明来显明),仅此而已,啰嗦了太多的事物,最终也即是如此的第一手。

    2)

    2)

    末段一件事是采纳@DumberRequestMapping在措施上增加表明:

    @DateTimeFormat(pattern="yyyy-MM-dd")  //有效,简单
    private Date birthday;
    

    Model //public abstract interface org.springframework.ui.Model

    透过执行

    jstl-api-1.2.jar

    √非常轻松与其他视图技能集成,如Velocity、FreeMarker等等,因为模型数据不放在特定的API里,而是位于三个Model里(Map数据结构达成,因而很轻易被别的框架使用);

    我们要求向大家的应用程序上下文增添新的HandlerMapping。请看上边那几个基于XML的配备:

    6) 数组类型的绑定

    √提供强大的预订大于配置的协议式编制程序帮忙;

    @Controllerpublic class FriendsController { @RequestMapping(value = "/friends.html", method = RequestMethod.GET) public String showFriendsList() { return "friendsListView"; } @RequestMapping(value = "/friends/potential-friends.html" method = RequestMethod.GET) public String showPotentialFriends() { return "potentialFriendsView"; }}
    
    private Date birthday;   //生成get set
    //在user_edit.jsp 页面上 加上字段   
    <input type="text" name="birthday" value="${user.birthday }" />  可以发现,在提交的时候出
    

    6) 数组类型的绑定

    public class DumberRequestHandlerMapping extends RequestMappingHandlerMapping { private static final Logger LOGGER = LoggerFactory.getLogger(DumberRequestHandlerMapping.class); /** * Checks if handler should be applied to given bean's class. The check is made through looking for DumberRequestMapping annotation. */ @Override protected boolean isHandler(Class<?> beanType) { Method[] methods = ReflectionUtils.getAllDeclaredMethods; for (Method method : methods) { if (AnnotationUtils.findAnnotation(method, DumberRequestMapping.class) != null) { LOGGER.debug("[DumberRequestHandlerMapping] Method " method " supports @DumberRequestMapping "); return true; } } return false; } /** * Make some operations directly before returning HttpServletRequest instance into mapped controller's method. For example, if you add here some attributes to this object, those attributes will be reachable from controller's method which handles the request. * RequestMappingInfoHandlerMapping does some of more complicated stuff here like exposing URI template variables or extracting * "matrix variable". * NOTE : "matrix variables" are name-value pairs within path segments, separated with a semicolon . For example in this URL * /clubs;country=France;division=Ligue 1, Ligue 2) we can find 2 matrix variables: country  and division (list composed by * Ligue 1 and Ligue 2) */ @Override protected void handleMatch(RequestMappingInfo info, String lookupPath, HttpServletRequest request) { LOGGER.debug("[DumberRequestHandlerMapping] handleMatch info " info  ", lookupPath ="  lookupPath   ", request =" request); request.setAttribute("isDumber", true); request.setAttribute("handledTime", System.nanoTime; } /** * Method invoked when given lookupPath doesn't match with this handler mapping. * Native RequestMappingInfoHandlerMapping uses this method to launch two exceptions : * - HttpRequestMethodNotSupportedException - if some URLs match, but no theirs HTTP methods. * - HttpMediaTypeNotAcceptableException - if some URLs match, but no theirs content types. For example, a handler can match an URL * like /my-page/test, but can expect that the request should be send as application/json. Or, the handler can match the URL but * returns an inappropriate response type, for example: text/html instead of application/json. */ @Override protected HandlerMethod handleNoMatch(Set<RequestMappingInfo> requestMappingInfos, String lookupPath, HttpServletRequest request) throws ServletException { LOGGER.debug("[DumberRequestHandlerMapping] handleNoMatch info " requestMappingInfos  ", lookupPath ="  lookupPath   ", request =" request); return null; } /** * Here we constructs RequestMappingInfo instance for given method. * RequestMappingInfo - this object is used to encapsulate mapping conditions. For example, it contains an instance of * PatternsRequestCondition which is used in native Spring's RequestMappingInfoHandlerMapping handleMatch() method to put URI * variables into @RequestMapping pattern. * Ie, it will take the following URL /test/1 and match it for URI template /test/{id}. In occurrence, it will found that 1 * corresponding to @PathVariable represented by id variable  and will set its value to 1. */ @Override protected RequestMappingInfo getMappingForMethod(Method method, Class<?> handlerType) { LOGGER.debug("[DumberRequestHandlerMapping] getMappingForMethod method " method  ", handlerType =" handlerType); RequestMappingInfo info = null; // look for @DumberRequestMapping annotation for the Method method from signature DumberRequestMapping methodAnnotation = AnnotationUtils.findAnnotation(method, DumberRequestMapping.class); if (methodAnnotation != null) { RequestCondition<?> methodCondition = getCustomMethodCondition; info = createRequestMappingInfo(methodAnnotation, methodCondition); } LOGGER.debug("[DumberRequestHandlerMapping] getMappingForMethod method; returns info mapping " info); return info; } /** * Creates RequestMappingInfo object which encapsulates: * - PatternsRequestCondition: represents URI template to resolve. Resolving is helped by UrlPathHelper utility class from * package org.springframework.web.util. * - RequestMethodsRequestCondition: methods accepted by this handler. You can make a test and replace RequestMethod.GET by * RequestMethod.POST. You will able to observe that our test won't work. * - ParamsRequestCondition: * - HeadersRequestCondition: headers which should be send in request to given handler should handle this request. You can, * for exemple, put there an header value like "my-header:test" and observe the program behavior. * - ConsumesRequestCondition: this condition allows to specify the content-type of request. We can use it for, for example, * specify that a method can be handled only for application/json request. * - ProducesRequestCondition: this condition allows to specify the content-type of response. We can use it for, for example, * specify that a method can be applied only for text/plain response. */ protected RequestMappingInfo createRequestMappingInfo(DumberRequestMapping annotation, RequestCondition<?> customCondition) { return new RequestMappingInfo( new PatternsRequestCondition(new String[] {annotation.value, new RequestMethodsRequestCondition(new RequestMethod[]{RequestMethod.GET}), new ParamsRequestCondition(new String[]{}), new HeadersRequestCondition(new String[] {}), new ConsumesRequestCondition(new String[]{}, new String[]{}), new ProducesRequestCondition(new String[]{}, new String[]{}, getContentNegotiationManager, customCondition); }}
    
    <!--  配置处理器映射器 handler Mapping -->
    <bean name="/search_all" class="cat.controller.UserAction"  />
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />  
    
    <!--   配置处理器适配器 handler Adapter -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
    
    <!--   配置视图解析器  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
    
    //Action 中的方法
    public class UserAction implements Controller {  //要实现 Controller
           public ModelAndView handleRequest(HttpServletRequest request,
                        HttpServletResponse response) throws Exception {
                        UserDao dao=new UserDao();
                        List<UserInfo> userList=dao.getAllUser();
    
                        ModelAndView mv=new ModelAndView();
                        mv.addObject("userList", userList); //相当于request.setAttribute();
                        mv.setViewName("user_manage.jsp");
    
                        return mv;
                    } 
                }
    
    <form action="${pageContext.request.contextPath }/deleUser" method="post">
    <c:forEach var="u" items="${userList }">
    <input type="checkbox" name="ids" value="${u.id } ">    ${u.id } | ${u.userName } | ${u.password }  <br />
    </c:forEach>
    <input type="submit" value="删除所选" >
    </form>
    

    它们的映射检查测量试验是依据注脚。这样,全体的逻辑都封存在Java代码那块,举个例子:

    -- consumes:  钦赐管理央浼的付出内容类型(Content-Type),举例application/json, text/html;

    三、配置

    正如您所见到的,这种布署在好些个UOdysseyL的动静下是非常不实用的。一些更加灵敏的管理映射器是org.springframework.web.servlet.handler.SimpleUrlHandlerMapping。并非为各样须求成立bean,大家能够创立五个辉映文件,个中包涵UENCOREL作为键和controller作为值,看上边包车型地铁布署:

    配置核心调整器

    五、@RequestMapping 评释, 和 Action中方法的再次来到值

    率先,在本文中,咱们先解读handler到底是个什么。之后,大家将介绍部分Spring框架中handlers的三种处理项目。最终大家加点salt来让大家学的事物实行落地,大家将编制大家友好的handler。

    例如

    六、参数绑定与值的传递

    编排自定义的Spring handler程序

    √对静态能源的支撑;

    证实 假如央求类型不对则出现就好像分外 Request method 'GET' not supported

    独一的品质是意味U安德拉L路线的值,与@RequestMapping注明中的value属性完全同样。将来我们能够流传大家的管理程序映射类。该学科在里面开展评价。那就是为什么它不会在平时的“文本形式”中隐含其余补偿批评。

    public class UserInfoCustomL {
                                  private List<UserInfo> userList;  //生成get set 
                          }            
    

    布置Computer映射器, 配置管理器适配器,  配置视图分析器 (即配置主文件)

    初稿:Spring5源码剖判-Spring中的处理器handlers

    spring-webmvc-4.1.4.RELEASE.jar

    @RequestMapping("/deleUser")
    public String delUsers(Integer [] ids){  //参数名要和页面中传的参数名相同
                           for(Integer id:ids){
                                        System.out.println(id);
                                        }
                           //new UserDao().deleteUsers(ids);
                                        return "success";
                           }
    
    //附:也可以如下
    @RequestMapping("/deleUser")
    public String delUsers(HttpServletRequest request){
                           String [] ids=request.getParameterValues("ids");
                           //new UserDao().deleteUsers(ids);
                           return "success";
    }
    

    除此之外曾经提供的管理程序适配器之外,Spring也许有本地管理程序映射,最宗旨的管理程序映射器是org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping类。它将U大切诺基L与相应的bean举办相称。比方,请看下边包车型大巴配置:

    3)灵活

    HttpSession

    @Target(ElementType.METHOD)@Retention(RetentionPolicy.RUNTIME)public @interface DumberRequestMapping { String value() default "";}
    
    <form action="${pageContext.request.contextPath }/deleUser" method="post">
    <c:forEach var="u" items="${userList }">
    <input type="checkbox" name="ids" value="${u.id } ">    ${u.id } | ${u.userName } | ${u.password }  <br />
    </c:forEach>
    <input type="submit" value="删除所选" >
    </form>
    

    org.springframework.web.servlet.FlashMapManager=org.springframework.web.servlet.support.SessionFlashMapManager

    2017-08-05 23:31:00,027 [http-bio-8084-exec-1] [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]-[DEBUG] Looking up handler method for path /test //先在RequestMappingHandlerMapping找的,也就是先找有@RequestMapping注解相应处理逻辑的方法来处理2017-08-05 23:31:00,028 [http-bio-8084-exec-1] [org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping]-[DEBUG] Did not find handler method for [/test] //在RequestMappingHandlerMapping中没找到相应的处理逻辑2017-08-05 23:31:00,028 [http-bio-8084-exec-1] [com.migo.sso.DumberRequestHandlerMapping]-[DEBUG] Looking up handler method for path /test //从DumberRequestHandlerMapping里找,发现@DumberRequestMapping所注解的方法可以处理,那就处理咯2017-08-05 23:31:00,029 [http-bio-8084-exec-1] [com.migo.sso.DumberRequestHandlerMapping]-[DEBUG] [DumberRequestHandlerMapping] handleMatch info {[/test],methods=[GET],params=[],headers=[],consumes=[],produces=[],custom=[]}, lookupPath =/test, request =org.apache.catalina.connector.RequestFacade@24a7274b2017-08-05 23:31:00,030 [http-bio-8084-exec-1] [com.migo.sso.DumberRequestHandlerMapping]-[DEBUG] Returning handler method [public java.lang.String com.migo.sso.controller.TestController.testSession(javax.servlet.http.HttpServletRequest)]2017-08-05 23:31:00,030 [http-bio-8084-exec-1] [org.springframework.beans.factory.support.DefaultListableBeanFactory]-[DEBUG] Returning cached instance of singleton bean 'testController'2017-08-05 23:31:00,030 [http-bio-8084-exec-1] [org.springframework.web.servlet.DispatcherServlet]-[DEBUG] Last-Modified value for [/test] is: -12017-08-05 23:31:00,040 [http-bio-8084-exec-1] [com.migo.sso.controller.TestController]-[DEBUG] Is dumber request ?true2017-08-05 23:31:00,040 [http-bio-8084-exec-1] [com.migo.sso.controller.TestController]-[DEBUG] Handled time ?21230126522470Handled time ?17452005683775
    

    √特别灵活的多寡表明、格式化和数据绑定机制,能选拔别的对象开展数据绑定,不必达成特定框架的API;

    调节层广东中华南体育大学程集团作方法

    请留意,order属性的留存显著了按梯次将须求由HandlerMapping管理。在此间,借使DumberRequestHandlerMapping能够选用于二个伸手,Spring将即时使用它,而无需搜索另二个可用的管理程序。

    servlet-api-2.5.jar

    √辅助灵活的U瑞鹰L到页面调控器的照耀;

    <bean name="/friends" />
    

    javax.servlet.jsp.jstl-1.2.1.jar

    7) List 类型的数额绑定 (比如批量翻新)

    笔者们以此handler将扩展RequestMappingHandlerMapping并覆盖其方法(有些措施能够从RequestMappingInfoHandlerMapping找到,其实正是重写或落到实处AbstractHandlerMethodMapping里的多少个抽象方法):

    安插计算机映射器 handler Mapping

    选择评释的措施布署计算机映射器和处理器适配器

    <bean >//此处根据自己的包进行配置 <property name="order" value="0" /></bean>
    

    org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator

    1) 导包,配置意况

    现行反革命大家更加尖锐摸底一下Spring mapping handlers。大家来促成个咱们温馨的U福睿斯L管理程序。其实很轻便(因为只要求完结最宗旨的管理指标就能够了) ,大家将替换RequestMappingHandlerMapping,并使一个简易的映射器来管理U昂科威L地址。大家的映射器将只管理静态U本田UR-VL,如:/home.html。它而不是也无法从事艺术工作术具名中获取动态参数以及也休想知道@PathVariable成分。主要对象是让大家从当中开掘Spring管理三个恳求所开展的手续。

    public class UserInfoCustom {
                                 private UserInfo user;  //包装一个pojo类型
                                 private String schoolName;  //get set 方法..
                                }
    

    org.springframework.web.servlet.RequestToViewNameTranslator=org.springframework.web.servlet.view.DefaultRequestToViewNameTranslator

    更加纯粹地说,Spring中存在三种档期的顺序的handlers。第一种是handler mappings。它们的角色定位与前方所描述的意义完全同样。它们尝试将近期呼吁与相应的controller以及中间的章程相相配。第二种是handler adapter。handler adapter从handler mappings中得到映射的controllers 和办法并调用它们。这种类型的适配器必得贯彻org.springframework.web.servlet.HandlerAdapter接口,它只有3种方法:boolean supports(Object handler):检查传入参数的目的是或不是足以因此适配器管理ModelAndView handle(HttpServletRequest request, HttpServletResponse response, Object handler) : 将须求翻译成视图。long getLastModified(HttpServletRequest request, Object handler):重回给定HttpServletRequest的最终修改日期,以微秒为单位。

    @RequestMapping("/user")  //写在类体上
    public class UserAction  {    ...  }
    

    1)Spring3 MVC使用简易,学习花费低。学习难度低于Struts2,Struts2用不上的多余效率太多

    • protected void registerHandlerMethod(Object handler,Method method,RequestMappingInfo mapping):

    • protected boolean isHandler(Class beanType): 检查bean是不是适合给定管理程序的法则。

    • protected RequestMappingInfo getMappingForMethod(Method method,Class handlerType): 为给定的Method实例提供映射的格局,该办法表示管理的方法(举个例子,使用@RequestMapping表明的controller的法子上所对应的U宝马X3L)。

    • protected HandlerMethod handleNoMatch(Set requestMappingInfos, String lookupPath, HttpServletRequest request) : 在加以的HttpServletRequest对象找不到极其的管理办法时被调用。

    • protected void handleMatch(RequestMappingInfo info, String lookupPath, HttpServletRequest request) : 当为给定的HttpServletRequest对象找到相配的拍卖措施时调用。

    -- ModelAndView

    附:

    Map<String ,Object>  //普通的map也足以,往此地放的值,最后就位于了效果域中,在页面就足以抽取${key} ;

    2 要是想钦命布署文件的渠道,能够加入参数进行指写

    --value 钦命央求的实际地址 -> @RequestMapping(value="/search_all")=@RequestMapping("/search_all")

    <!--  配置处理器映射器 handler Mapping -->
    <bean name="/search_all" class="cat.controller.UserAction"  />
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping" />  
    
    <!--   配置处理器适配器 handler Adapter -->
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter" />
    
    <!--   配置视图解析器  -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" />
    
    //Action 中的方法
    public class UserAction implements Controller {  //要实现 Controller
           public ModelAndView handleRequest(HttpServletRequest request,
                        HttpServletResponse response) throws Exception {
                        UserDao dao=new UserDao();
                        List<UserInfo> userList=dao.getAllUser();
    
                        ModelAndView mv=new ModelAndView();
                        mv.addObject("userList", userList); //相当于request.setAttribute();
                        mv.setViewName("user_manage.jsp");
    
                        return mv;
                    } 
                }
    

    Spring MVC是这段日子最玄妙的 MVC 框架,自从Spring 2.5 版本公布后,由于支持申明配置,易用性有了大开间的提升。Spring 3.0 特别完美,达成了对 Struts 2 的凌驾。今后特别多的开支公司选取了Spring MVC。

    √特别简约的非常管理;

    @Controller  //这里只能用 @Controller ,不能用 Service
    public class UserAction  {
    @RequestMapping("/search_all")  //请求的名称,最好和方法名相同
    public ModelAndView getAllUser(){
                                    UserDao dao=new UserDao();
                                    List<UserInfo> userList=dao.getAllUser();
    
                                    ModelAndView mv=new ModelAndView();
                                    mv.addObject("userList", userList); //相当于request.setAttribute();
                                    mv.setViewName("user_manage.jsp");
    
                                    return mv;
                                }
                         }
    
    public class UserInfoCustomL {
                                  private List<UserInfo> userList;  //生成get set 
                          }            
    

    2 如若想钦命布置文件的门道,能够参加参数进行指写

    <body>
    <c:forEach var="u" items="${userList }">
       ${u.id } | ${u.userName } | ${u.password }  <br />
    </c:forEach>
    </body>
    

    本文由68399皇家赌场发布于集群主机,转载请注明出处:SpringMVC入门知识2

    关键词: 68399皇家赌场 Java 编程语言 处理器 源码

上一篇:C# 生成轻便验证码

下一篇:没有了