Springmvc frame Finishing (I.)

Source: Internet
Author: User
Tags bind relative
Blog mainly on the SPRINGMVC framework of knowledge points, this chapter introduces the SPRINGMVC HelloWorld environment, the use of common annotations, ant path style, restful programming style, Finally, use SPRINGMVC to implement a restful programming style crud.

MVC Overview model (models)-view (view)-controller (Controller) model (models): business models: Business processes and business logic Data Model: The data that is displayed on the page. JavaBean for data stored in the database View : A page, a program interface that interacts directly with the user Controller: Scheduler controls the forwarding logic for the entire Web site
SRINGMVC Overview Springmvc is an expression layer framework based on MVC concept, and is the most mainstream MVC framework at present. Spring MVC uses a set of MVC annotations to make POJO the controller that handles requests without having to implement any interfaces. RESTful URL requests feature a loosely coupled pluggable component structure that is more scalable and flexible than other MVC frameworks


SPRINGMVC Running Process Springmvc running logic:        ① client request submission to Dispatcherservlet (SPRINGMVC Front Controller)       The ② is queried by the Dispatcherservlet controller for one or more handlermapping to find the controller that handles the request.            based on the information provided by handlermapping, then find the adapter that can really parse and invoke the business logic method.      ③dispatcherservlet submits the request to the controller (also known as handler), that is, using the adapter to execute the target method            MV = Ha.handle (processedrequest, Response, Mappedhandler.gethandler ());      ④controller after calling business logic processing, return Modelandview            Modelandview contains information to go to the view, as well as additional information      ⑤dispatcherservlet query one or more Viewresoler view resolvers to find the Modelandview specified view           viewresoler for view resolution, call Render. Parse out which page       The ⑥ view is responsible for displaying the results to clients, rendering            RequestDispatcher Rd          &N Bsp; rd.forward (requesttoexpose, response); Summary: Request reached--find the adapter that can execute the target method---> Execute target method---> Return view information and data information (MV)---> Render view based on return information---> Presentation view
HelloWorld Environment Construction
① Import jar Package Spring Base package Com.springsource.net.sf.cglib-2.2.0.jar Com.springsource.org.aopalliance-1.0.0.jar Com.springsource.org.aspectj.weaver-1.6.8.release.jar Commons-logging-1.1.3.jar Spring-aop-4.0.0.RELEASE.jar Spring-aspects-4.0.0.release.jar Spring-beans-4.0.0.release.jar Spring-context-4.0.0.release.jar Spring-core-4.0.0.release.jar Spring-expression-4.0.0.release.jar
SPRINGMVC Required Package Spring-web-4.0.0.release.jar Spring-webmvc-4.0.0.release.jar
② Configuring front-end Controller <!--SPRINGMVC Front-end controller in Web. XML, it is a true servlet inherited from HttpServlet     so the configuration and servlet configuration are basically consistent--<!- -The front controller of this Spring WEB application, responsible for handling all application requests--&NBSP;&NBS P;  <servlet>         <servlet-name> Springdispatcherservlet</servlet-name>         <servlet-class >org.springframework.web.servlet.DispatcherServlet</servlet-class>          <init-param>              <param-name>contextConfigLocation</param-name>             <!-- This location writes the SPRINGMVC configuration file--             < Param-value>location</param-value>         </init-param>   &NBsp     <!--This is the priority of the boot, the smaller the value, the higher the priority--        < load-on-startup>1</load-on-startup>     </servlet>      <!-- Configure intercept those requests-    <!--Map all requests to the dispatcherservlet for handling-     <servlet-mapping>         <servlet-name> springdispatcherservlet</servlet-name>         <!--configured here/, All requests can be intercepted while overwriting the Defaultservlet configuration, so that all requests are intercepted by our front-end controller           also embodies the restful style of programming                   <url-pattern>/</url-pattern >     </servlet-mapping>       ③ Create SPRINGMVC profile, and write the address of the configuration file to location            src directory new
Configure location (classpath in the classpath)<param-value>classpath:springmvc.xml</param-value> The basic environment is built.
④ write a simple request response process, test the Run Environment ①index.jsp (Request/hello)

Import Org.springframework.stereotype.Controller; Import org.springframework.web.bind.annotation.RequestMapping; Based on annotation injection, the relevant annotations need to be added @Controller public class Myhandle {//Map request address @RequestMapping (" /hello") Public String Hello () {System.out.println (" received request ");     Return "Success"; }}③ Configure the SPRINGMVC framework to allow the framework to help process requests (Springmvc.xml) <?xml version= "1.0" encoding= "UTF-8"?> <beans xmlns= "http: Www.springframework.org/schema/beans "xmlns:xsi=" Http://www.w3.org/2001/XMLSchema-instance "xmlns:context=" Http://www.springframework.org/schema/context "xsi:schemalocation=" Http://www.springframework.org/schema/beans Http://www.springframework.org/schema/beans/spring-beans.xsd Http://www.springframework.org/schema/context http ://www.springframework.org/schema/context/spring-context-4.0.xsd ">
<!--automatic scanning of the package, handle class with controller annotations is injected--< Context:component-scan base-package= "Com.springmvc.handle" ></context:component-scan> <!--configuration View resolver for rendering MV-- <bean id= "Viewresolver" class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" > <!--Configure a prefix to the return address -- <property name= "prefix" value= "/" ></property> <!--Configure a suffix -- <property name= "suffix" value= ". jsp" ></property> <!--/success.jsp (prefix + return result + suffix together form a forwarding address)-- </bean>
</beans>④ Writing response page success.jsp @RequestMapping① is labeled on the class, indicating that all handle methods in the class begin with this mapped address. Relative to the WEB application root directory ② on the method, if there is no @requestmapping on the class, directly represents the request address, if there is a class on the map + method on the map together constitute the request address. Relative to the URL marked on the class
Function: Dispatcherservlet intercepts the request, it determines the processing method corresponding to the request through the mapping information provided by the @requestmapping on the controller. Properties: Value: Sets the request address, the meaning of labeling on a class and the means of labeling/representing on a method: set what kind of request a method handles, and method is an array that can handle multiple requests that meet the requirements. The default is to handle any request params: Set request parameters (can set multiple request parameters) (support simple expression) when the params is configured, must be in the request to pass the configuration parameters, mismatch or error 404 when setting multiple Parameters must be set, or error 404 conclusion: Params set request parameters must match exactly, otherwise the error params =!user indicates that the request parameter cannot be set to user, the other can be params = User!=1 to indicate that the request parameter value cannot equals 1
Code with params:     /**      * This request address must have Password,user can have no, but if the value of the user cannot be 1, Cannot have username      * Other requests      * @return      */ & nbsp;   @RequestMapping (value= "/test5", params={"user!=1", "Password", "!username"})      public String test5 () {        system.out.println ("Accept to request");          return "Success";     }            headers Set request header       & nbsp;    send request header must contain content in headers, different browser request headers, can be used to distinguish between different browsers     /**       * Headers (set only one browser can access)      * @return      */      @RequestMapping (value= "/testheader", headers= "user-agent=mozilla/5.0 (Windows NT 10.0; WOW64; rv:49.0) gecko/20100101 FIREFOX/49.0 ")     public String Test6 () {         System.out.println ("Accept to request");         return "Success";     }
after setting the condition of the @requestmapping, all the above rules must be satisfied when sending the request, otherwise the error and nothing is written to indicate the default rule.
return StringForwarding address, the view resolver configured in the SPRINGMVC configuration file will also wrap this address
ant path style ? : Matches any one of the characters *: matches any 0 or more characters * *: Indicates multi-layered fuzzy match (to use * * Multilayer fuzzy match to wrap these two * *) (so that you can write a multi-layered nested path before the specific path) matching principle: When all are fuzzy matching, first accurate and then Fuzzy, first range of large again range small
Example: Ant path:/user/*/createuser: Matching/user/aaa/createuser,/user/bbb/createuser, etc. url/user/**/c Reateuser: Match/user/createuser,/user/aaa/bbb/createuser and so on Url/user/createuser??: Horse With/user/createuseraa,/USER/CREATEUSERBB and other URLs
Import Org.springframework.stereotype.Controller; Import org.springframework.web.bind.annotation.RequestMapping;
@Controller public class Anturlpathhandle {    /**      * ant path style       * &NBSP;&NBSP;&NBSP;&NBSP;&NBSP;?: means match any one of the characters      *       *: matches any 0 or more characters      *      **: Indicates multi-layer fuzzy match (to use * * Multilayer fuzzy match to wrap these two * *)      *      *       When all are fuzzy matching, first accurate in the Blur, first range of large again range small      * @return      */     @RequestMapping (value= "/?? Ervice ")     public String test2 () {         SYSTEM.OUT.PRINTLN ("a request to receive a request address is a fuzzy match");         return "Success";     }      @RequestMapping (value= "/*ervice")      Public String test3 () {        system.out.println ("Received request address is fuzzy matching * request");         return "Success";     }      @RequestMapping (value= "/*/*ervice")      Public String Test5 () {        system.out.println ("received request address is a request for fuzzy matching of a layer *");         return "Success";     }      @RequestMapping (value= "/**/ervice")      Public String test4 () {        system.out.println ("The Received request address is a fuzzy match * * multi-layered blur request" );         return "Success";     }

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.