Spring MVC(model-view-controller)框架?chē)@著DispatcherServlet進(jìn)行設(shè)計(jì),DispatcherServlet就是Spring MVC的前端控制器。瀏覽器端用戶的請(qǐng)求就是通過(guò)DispatcherServlet進(jìn)行了分發(fā)到達(dá)一個(gè)合適Controller來(lái)生產(chǎn)所需要的業(yè)務(wù)數(shù)據(jù)model,model再通過(guò)DispatcherServlet進(jìn)行傳遞,傳遞給view來(lái)完成最終的業(yè)務(wù)呈現(xiàn)。如下圖:
核心步驟:
1、 DispatcherServlet在web.xml中的部署描述,從而攔截請(qǐng)求到Spring Web MVC。
2、 HandlerMapping的配置,從而將請(qǐng)求映射到處理器。
3、 HandlerAdapter的配置,把處理器包裝為適配器,從而支持多種類(lèi)型的處理器,即適配器設(shè)計(jì)模式的應(yīng)用。
4、 ViewResolver的配置,將把邏輯視圖名解析為具體的View。
5、處理器(頁(yè)面控制器)的配置,用于對(duì)請(qǐng)求進(jìn)行處理。
XML 例子:
-
web.xml中添加如下配置,實(shí)現(xiàn)前端控制器:
<servlet> <servlet-name>chapter2</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <load-on-startup>1</load-on-startup> <!-- <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-servlet-config.xml</param-value> </init-param> --> </servlet> <servlet-mapping> <servlet-name>chapter2</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
load-on-startup:表示啟動(dòng)容器時(shí)初始化該Servlet。
url-pattern:表示哪些請(qǐng)求交給Spring Web MVC處理, “/” 是用來(lái)定義默認(rèn)servlet映射的。也可以如“*.do”表示攔截所有以do為擴(kuò)展名的請(qǐng)求。
- 在Spring配置文件中配置HandlerMapping、HandlerAdapter
具體配置在WEB-INF/chapter2-servlet.xml文件中(chapter2為web.xml中的servlet-name):
<!-- HandlerMapping -->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!-- HandlerAdapter -->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
BeanNameUrlHandlerMapping:表示將請(qǐng)求的URL和Bean名字映射,如URL為 “上下文/hello”,則Spring配置文件必須有一個(gè)名字為“/hello”的Bean。
SimpleControllerHandlerAdapter:表示所有實(shí)現(xiàn)了org.springframework.web.servlet.mvc.Controller接口的Bean可以作為Spring Web MVC中的處理器。
- 配置ViewResolver
具體配置在WEB-INF/ chapter2-servlet.xml文件中(chapter2為web.xml中的servlet-name):
<!-- ViewResolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
InternalResourceViewResolver:用于支持Servlet、JSP視圖解析。
viewClass:JstlView表示JSP模板頁(yè)面需要使用JSTL標(biāo)簽庫(kù),classpath中必須包含jstl的相關(guān)jar包;
prefix和suffix:查找視圖頁(yè)面的前綴和后綴(前綴[邏輯視圖名]后綴),比如傳進(jìn)來(lái)的邏輯視圖名為hello,則該該jsp視圖頁(yè)面應(yīng)該存放在“WEB-INF/jsp/hello.jsp”;
-
最后配置文件如下:
<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" xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd "> <!-- HandlerMapping --> <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/> <!-- HandlerAdapter --> <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/> <!-- ViewResolver --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> <!-- 處理器 --> <bean name="/hello" class="cn.javass.chapter2.web.controller.HelloWorldController“> </beans>
-
Controller:
package cn.javass.chapter2.web.controller; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import org.springframework.web.servlet.ModelAndView; import org.springframework.web.servlet.mvc.Controller; public class HelloWorldController implements Controller { @Override public ModelAndView handleRequest(HttpServletRequest req, HttpServletResponse resp) throws Exception { //1、收集參數(shù)、驗(yàn)證參數(shù) //2、綁定參數(shù)到命令對(duì)象 //3、將命令對(duì)象傳入業(yè)務(wù)對(duì)象進(jìn)行業(yè)務(wù)處理 //4、選擇下一個(gè)頁(yè)面 ModelAndView mv = new ModelAndView(); //添加模型數(shù)據(jù) 可以是任意的POJO對(duì)象 mv.addObject("message", "Hello World!"); //設(shè)置邏輯視圖名,視圖解析器會(huì)根據(jù)該名字解析到具體的視圖頁(yè)面 mv.setViewName("hello"); return mv; } }
配置文件中的視圖解析器InternalResourceViewResolver會(huì)將其解析為WEB-INF/jsp/hello.jsp
-
/WEB-INF/jsp/hello.jsp視圖頁(yè)面:
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"> <title>Hello World</title> </head> <body> ${message} </body> </html>
運(yùn)行步驟:
1.首先用戶發(fā)送請(qǐng)求 http://localhost:9080/springmvc-chapter2/hello ——>web容器,web容器根據(jù)“/hello”路徑映射到DispatcherServlet(url-pattern為/)進(jìn)行處理。
2.DispatcherServlet——>BeanNameUrlHandlerMapping進(jìn)行請(qǐng)求到處理的映射,BeanNameUrlHandlerMapping將“/hello”路徑直接映射到名字為“/hello”的Bean進(jìn)行處理,即HelloWorldController,BeanNameUrlHandlerMapping將其包裝為HandlerExecutionChain(只包括HelloWorldController處理器,沒(méi)有攔截器)。
3.DispatcherServlet——> SimpleControllerHandlerAdapter,SimpleControllerHandlerAdapter將HandlerExecutionChain中的處理器(HelloWorldController)適配為SimpleControllerHandlerAdapter。
4.SimpleControllerHandlerAdapter——> HelloWorldController處理器功能處理方法的調(diào)用,SimpleControllerHandlerAdapter將會(huì)調(diào)用處理器的handleRequest方法進(jìn)行功能處理,該處理方法返回一個(gè)ModelAndView給DispatcherServlet。
5.hello(ModelAndView的邏輯視圖名)——>InternalResourceViewResolver, InternalResourceViewResolver使用JstlView,具體視圖頁(yè)面在/WEB-INF/jsp/hello.jsp。
6.JstlView(/WEB-INF/jsp/hello.jsp)——>渲染,將在處理器傳入的模型數(shù)據(jù)(message=HelloWorld!)在視圖中展示出來(lái)。
7.返回控制權(quán)給DispatcherServlet,由DispatcherServlet返回響應(yīng)給用戶,到此一個(gè)流程結(jié)束。
與Sprin集成:
配置是Spring集成Web環(huán)境的通用配置;一般用于加載除Web層的Bean(如DAO、Service等),以便于與其他任何Web框架集成。
contextConfigLocation:表示用于加載Bean的配置文件;
contextClass:表示用于加載Bean的ApplicationContext實(shí)現(xiàn)類(lèi),默認(rèn)WebApplicationContext。
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>
classpath:applicationContext
</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
ContextLoaderListener初始化的上下文加載的Bean是對(duì)于整個(gè)應(yīng)用程序共享的,不管是使用什么表現(xiàn)層技術(shù),一般如DAO層、Service層Bean。
DispatcherServlet初始化的上下文加載的Bean是只對(duì)Spring Web MVC有效的Bean,如Controller、HandlerMapping、HandlerAdapter等等,該初始化上下文應(yīng)該只加載Web相關(guān)組件。
注解 例子:
通過(guò)@Controller 和 @RequestMapping注解定義我們的處理器類(lèi)。通過(guò)在一個(gè)POJO類(lèi)上放置@Controller或@RequestMapping,即可把一個(gè)POJO類(lèi)變身為處理器。
@RequestMapping(value = "/hello") 請(qǐng)求URL(/hello) 無(wú)需實(shí)現(xiàn)/繼承任何接口/類(lèi)。
-
推薦使用這種方式聲明處理器,它和我們的@Service、@Repository很好的對(duì)應(yīng)了我們常見(jiàn)的三層開(kāi)發(fā)架構(gòu)的組件。
@Controller public class HelloWorldController { …… }
-
這種方式也是可以工作的,但如果在類(lèi)上使用@ RequestMapping注解一般是用于窄化功能處理方法的映射的。
@RequestMapping public class HelloWorldController { …… }
-
窄化請(qǐng)求映射。
@Controller @RequestMapping(value="/user") //①處理器的通用映射前綴 public class HelloWorldController { @RequestMapping(value = "/hello2") //②相對(duì)于①處的映射進(jìn)行窄化 public ModelAndView helloWorld() { …… } …… }
URL路徑映射:
@RequestMapping(value={"/test1", "/user/create"}):多個(gè)URL路徑可以映射到同一個(gè)處理器的功能處理方法。
@RequestMapping(value="/users/{userId}"):{×××}占位符, 請(qǐng)求的URL可以是 “/users/123456”或“/users/abcd”,通過(guò)@PathVariable可以提取URI模板模式中的{×××}中的×××變量。
@RequestMapping(value="/users/{userId}/create"):這樣也是可以的,請(qǐng)求的URL可以是“/users/123/create”。
@RequestMapping(value="/users/{userId}/topics/{topicId}"):這樣也是可以的,請(qǐng)求的URL可以是“/users/123/topics/123”。
@RequestMapping(value="/users/"):可以匹配“/users/abc/abc”,但根據(jù)最長(zhǎng)匹配優(yōu)先“/users/123”將優(yōu)先映射“/users/{userId}”。
@RequestMapping(value="/product?"):可匹配“/product1”或“/producta”,但不匹配“/product”或“/productaa”;
@RequestMapping(value="/product"):可匹配“/productabc”或“/product”,但不匹配“/productabc/abc”;
@RequestMapping(value="/product/"):可匹配“/product/abc”,但不匹配“/productabc”;
@RequestMapping(value="/products/**/{productId}"):可匹配“/products/abc/abc/123”或“/products/123”請(qǐng)求參數(shù)數(shù)據(jù)映射:
@RequestMapping(params="create") :表示請(qǐng)求中有“create”參數(shù)名,如可匹配的請(qǐng)求URL“http://×××/parameterTest?create”。
@RequestMapping(params="!create"):表示請(qǐng)求中沒(méi)有“create”參數(shù)名,如可匹配的請(qǐng)求URL“http://×××/parameterTest?abc”。
@RequestMapping(params="submitFlag=create"):表示請(qǐng)求中有“submitFlag=create”請(qǐng)求參數(shù),如請(qǐng)求URL為http://×××/parameterTest?submitFlag=create。
@RequestMapping(params="submitFlag!=create"):表示請(qǐng)求中的參數(shù)“submitFlag!=create”,如可匹配的請(qǐng)求URL“http://×××/parameter1?submitFlag=abc”。-
數(shù)據(jù)綁定:
@RequestParam用于將請(qǐng)求參數(shù)區(qū)數(shù)據(jù)映射到功能處理方法的參數(shù)上,請(qǐng)求中包含username參數(shù)(如/requestparam1?username=zhang),則自動(dòng)傳入。public String requestparam1(@RequestParam String username) { …… } //即通過(guò)@RequestParam("username")明確告訴Spring Web MVC使用username進(jìn)行入?yún)ⅰ? public String requestparam2(@RequestParam("username") String username){ …… } //required:是否必須,默認(rèn)是true,表示請(qǐng)求中一定要有相應(yīng)的參數(shù),否則將報(bào)404錯(cuò)誤碼。 public String requestparam4(@RequestParam(value="username",required=false) String username){ …… } //defaultValue:默認(rèn)值,表示如果請(qǐng)求中沒(méi)有同名參數(shù)時(shí)的默認(rèn)值。 public String requestparam4(@RequestParam(value="username",required=false, defaultValue="zhang") String username){ …… } public String requestparam5(@RequestParam(value="list") List<String> list){ …… }
@PathVariable用于將請(qǐng)求URL中的模板變量映射到功能處理方法的參數(shù)上。
@RequestMapping(value="/users/{userId}/topics/{topicId}")
public String test(@PathVariable(value="userId") int userId, @PathVariable(value="topicId") int topicId){
……
}
@CookieValue用于將請(qǐng)求的Cookie數(shù)據(jù)映射到功能處理方法的參數(shù)上。@CookieValue也擁有和@RequestParam相同的value,required,defaultValue三個(gè)參數(shù),含義一樣。
//將自動(dòng)將JSESSIONID值入?yún)⒌絪essionId參數(shù)上,defaultValue表示Cookie中沒(méi)有JSESSIONID時(shí)默認(rèn)為空。
public String test(@CookieValue(value="JSESSIONID", defaultValue="") String sessionId){
……
}
//傳入?yún)?shù)類(lèi)型也可以是javax.servlet.http.Cookie類(lèi)型。
public String test2(@CookieValue(value="JSESSIONID", defaultValue="") Cookie sessionId){
……
}
@RequestHeader用于將請(qǐng)求的頭信息區(qū)數(shù)據(jù)映射到功能處理方法的參數(shù)上。@RequestHeader也擁有和@RequestParam相同的三個(gè)參數(shù),含義一樣。
//如上配置將自動(dòng)將請(qǐng)求頭“User-Agent”值入?yún)⒌絬serAgent參數(shù)上,并將“Accept”請(qǐng)求頭值入?yún)⒌絘ccepts參數(shù)上。
public String test(@RequestHeader("User-Agent") String userAgent, @RequestHeader(value="Accept") String[] accepts){
……
}
@ModelAttribute放在方法的注解上時(shí),會(huì)在每一個(gè)@RequestMapping標(biāo)注的方法前先執(zhí)行此@ModelAttribute方法,如果有返回值,則自動(dòng)將該返回值加入到ModelMap中。
暴露表單引用對(duì)象為模型(model)數(shù)據(jù)
返回void:
//訪問(wèn)控制器方法helloWorld時(shí),會(huì)首先調(diào)用populateModel方法,將頁(yè)面參數(shù)abc(/helloWorld.ht?abc=text)放到model的attributeName屬性中,在視圖中可以直接訪問(wèn)。
//在視圖中可以直接訪問(wèn)<c:out value="${attributeName}"></c:out>
@Controller
public class HelloModelController {
@ModelAttribute
public void populateModel(@RequestParam String abc, Model model) {
model.addAttribute("attributeName", abc);
}
@RequestMapping(value = "/helloWorld")
public String helloWorld() {
return "helloWorld.jsp";
}
}
返回具體類(lèi):
//設(shè)置這個(gè)注解之后可以直接在前端頁(yè)面使用hobbise這個(gè)對(duì)象(List)集合。
//例如:<c:forEach items="${hb}" var="hobby" varStatus="vs">
@ModelAttribute("hb")
public List<String> hobbiesList(){
List<String> hobbise = new LinkedList<String>();
hobbise.add("basketball");
hobbise.add("football");
hobbise.add("tennis");
return hobbise; //那么這個(gè)model屬性的名稱(chēng)是hb。相當(dāng)于model.addAttribute("hb", hobbise);
}
@RequestMapping(value = "/helloWorld")
public String helloWorld(@ModelAttribute("hb") List<String> hobbise) {
System.out.println("hobbise : "+hobbise.toString());
return "helloWorld";
}
在這個(gè)例子里,@ModelAttribute("hb") List<String> hobbise注釋方法參數(shù),參數(shù)hobbise的值來(lái)源于hobbiesList()方法中的model的屬性hb。進(jìn)行模型綁定時(shí)首先查找模型數(shù)據(jù)中是否含有同名對(duì)象,如果有直接使用,如果沒(méi)有通過(guò)反射創(chuàng)建一個(gè)。參考
綁定請(qǐng)求參數(shù)到命令對(duì)象
//如請(qǐng)求參數(shù)包含“?username=zhang&password=123&workInfo.city=bj”自動(dòng)綁定到User類(lèi)中的username屬性,password屬性,workInfo屬性的city屬性中。
//我們?cè)谝晥D頁(yè)面也可以直接使用user,如:${user},${user.username}
public String test1(@ModelAttribute("user") UserModel user) {
……
}
@SessionAttributes注解就可以使得模型中的數(shù)據(jù)存儲(chǔ)一份到session域中。默認(rèn)情況下Spring MVC將模型中的數(shù)據(jù)存儲(chǔ)到request域中。當(dāng)一個(gè)請(qǐng)求結(jié)束后,數(shù)據(jù)就失效了。如果要跨頁(yè)面使用。那么需要使用到session。
@SessionAttributes參數(shù):
1.names:這是一個(gè)字符串?dāng)?shù)組。里面應(yīng)寫(xiě)需要存儲(chǔ)到session中數(shù)據(jù)的名稱(chēng)。
2.types:根據(jù)指定參數(shù)的類(lèi)型,將模型中對(duì)應(yīng)類(lèi)型的參數(shù)存儲(chǔ)到session中。
3.value:其實(shí)和names是一樣的。
@RequestMapping("/test")
public String test(Map<String,Object> map){
map.put("names", Arrays.asList("caoyc","zhh","cjx"));
map.put("age", 18);
return "hello";
}
request中names:${requestScope.names}<br/>
request中age:${requestScope.age}<br/>
<hr/>
session中names:${sessionScope.names }<br/>
session中age:${sessionScope.age }<br>
@SessionAttributes(value={"names"},types={Integer.class})
@Controller
public class TestController {
@RequestMapping("/test")
public String testController(Map<String,Object> map){
map.put("names", Arrays.asList("caoyc","zhh","cjx"));
map.put("age", 18);
return "hello";
}
}
如果在另一個(gè)Controller重要調(diào)用其他Controller中放入session中的值,也許要在Controller上加上相同的SessionAttributes注解,例如:
@Controller
@SessionAttributes("names")
public class AnotherController {
public String lendBooks(@ModelAttribute("names")List names){
System.out.println("names:"+names.toString);
}
}