SpringMVC Annotation Configuration

Keywords: Java Spring xml JSP encoding

Configuring spring mvc with annotations

(1) configuration file for spring mvc

<?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 https://www.springframework.org/schema/context/spring-context.xsd">

    <!--Configuration Package Scan-->
    <context:component-scan base-package="com.chy.controller" />

    <!-- Configure Annotated HandlerMapping-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />

    <!--Configure Annotated HandlerAdapter-->
    <bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter" />

    <!--Configure View Parser-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--prefix-->
        <property name="prefix" value="/WEB-INF/jsp/" />
        <!--Suffix-->
        <property name="suffix" value=".jsp" />
    </bean>
    
</beans>

 

 

(2)controller

//stay controller Upper label@Controller
@org.springframework.stereotype.Controller
public class UserController{

    //Label on business methods@RequestMapping
    @RequestMapping("/userController")
    public ModelAndView handle(){
        ModelAndView mav = new ModelAndView("user_info");
        User user = new User();
        user.setUsername("chy");
        user.setPassword("abcd");
        mav.addObject("user", user);
        return mav;
    }

}

 

  • Controller does not need to implement interfaces, just label @Controller on the controller, and do not need to configure <bean>for the controller in xml

(Configuring with XML requires configuring <bean> of this controller in xml, cumbersome and cumbersome XML files)

 

  • There can be multiple business methods in the controller

(There can only be one business method in the controller when using xml configuration, which is inconvenient, such as UserController, which has saveUser, updateUser, queryUser, etc.)

 

  • The parameter type and return value type of a business method can be arbitrary

(parameter types and return values are fixed when using xml configuration, ajax queries data, accesses static pages, all need to return to ModelAndView, not necessary)

 

Usually you configure it with annotations.

 

 

 

 

@RequestMapping Configure Business Methods

(1) value specifies the url to which this business method corresponds (maps)

@RequestMapping(value = "/userController")
//only value Abbreviate an attribute
@RequestMapping("/userController")  

//Slash that doesn't start
@RequestMapping(value = "userController")
@RequestMapping("userController")

The above four styles are equivalent, and the red ones are the most common.

 

Access paths are:

http://localhost:8080/springmvc_war_exploded/userController

//You can also add at the end.do
http://localhost:8080/springmvc_war_exploded/userController.do

 

 

 

 

(3) method

    @RequestMapping(value = "/userController",method = RequestMethod.GET)
    @RequestMapping(value = "/userController",method = RequestMethod.POST)

This method is used to process business only if the request address meets and the request is GET|POST.

 

The above two notes are equivalent to:

    @GetMapping(value = "/userController")
    @PostMapping(value = "/userController")

 

 

 

 

(4) Stitching of url maps

Sometimes there are multiple business methods in the controller:

@org.springframework.stereotype.Controllerpublic class UserController{
    
    @RequestMapping("/userController/saveUser")
    public void saveUser(){
        //......
    } 
    
    @RequestMapping("/userController/deleteUser")
    public void deleteUser(){
        //......
    }
    
    @RequestMapping("/userController/updateUser")
    public void updateUser(User user){
        //......
    }
    
    @RequestMapping("/userController/queryUser")
    public User queryUser(){
        //......
    }
    
}

Write a long list of URLs each time, which is cumbersome.

 

You can propose a common parent path, write it on the controller, and write the child path on the business method:

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/saveUser")
    public void saveUser(){
        //......
    }

    @RequestMapping("/deleteUser")
    public void deleteUser(){
        //......
    }

    @RequestMapping("/updateUser")
    public void updateUser(User user){
        //......
    }

    @RequestMapping("/queryUser")
    public User queryUser(){
        //......
    }

}

Access is the same as before.

 

 

 

 

Business method parameter types, number of parameters can be arbitrary, use as needed

Common parameter types:

  • HttpServletRequest,HttpServletResponse,HttpSession
  • Model, ModelMap (passing data to view)
  • Simple data types, entity classes (receive data passed by the form)

 

Common return value types:

  • ModeAndView
  • String (returns view name)

 

 

Example - Return view name

  @RequestMapping("/userController")
    public String handler(){
        //....
        return "user_info";
    }

 

 

Example of using Model to pass data to a view

    @RequestMapping("/userController")
    public String handler(Model model){
        User user = new User();
        user.setUsername("chy");
        user.setPassword("abcd");
        
        model.addAttribute("user", user);
        return "user_info";
    }

You can get the corresponding value in the view by ${key}.

Model s can store multiple data, using multiple setAttributes () can make the data type different (essentially, using Map to store the data).

 

 

Example Direct Output to Browser

    @RequestMapping("/userController")
    public void handler(HttpServletResponse response) throws IOException {
        response.getWriter().print("<h1>hello</h1>");
    }

The browser resolves the html tags inside.

Note that print() is the output to the browser page. write() is to write data to the browser. The browser will save the contents of write() to a file (download).

 

 

 

 

Forward, redirect to other business methods

@org.springframework.stereotype.Controller
@RequestMapping("/userController")
public class UserController{

    @RequestMapping("/handler1")
    public String handler1() throws IOException {
        //Forward to handler2 Handle
        return "forward:handler2";
    }

    @RequestMapping("/handler2")
    public void handler2(HttpServletResponse response) throws IOException {
       //......
    }

}

Back to String, String would have been resolved to the view name, and we just need to add the keywords: forward, redirect.

 

It is important to note that springmvc originally parses the returned string as a view name and forwards it to the corresponding view. To forward to the view (jsp, html, etc.), write the view name directly, without using the keywords forward, redirect.

If forward and redirect keywords are not required to be forwarded to the view, the configured view name stitching is not valid for these two keywords, only the full path can be written:

return "forward:/WEB-INF/jsp/user_info.jsp";

 

 

If it is a business method that forwards or redirects to another controller, only the full path can be written.

 

If other business methods are forwarded, redirected to this controller:

  • Writable full path
return "forward:/userController/handler2";

 

  • You can also write only subpaths, but not at the beginning of them/

Whether handler2() is labeled @RequestMapping("/handler2") or @RequestMapping("handler2"), this is the only way:

return "forward:handler2";

 

 

You can also use a servlet to do this by passing in parameters of type HttpServletRequest | HttpServletResponse.

 

 

 

 

I use new in my business methods. In fact, when using spring, try not to use new, but instead use dependency injection with dependency injection.

If it's a generic bean, such as a tool class, the instances are all the same, designed as singletons, placed in a spring container, used as member variables, and automatically assembled with annotations.

If the instances are different, such as the User class, each user's information is different, designed as multiple instances, placed in the spring container, used as member variables, and assembled automatically with annotations, you can call the setter method assignment of the bean s in the method.

Posted by pwes24 on Thu, 30 Jan 2020 17:43:35 -0800