SpringMVC----A brief introduction based on annotations

SpringMVC is an MVC framework based on DispatcherServlet. DispatcherServlet is the first access to each request. DispatcherServlet is responsible for forwarding each Request request to the corresponding Handler. After processing, the Handler returns the corresponding View and Model. Return Both the view and the model can be left unspecified, that is, only the Model or only the View can be returned, or none of them can be returned.

DispatcherServlet is inherited from HttpServlet. Since SpringMVC is based on DispatcherServlet, let's configure DispatcherServlet so that it can manage the content we want it to manage. HttpServlet is declared in the web.xml file.

  1. <servlet>  
  2.     <servlet-name>blog</servlet-name>  
  3.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  4.     <load-on-startup>1</load-on-startup>  
  5. </servlet>  
  6. <servlet-mapping>  
  7.     <servlet-name>blog</servlet-name>  
  8.     <url-pattern>*.do</url-pattern>  
  9. </servlet-mapping>  

The above declares a DispatcherServlet called blog which will handle all requests ending with ".do". When initializing the DispatcherServlet, SpringMVC will go to the /WEB-INF directory to find a configuration file called [servlet-name]-servlet.xml by default to initialize the bean object in it. The corresponding bean object in this file will override the spring configuration. A bean object of the same name declared in the file. As above, a file called blog-servlet.xml will be found in the /WEB-INF directory; of course, the location of the configuration file can also be declared in the Servlet.

  1. <servlet>  
  2.     <servlet-name>blog</servlet-name>  
  3.     <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>  
  4.     <init-param>  
  5.         <param-name>contextConfigLocation</param-name>  
  6.         <param-value>/WEB-INF/blog-servlet.xml</param-value>  
  7.     </init-param>  
  8.     <load-on-startup>1</load-on-startup>  
  9. </servlet>  
  10. <servlet-mapping>  
  11.     <servlet-name>blog</servlet-name>  
  12.     <url-pattern>*.do</url-pattern>  
  13. </servlet-mapping>  

DispatcherServlet will use some special beans to process Request requests and generate corresponding view returns.

 

Regarding the return of the view, the Controller is only responsible for returning a value, and then what view is returned is controlled by the view resolver. The view resolver commonly used in jsp is InternalResourceViewResovler, which requires a prefix and a suffix

  1. <bean  
  2.     class="org.springframework.web.servlet.view.InternalResourceViewResolver">  
  3.     <property name="prefix" value="/WEB-INF/" />  
  4.     <property name="suffix" value=".jsp" />  
  5. </bean>  

在上述视图解析器中,如果Controller返回的是blog/index,那么通过视图解析器解析之后的视图就是/WEB-INF/blog/index.jsp。

要使用注解的SpringMVC需要在SpringMVC的配置文件中进行声明,具体方式为先引入mvc命名空间,然后利用<mvc:annotation-driven />进行声明。

  1. <beans xmlns="http://www.springframework.org/schema/beans"  
  2.     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:context="http://www.springframework.org/schema/context"  
  3.     <SPAN style="BACKGROUND-COLOR: #00ff00"><SPAN style="COLOR: #ff0000">xmlns:mvc="http://www.springframework.org/schema/mvc"</SPAN></SPAN>  
  4.     xsi:schemaLocation="http://www.springframework.org/schema/beans   
  5.      http://www.springframework.org/schema/beans/spring-beans-3.0.xsd   
  6.      http://www.springframework.org/schema/context   
  7.      http://www.springframework.org/schema/context/spring-context-3.0.xsd   
  8.     <SPAN style="COLOR: #ff0000; BACKGROUND-COLOR: #00ff00"> http://www.springframework.org/schema/mvc   
  9.      http://www.springframework.org/schema/mvc/spring-mvc-3.0.xsd"</SPAN>>  
  10.   
  11. <mvc:annotation-driven />  
  12.   
  13. </beans>  

主要是说说Controller.

一个类使用了@Controller进行标记的都是Controller

  1. @Controller  
  2. public class BlogController {   
  3.   
  4. }  

有了Controller之后,那么到底是怎样请求一个Controller具体的方法的呢,那是通过@RequestMapping来标记的,@RequestMapping可以标记在类上面,也可以标记在方法上,当方法上和类上都标记了@RequestMapping的时候,那么对应的方法对应的Url就是类上的加方法上的,如下面的index方法,其对应的URL应为类上的/blog加上index方法上的/index,所以应为/blog/index,所以当请求/blog/index.do的时候就会访问BlogController的index方法。

  1. @Controller  
  2. @RequestMapping("/blog")   
  3. public class BlogController {   
  4.   
  5.        
  6.     @RequestMapping("/index")   
  7.     public String index(Map<String, Object> map) {   
  8.         return "blog/index";   
  9.     }   
  10. }  

在上面的代码中,如果index方法上没有RequestMapping注解,而只有BlogController类上有,且该类只有一个方法的时候,直接请求类上的URL就会调用里面的方法,即直接请求/blog.do的时候就会调用index方法。

在RequestMapping中还可以指定一个属性method,其主要对应的值有RequestMethod.GET和RequestMethod.POST,利用该属性可以严格的控制某一方法只能被标记的请求路径对应的请求方法才能访问,如指定method的值为GET,则表示只有通过GET方式才能访问该方法,默认是都可以访问。

在SpringMVC中常用的注解还有@PathVariable,@RequestParam,@PathVariable标记在方法的参数上,利用它标记的参数可以利用请求路径传值,看下面一个例子

  1. @RequestMapping(value="/comment/{blogId}", method=RequestMethod.POST)   
  2. public void comment(Comment comment,@PathVariable int blogId, HttpSession session, HttpServletResponse response) throws IOException {   
  3.        
  4. }  

在该例子中,blogId是被@PathVariable标记为请求路径变量的,如果请求的是/blog/comment/1.do的时候就表示blogId的值为1. 同样@RequestParam也是用来给参数传值的,但是它是从头request的参数里面取值,相当于request.getParameter("参数名")方法。

在Controller的方法中,如果需要WEB元素HttpServletRequest,HttpServletResponse和HttpSession,只需要在给方法一个对应的参数,那么在访问的时候SpringMVC就会自动给其传值,但是需要注意的是在传入Session的时候如果是第一次访问系统的时候就调用session会报错,因为这个时候session还没有生成。

接下来讨论一下方法的返回值,主要有一下情况:

返回一个ModelAndView,其中Model是一个Map,里面存放的是一对对的键值对,其可以直接在页面上使用,View是一个字符串,表示的是某一个View的名称

返回一个View,也就是一个字符串,这个时候如果需要给页面传值,可以给方法一个Map参数,该Map就相当于一个Model,往该Model里面存入键值对就可以在页面上进行访问了

返回一个Model也就是一个Map,这个时候将解析默认的生成的view name。

什么也不返回,这个时候可以利用HttpServletResponse进行返回,也可以直接使用printStream进行返回

下面是一个简单的实例

  1. @RequestMapping("/{owner}/index")   
  2. public String userIndex(Map<String, Object> map,@PathVariable String owner, HttpServletRequest request) throws ParserException {   
  3.     List<DefCategory> categories = categoryService.find(owner);   
  4.     int offset = Util.getOffset(request);   
  5.     Pager<Blog> pager = blogService.find(owner, 0, offset, maxResults);   
  6.     int totalRecords = pager.getTotalRecords();   
  7.     List<Blog> blogs = pager.getData();   
  8.     Util.shortBlog(blogs);   
  9.        
  10.     List<Message> messages = messageService.find(owner, 05).getData();   
  11.     Util.shortMessage(messages, 20);   
  12.     map.put("messages", messages);   
  13.     map.put("totalRecords", totalRecords);   
  14.     List<BlogStore> stores = storeService.find(owner, 05).getData();   
  15.     map.put("maxResults", maxResults);   
  16.     map.put("blogs", blogs);   
  17.     map.put("totalRecords", totalRecords);   
  18.     map.put("owner", userService.find(owner));   
  19.     map.put("defCategories", categories);   
  20.     map.put("stores", stores);   
  21.     return "blog/userIndex";   
  22. }  

 

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326943146&siteId=291194637