SpringMVC總結

xiaoyang531發表於2020-09-23

1.SpringMVC簡介

springmvc是web層mvc框架,用於替代servlet。

2.工作流程

springmvc工作流程
1.使用者傳送請求至前端控制器dispatcherServlet;
2.dispatcherServlet收到請求呼叫HandlerMapping處理器對映器;
3.HandlerMapping找到具體的處理器(可以根據xml配置、註解進行查詢),生成處理器物件及處理器攔截器(如果有則生成)一併返回給DispatcherServlet;
4.dispatcherServlet呼叫HandlerAdapter處理器介面卡;
5.HandlerAdapter經過適配呼叫具體的處理器(Controller);
6.Controller執行完成返回ModelAndView;
7.HandlerAdapter將controller執行結果ModelAndView返回給DispatcherServlet;
8.DispatcherServlet將ModelAndView傳給ViewReslover檢視解析器;
9.ViewReslover解析後返回具體View;
10.DispatcherServlet根據View進行渲染檢視(即將模型資料填充至檢視中)。
11.DispatcherServlet響應使用者

注:HandlerMapping、Handler和HandlerAdapter的關係與區別:
hander\handerMapping與handerAdapter關係圖

Handler對應controller.@RequestMapping註解標註的方法,它就對應著一個Handler;
HandlerMapping,是用來查詢Handler的,在spingmvc中會處理很多請求,每一個請求都需要一個Handler進行處理,具體接受到一個請求後使用哪個Handler來處理,就是HandlerMapping需要做的事情;
HandlerAdapter,即Handler的介面卡,也是這3個概念中理解起來比較模糊的一個概念。上面說Handler的時候,我們說Handler是有多種的表現形式,只要能處理請求就可以,而dispatchServlet處理請求的方式卻是固定的——doService(request,response),那麼怎麼讓固定的doService呼叫靈活的Handler來進行處理呢,這就是HandlerAdapter需要做的事情。
總結:handler與handlerAdapter的關係,和view與ViewReslover關係是一樣的。

3.搭建例項

3.1 web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee
	http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

  <display-name>Archetype Created Web Application</display-name>
  
  <!--Spring應用上下文,理解層次化的ApplicationContext-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath*:/applicationContext.xml</param-value>
  </context-param>

  <!-- DispatcherServlet, Spring MVC的核心 -->
  <servlet>
    <servlet-name>mvc-dispatcher</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!-- DispatcherServlet對應的上下文配置, 預設為/WEB-INF/$servlet-name$-servlet.xml
     -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:mvc-dispatcher-servlet.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>mvc-dispatcher</servlet-name>
    <!-- mvc-dispatcher攔截所有的請求-->
    <url-pattern>/</url-pattern>
  </servlet-mapping>
</web-app>

3.2 mvc-dispatcher-servlet.xml

	<!--啟用對標籤配置生命週期的管理@Required @Autowired@Resource等-->
	<context:annotation-config />

	<!--DispatcherServlet上下文,只搜尋@Controller標註的類-->
	<context:component-scan base-package="com.mrzhang.mvcdemo" >
		<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller" />
	</context:component-scan>

	<!--HAandlerMapping 無需配置 spring MVC可以預設啟動-->

	<!--擴充註解驅動,可以將請求引數繫結到控制器引數-->
	<mvc:annotation-driven />

	<!--靜態資源處理,css,js,imgs-->
	<mvc:resources mapping="/resources/**" location="/resources/" />


	<!--配置viewResolver 可以用多個ViewResolver
	使用order屬性排序 InternalResourceViewResolver放在最後-->
	<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix" value="/WEB-INF/jsps/"/>
		<property name="suffix" value=".jsp"/>
	</bean>

	<!--200*1024*1024即200M resolveLazily屬性啟用是為了推遲檔案解析,以便捕獲檔案大小異常-->
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
		<property name="maxUploadSize" value="209715200"/>
		<property name="defaultEncoding" value="UTF-8" />
		<property name="resolveLazily" value="true"/>
	</bean>

3.3 applicationContext.xml

    <context:annotation-config />
    
    <context:component-scan base-package="com.mrzhang.mvcdemo">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

3.4 controller.java


@Controller
@RequestMapping("/courses")
public class CourseController {
    private  static Logger log= LoggerFactory.getLogger(CourseController.class);

    private CourseService courseService;

    @Autowired
    public void setCourseService(CourseService courseService) {
        this.courseService = courseService;
    }

    @RequestMapping(value = "/view",method = RequestMethod.GET)
    public  String viewCourse(@RequestParam("courseId") Integer courseId, Model model){
        Course course=courseService.getCoursebyId(courseId);
        model.addAttribute(course);
        return "course_overview";
    }

    @RequestMapping(value = "/view2/{courseId}",method = RequestMethod.GET)
    public  String viewCourse2(@PathVariable("courseId") Integer courseId, Map<String,Object> model){
        Course course=courseService.getCoursebyId(courseId);
        model.put("course",course);
        return "course_overview";
    }

    @RequestMapping(value = "/view3",method = RequestMethod.GET)
    public  String viewCourse3(HttpServletRequest request){
        Integer courseId =Integer.valueOf(request.getParameter("courseId"));
        Course course=courseService.getCoursebyId(courseId);
        request.setAttribute("course",course);
        return "course_overview"; 
    }

    @RequestMapping(value = "/admin",method = RequestMethod.GET,params = "add")
    public String creatCourse(){
        return "/course_admin/edit";
    }

    @RequestMapping(value = "/save",method = RequestMethod.POST)
    public String save(Course course){
        course.setCourseId(123);
        return "redirect:view2/"+course.getCourseId();
    }

    @RequestMapping(value="/upload", method=RequestMethod.GET)
    public String showUploadPage(@RequestParam(value= "multi", required = false) 		  Boolean multi){
    		if(multi != null && multi){
    			return "course_admin/multifile";
    		}
    		return "course_admin/file";
    	}


    @RequestMapping(value="/{courseId}",method=RequestMethod.GET)
     public @ResponseBody Course getCourseInJson(@PathVariable Integer courseId){
       	return  courseService.getCoursebyId(courseId);
       }


}

3.5 SpringMVC常用註解及其作用

@Controller:標識這個類是一個控制器

@RequestMapping:給控制器方法繫結一個uri

@ResponseBody:將java物件轉成json,並且傳送給客戶端

@RequestBody:將客戶端請求過來的json轉成java物件

@RequestParam:當表單引數和方法形參名字不一致時,做一個名字對映

@PathVarible:用於獲取uri中的引數,比如user/1中1的值

相關文章