Spring Learning Note-SPRINGMVC Note-based controller (DEMO)

Source: Internet
Author: User

SPRINGMVC's overall operating flow chart:

Based on @Controller and @RequestMapping is SPRINGMVC sample code

    • Configuring the SPRINGMVC core dispatcher in Web. xmlDispatcherServlet
....<Servlet>       <Servlet-name>Springmvc</servlet-name>       <Servlet-class>Org.Springframework.Web.Servlet.Dispatcherservlet</servlet-class>       <Init-param>           <Param-name>Contextconfiglocation</param-name>           <Param-value>Classpath:springmvc-servlet</param-value>       </init-param>       <Locad-on-startup>1</load-on-startup></servlet><Servlet-mapping>        <Servlet-name>Springmvc</servlet-name>        <Url-pattern>/</url-pattern></servlet-mapping>
    • Configuring the SPRINGMVC core configuration file Springmvc-servlet.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:mvc="Http://www.springframework.org/schema/mvc"       Xmlns:context="Http://www.springframework.org/schema/context"       xmlns:p="http://www.springframework.org/schema/p"       xsi:schemalocation="Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/sp Ring-beans-3.0.xsd Http://www.springframework.org/schema/context htt P://www.springframework.org/schema/context/spring-context-3.0.xsd http://www.springframework.or G/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd ">    <!--annotation class scan path --    <context:component-scan base-pakage="Com.springmvc.test.controller"/>    <!--add Springmvc annotation driver --    <mvc:annotation-driven/>    <!--register SPIRNGMVC Red The most commonly used view resolver: Internal Resource View Resolver --    <bean id= "viewresolver"class=" Org.springframework.web.servlet.view.InternalResourceViewResolver ">                    <!--prefixes --         < property name="prefix" value="/web-inf/jsp/"/>          <!--suffix --         < property name="suffix" value=""/>    </Bean></Beans>

It should be noted that the <mvc:annotation-driven/> purpose of this tag is to register an annotation-based processor mapping (handlermapping).

    • Writing controller Classes
Packagecom. Springmvc. Test. Controller;import org. Apache. Commons. Logging. Log;import org. Apache. Commons. Logging. Logfactory;import org. Springframework. Stereotype. Controller;import org. Springframework. UI. Model;import org. Springframework. Web. Bind. Annotation. Requestmapping;Importcom. Springmvc. Test. Domain. Product;Add controller annotations, register to spring container @controllerpublic class productcontroller{private static final Log logger = logfactory. GetLog(Productcontroller. Class);Add requestmapping, map to a URI @RequestMapping (value="/product_input") public String inputproduct () {Logger. Info("Inputproduct called");Return"Productform";}//Save commodity @RequestMapping (value="/product_save") Public String saveproduct (Product Product,model Model) {Logger. Info("Save Product called");Save product model. AddAttribute("Product", product); 'Return"ProductDetails";}}

There are two ways to explain that for the model parameter in the second method, SPRINGMVC creates a model instance for each request to increase the properties that need to display the consequences of the re-view, which is to pass the data from the controller to the JSP using a qualified object

model.addAttribute("product",product);

In this way, product can be accessed as if it were added to the httpservletrequest.

    • JSP page (slightly).

The above is a simple but relatively complete example of SPRINGMVC code.

Here are two more commonly used knowledge points: Request parameters and Classpath variables, @ModelAttribute

Request parameters and path variables can be used to send data to the server, both are part of the URL, request parameters in the form of Key=value, and separated by &, such as the following

http://localhost:8080/springmvc/product_retrieve?productId=3

In traditional servlet programming, you can use the HttpServletRequest GetParameter method to obtain a request parameter value:

Stringrequest.getParameter("productId");

SPRINGMVC provides a relatively concise way to get request parameter values: Annotate method parameters by using the Requestparam annotation type, for example

publicvoidsendProductint productId)

A path variable is like a request parameter, but there is no key part, just a value, like this

/product_view/productId

Booing ProductID is an integer that marks the product identifier. In Springmvc, ProductID is called a path variable, which is used to send a value to the server.
eg

@RequestMapping("/product_view/{id}")publicviewProduct(@PathVariable Long id, Model model){      Product product = productService.get(id);      model.addAttribute(“product”,product);      return"productView"}

1) to use a path variable, first add a variable to the value attribute of the requestmappng annotation, which must be placed between the curly braces. For example, the above instance.

2) then add a variable with the same name in the method signature, plus the @pathvariable annotation. Take a look at the method signature in the example above, and when the method is called, the ID value of the request URL is copied to the path variable and can be used in the method.
You can also specify multiple path variables

@RequestMapping("/product_view/{userId}/{orderId}")

@ModelAttribute annotation Types

SPRINGMVC creates an instance of the model type each time the request method is called, and if you intend to use the instance, you can add a model object to the method.

You can actually add @modelatttribute annotations to the model instance in the method you use.

You can annotate a method or method parameter with a @modelattribute annotation. The method with the @modelattribute annotation adds the parameter object that it enters or creates to the model object, for example, an order instance that is created each time the SubmitOrder method is called in Springmvc.

@RequestMapping(method=RequestMethod.POST)public String submitOrder(@ModelAttribute("newOrder") Order order, Model model){     ......}

Entering or creating an order instance will be added to the model object with the Neworder build value. If a key value name is not defined, the class name of the object is used, for example, the order instance is added to the model object using the key value order each time the following method is called.

publicStringOrderorder,Model model)

The second purpose of the @ModelAttribute is to label a non-request processing method. The method that is annotated by @modelattribute is called every time that the controller's request processing method is called. Springmvc calls the method with the @modelattribute annotation before invoking the request processing method. A method with @modelattribute annotations can return an object or a void type, and if returned is an object, the returned object is automatically added to the model.

@ModelAttributepublicaddProduct(@RequestParam String productId){     return productService.get(productId);}

If the method return value is void, you must also add a table of model type and manually add the instance to the model

@ModelAttributepublicvoidpopulateModel(@RequestParam String id,Model model){     model.addAttriute(new Account(id));}

Reference: SPRINGMVC study Guide.

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Spring Learning Note-SPRINGMVC Note-based controller (DEMO)

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.