This article brings you a detailed introduction to the basic configuration of SpringMVC. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.
Today we will talk about the basic configuration of SpringMVC. Currently, more and more mainstream frameworks support annotations, and our invincible Spring also supports "zero configuration" based on annotations.
Advantages of annotations compared to XML: It can make full use of Java's reflection mechanism to obtain structural information in a class. This information can effectively reduce configuration work. Annotations and Java code are located in one file, which is more conducive to maintenance.
Note: Annotations can only be used after Spring 2.5 version.
The annotation method combines the definition information of the Bean and the implementation class of the Bean. The annotations provided by Spring are:
@Component: Declare a common Bean class
@Repository: Declare a persistence layer Dao class
@Service: Declare a business layer class
@Controller: Declare a controller class
I believe that friends are already very familiar with these four annotations, so there is no need to talk nonsense. When we use annotations, don’t forget to scan them in the class! ! !
@RequestMapping (a very core annotation), this annotation is used to specify the request URL of the controller.
In the class definition of the controller: provide preliminary mapping information and add a prefix to all request methods under the class.
Method definition in the controller class: Provide further mapping information and provide the request path of the method
After DispacherServlet intercepts the request, Confirm the processing method corresponding to the request through the mapping information provided by @RequestMapping on the controller.
@Controller @RequestMapping("user") public class UserController { @RequestMapping("/hello") public String hello(){ return "hello"; } }
At this time, the path we request is http://localhost:8080/SpringMvcDemo2/user/hello
@RequestMapping In addition to mapping the request URL request, you can also use the request method, For requests with request parameters and request headers, there are several parameters in the annotation:
1) value: Indicates the URL of the request
2) Method: Indicates the request method (GET/POST)
3) params: Represents the parameters of the request
4) heads: Request headers
The relationship between them is and. The joint use of multiple requests can make the request more accurate. change.
@RequestMapping(value="hello2",method=RequestMethod.POST,params={"username","userpass"},headers="contentType=text/*") public String hello2(){ return "hello"; }
This code indicates that the requested address is hello. The request method is Post and must contain two parameters: username and userpass. The request header contentType must start with text/. We can write two URLs with the same method. The request method, one POST and the other GET, will be called strictly according to the settings.
@RequestMapping also supports Ant-style URLs and supports 3 wildcards in Ant.
? : Indicates configuring a character.
*: Matches any characters
**: Matches multi-layer paths
Parameter processing in SpringMVC:
@pathVariable: URL template method
Used to map placeholders in URLs. The mapped variable names must be consistent with the names in the placeholders, like this our The request address will be http://localhost:8080/SpringMvcDemo2/user/testPathVariable/Miya. This miya is the parameter we passed. In the traditional URL, testPathVariable? username=miya but this is not conducive to Baidu's inclusion.
@RequestMapping("/testPathVariable/{username}") public String hello3(@PathVariable("username")String username){ System.out.println("username : " + username); return "hello"; }
@RequestParam: Get the request parameters. If the request parameter name is consistent with the name of the type, we can omit this annotation and still receive the value.
@RequestMapping("/textParam") public String hello4(@RequestParam("username")String username,@RequestParam("userpass")String userpass){ System.out.println("userpass : " + userpass); return "hello"; }
@RequestHeader: Get the parameters of the request header
There are three parameters here, value: the name of the specified parameter, required: the specified parameter Whether it is required, defaultValue: specifies the default value of the parameter.
@RequestMapping("/testRequestHeader") public String hello5(@RequestHeader("Accept-Language") String language){ System.out.println("language=" + language); return "hello"; }
@CookieValue: Used to obtain client cookie information.
@RequestMapping("/testCookieValue") public String hello6(@CookieValue("JSESSIONID")String sessionid){ System.out.println("sessionid=" + sessionid); return "hello"; }
SpringMVC can use ServletAPI as a parameter of the request method
@RequestMapping("/testServletAPI") public String hello7(HttpServletRequest request,HttpServletResponse response,HttpSession session){ //我们可以在这里使用 return "hello"; }
SpringMVC provides the following ways to process model data.
1) ModelAndView: Set the return type of the processing method to the ModelAndView method body to add model data through the model object. Contains both views and model information
@RequestMapping("/testModelAndView") public ModelAndView hello8(){ ModelAndView modelAndView = new ModelAndView("hello"); //添加单个值 modelAndView.addObject("h","Hello Spring MVC"); return modelAndView; }
2) Map and formal parameters: When the formal parameters are Map, Model, and ModelMap, when the processing method returns, The data in the Map is automatically added to the model.
Spring MVC internally uses a Model interface to store data, and will create an implicit The model object serves as the storage container for the data model. If the incoming parameters are Map, Model, ModelMap, SpringMVC will automatically save it to the container
@RequestMapping("/testMap") public String hello9(Map<String,Object> map){ map.put("mapdata", "map data"); return "hello"; }
3)@SessionAttributes:将这个模型中的某个属性存储到Session中,以便多个请求之间共享这个属性,只能用来修饰类。在里面的方法如果参数容器中如map里卖弄保存一个与定义的属性名字相同会保存到容器中共享
4)@ModelAttribute:方法形参标记该注解后,形参对象就会放到模型中。
SpringMVC在调用方法之前会逐个调用方法上标注了这个注解的方法。将@ModelAttribute中的属性保存到map中,可在执行表单提交生成对象之前,替换执行方法名相同的参数。
@ModelAttribute public User getUser(){ User user = new User(); System.out.println("调用 getUser 方法"); //默认保存名字为类名首字母小写的user对象到Request中 return user; } @ModelAttribute public void getUserById(Integer id,Map<String,Object> map){ User myuser = new User(); map.put("myuser", myuser); //手动指定user对象的名称,到Request中 System.out.println("调用 getUser 方法"); }
由@SessionAttributs会引发一个很容易轻视的错误当类使用@SessionAttributes修饰,而方法中使用了和SessionAttributes修饰同名的映射参数,确没有添加@ModelAttribute修饰时,则会报错。
The above is the detailed content of Detailed introduction to SpringMVC basic configuration. For more information, please follow other related articles on the PHP Chinese website!