In the last article of Spring+SpringMVC+Mybatis integration, SSM integration was mentioned, and a simple query function was added to it. The purpose is just to sort out the whole integration process. Here are some details about SpringMVC’s Controller based on the project in the previous article.

First of all, attached is the overall project structure diagram, attached is the download address of the entire code engineering, the following test cases are based on the following test project.


1. Note form about Controller

Controller annotation development can be implemented using @Controller annotation. Then configure the annotation scanner in the springMVC.xml configuration file to use the annotation form for Controller development. Here is a simple example using helloWorld

① Configure the annotation scanner in springMVC.xml

It also includes the processor mapper, processor adapter, and view resolver required by SpringMVC. You can see these components in the introduction of SpringMVC, which starts with springMVC’s processing flow and the relationships between components. Here we directly use the following configuration method to configure

Write a simple HelloWorld, request the Controller in the browser, and print it on the page

 1 package cn.test.ssm.controller;
 2 
 3 import org.springframework.stereotype.Controller;
 4 import org.springframework.web.bind.annotation.RequestMapping;
 5 import org.springframework.web.servlet.ModelAndView;
 6 
 7 @Controller
 8 public class HelloWorldController {
 9 
10     @RequestMapping("/helloWorld.do")
11     public ModelAndView helloWorld() throws Exception{
12         ModelAndView modelAndView = new ModelAndView();
13         modelAndView.addObject("test"."HelloSSM");
14         modelAndView.setViewName("/WEB-INF/items/hello.jsp");
15         returnmodelAndView; 17 16}}Copy the code


 1 <%@ page contentType="text/html; charset=UTF-8" language="java" %>
 2 <html>
 3 <head>
 4     <title>$Title$</title> 5 </head> 6 <body> 7 Tests Controller 8${test}
 9 </body>
10 </html>Copy the code


(3) request to http://localhost:8080/TestSSM2/helloWorld.do in the address bar, then the output

RequestMapping

1. Use different processor mapping rules

RequestMapping allows you to use different processor mapping rules. The RequestMapping annotation controls the path and mode of HTTP requests (get, post……). In the same Controller, different mapping methods can be written to map different requests of the browser.

RequestMapping(value=”/test.do”) or @requestMapping (“/test), where value is an array and multiple urls can be mapped to the same method

B) RequestMapping (RequestMapping, RequestMapping, RequestMapping

① First add the Sql configuration for querying details in productDemo. XML in mapper

    <select id="queryProductInfo" parameterType="java.lang.Integer" resultType="cn.test.ssm.po.ProductExtend">
        SELECT pname,shop_price FROM product WHERE pid = #{id}
    </select>Copy the code

② Add the above methods to the Mapper interface

③ Add the corresponding method and method implementation to the service interface

The service interface

  

Interface implementation class

  

④ Add queryInfo method in controller layer, which uses RequestMapping to map two different request corresponding method implementation

 1 package cn.test.ssm.controller;
 2 
 3 import cn.test.ssm.po.ProductExtend;
 4 import cn.test.ssm.service.ProductService;
 5 import org.springframework.beans.factory.annotation.Autowired;
 6 import org.springframework.stereotype.Controller;
 7 import org.springframework.web.bind.annotation.RequestMapping;
 8 import org.springframework.web.servlet.ModelAndView;
 9 
10 import java.util.List;
11 
12 @Controller
13 public class ProductController {
14 
15     @Autowired
16     private ProductService productService;
17 
18     @RequestMapping("/queryList.do"19 public ModelAndView queryList() throws Exception{20 // Call method 21 List<ProductExtend> productExtendList = productService.findProductListByName(null); 22 // Return ModelandView 23 ModelandView ModelandView = new ModelandView (); 24 modelAndView.addObject(productExtendList); 25 modelAndView.setViewName("/WEB-INF/items/itemsList.jsp");
26         return modelAndView;
27     }
28 
29     @RequestMapping("/queryInfo.do")
30     public ModelAndView queryInfo() throws Exception {
31 
32         ProductExtend productExtend = productService.queryProductInfo(1);
33         productExtend.setDesc("This is the camera.");
34         ModelAndView modelAndView = new ModelAndView();
35         modelAndView.addObject(productExtend);
36         modelAndView.setViewName("/WEB-INF/items/editItem.jsp");
37         returnmodelAndView; 38}} 39Copy the code


⑤ Finally click query in the query list to view the details

2. Narrow the request mapping

A) Add @requestMapping (URL) to class to specify a common request prefix, restrict all method requests in this class url must start with the request prefix, use this method to manage the URL category.

B) put @requestMapping above the class name and set the request prefix

@Controller

@RequestMapping(“/test”)

Then set the request mapping URL above the method name:

@RequestMapping(“/queryItem “)

To access the address is: http://localhost:8080/TestSSM2/test/queryList.do

  

3. Restriction on HTTP request mode

A) Specify the POST method @requestMapping (method = RequestMethod.

POST

HTTP Status 405-request method ‘Get’ not supported, for example

  

Then go to http://localhost:8080/TestSSM2/test/queryList.do, it would be the following error

  

B) specify @requestMapping (method = RequestMethod);

GET

HTTP Status 405-request method ‘Post’ not supported

C) the GET and POST are: @ RequestMapping (method = {RequestMethod. GET RequestMethod. POST})


3. The return value of Controller

1. Return to ModelAndView

A) We wrote controllers in this way, basically defining a ModelAndView object, populating the model (the data from the database) and the logical view (the path to the specified JSP, etc.), and returning it

B) e.g.

2. Use void

A) Request and response can be defined on the controller method parameter, using request or response to specify the response result:

(1) using the request to the page: request. GetRequestDispatcher (” path “page). The forward (request, response);

Such as:

    @RequestMapping("/test_void.do")
    public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception{
        request.setAttribute("test"."Tests that return void");
        request.getRequestDispatcher("/WEB-INF/items/hello.jsp").forward(request,response);
    }Copy the code

And then output the result

② Redirection through response page: Response.sendreDirect (” URL “), same as above

3. Use String as return value

A) The method parameter in Controller is model, and then the data is returned to the request page through the parameter. Finally, the return string can specify the logical view name (path information), which is parsed into the physical view address by the view parser;

1     @RequestMapping("/testString.do")
2     public String testString(Model Model) throws Exception {3 // Other operations performed 4 // Returning data to the request page with parameter Model is similar to returning addObject method 5 in ModelAndView model.addAttribute("testString"."testString"); 6 // Then return the logical view name, which is parsed by the view parser into the corresponding JSP and other paths 7return "test/helloWorld"; 8}Copy the code


/item/ queryitem. action: /test/queryTest? test1Key=test1Value&test2Key=test2Value

C) Forwarding: after the method in Controller is executed, another Controller method is executed. After the following information is modified, the page is turned to the information display page. The ID parameter of the modified information can be added to the modification method. Return “forward:update.action”; return”forward:update.action”; Way forward is equivalent to “request. GetRequestDispatcher () forward (request, response)”, after forwarding your browser’s address bar or the original address. Forwarding does not execute a new request and response, but shares the same request and response with the previous request. So parameters requested before forwarding can still be read after forwarding.


4. Parameter binding of SpringMVC

1. Parameter binding process

A) Parameter binding: The annotation adapter ADAPTS the RequestMapping tag’s methods to bind parameters to the form of the data requested from the browser (key/value or form information) in the method, so the parameter binding in SpringMVC is done through the Controller’s method parameters.

B) Default parameter types supported by parameter bindings. You can define the following types of parameters directly above the Controller method and then use them directly inside the method body

HttpServletRequest (HttpServletRequest)

②HttpServletResponse (response)

③HTTPSession (get the object stored in session from the session object)

${test.xxxx} = ${test.xxxx} = ${test.xxxx} = ${test.xxxx} As in the case of the Controller method returning String above)

2. Use RequestParam annotations

A) Without annotations, the key name of the parameter submitted in the front end should be the same as the parameter of the method in the Controller, otherwise it will not be matched in the request field. We use this annotation when we need to set parameters in the Controller method to different parameter names

B) Brief notes: @requestParam is used to bind a single request parameter.

For example, value= “test_id” indicates that the value of the request parameter whose name is test_id will be passed in.

(2) Required: Indicates whether a parameter must be passed in. The default value is true, indicating that the request must have a parameter. Otherwise, HTTP Status 400 – Required Integer parameter ‘XXXX’ is not present is reported

③defaultValue: indicates the defaultValue if there is no parameter with the same name

For example, the parameter name is ID, but value=” test_id” is used to qualify the request parameter name as test_id, so the page must pass the parameter name as test_id.

Note: An exception will be thrown if test_id is not present in the request parameter: HTTP Status 500 – Required Integer parameter ‘test_id’ is not present

Here, the itest_id parameter is required to be passed with required=true, and 400 is reported if it is not passed. You can use defaultvalue to set the defaultvalue, and you can not pass the item_id parameter value even if required=true

C) The following uses examples to illustrate the above points

① Test notes

The test project is similar to the project built in the previous SSM integration, where only one function is the query list. We added the function to query the details in RequestMapping, but we did not receive the data from the front end, all use the default value 1.

 1     @RequestMapping("/queryInfo.do")
 2     public ModelAndView queryInfo(@RequestParam(value = "id") Integer testId) throws Exception {3 // If no annotations are used, the parameter name in the method parameter must be the same as the key name in the front-end request. After using can custom 4 ProductExtend ProductExtend = productService. QueryProductInfo (testId);
 5 
 6         productExtend.setDesc("This is the camera.");
 7         ModelAndView modelAndView = new ModelAndView();
 8         modelAndView.addObject(productExtend);
 9         modelAndView.setViewName("/WEB-INF/items/editItem.jsp");
10         returnmodelAndView; 11}Copy the code


Then we tested again, visit http://localhost:8080/TestSSM2/test/queryList.do first, then look at the id = 2

We get the following result

  

When I compare id=1  

 

(2) the test required

Plus in the method above

And then test, enter http://localhost:8080/TestSSM2/test/queryInfo.do, without parameters, quote us the following error

  

(3) test defaultValue

If no key/value is passed in when required is set to true, the above exception is not reported when defaultValue is set in Controller. Change the Controller method parameter to the following

  

And then directly enter http://localhost:8080/TestSSM2/test/queryInfo.do without id parameter, or be able to query data to the default id = 1

  

3. Common POJO type binding

If the parameter name is the same as the attribute name in the object, set the parameter value in the POJO object. Then define the parameter value in the Contrller method: If the request parameter name is the same as the poJO property name, the request parameter is automatically assigned to the POJO property.

B) We now add the following method to the Controller to output data submitted from the page above

  

C) Click Submit data in the page form

  

And then output it in the background

4. Customize parameter binding

A) Define a parameter binding of type Date. First suggest a Java utility class for the converter that converts String to java.util.Date

 1 package cn.test.ssm.controller.converter;
 2 
 3 
 4 import org.springframework.core.convert.converter.Converter;
 5 
 6 import java.text.ParseException;
 7 import java.text.SimpleDateFormat;
 8 import java.util.Date;
 9 
10 public class StringToDateConverter implements Converter<String, Date> {
11     @Override
12     public Date convert(String s) {
13 
14         try {
15             SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
16             returnsimpleDateFormat.parse(s); 17 } catch (ParseException e) { 18 e.printStackTrace(); 19} 20returnnull; 22 21}}Copy the code


Then configure the above converter in springMVC.xml

1 <! > 2 < MVC :annotation-driven Conversion -service="converterService"></mvc:annotation-driven>
 3 
 4     <bean id="converterService" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"5 > <! -- Configure converter --> 6 <property name="converters">
 7             <list>
 8                 <bean class="cn.test.ssm.controller.converter.StringToDateConverter"></bean>
 9             </list>
10         </property>
11     </bean>Copy the code


Print all submitted data in the background. Note that the createTime parameter has been set to Date and the createTime input has been added to the front page

1     @RequestMapping("/printInfo.action")
2     public String printInfo(Product product, Date createtime) throws Exception {
3         System.out.println("Output information"+product);
4         System.out.println(createtime);
5         return "forward:queryList.do"; 6}Copy the code

Finally, enter a date type in the browser for the following input test

Finally, the printed information is viewed in the background

5. Customize the packaging type

A) the current day is more complex when the incoming parameters (such as cover the correlation between different data entity class extension attribute information of the query or an entity class), at this time we can add additional attributes in the extension class and then as we custom packaging attributes of a class, then the front desk page into the parameter name is set to a wrapper class attribute names. Entity class attributes (testextend.name)

B) Look at the following example, which is a simple implementation of a fuzzy query

We first add an attribute that accepts fuzzy query parameters to the ProductExtend extension of the entity class Product

  

② Then define a wrapper type in which the above extension type is set as a property

  

③ Then set the custom wrapper type as a method parameter in the Controller method for parameter binding and call the service method for query

  

④ Check in the front desk

  

⑤ Check whether the parameters sent from the front end are received in debug mode. The parameters sent from the page can be received

  

And the query result after calling the service method is also

  

The final page displays the results