SpringMVC是什么
SpringMVC是目前最好的實現MVC設計模式的框架,是Spring框架的一個分支產品,以SpringIOC容器為基礎,並利用容器的特性來簡化它的配置。SpringMVC相當於Spring的一個子模塊,可以很好的和Spring結合起來進行開發,是JavaWeb開發者必須要掌握的框架。實現了MVC設計模式,MVC設計模式是一種常用的軟件架構方式:以Controller(控制層),Model(模型層),View(視圖層)三個模塊分離的形式來組織代碼。
SpringMVC的執行順序
1、 用戶發送請求至前端控制器DispatcherServlet
2、 DispatcherServlet收到請求調用HandlerMapping處理器映射器。
3、 處理器映射器根據請求url找到具體的處理器,生成處理器對象及處理器攔截器(如果有則生成)一並返回給DispatcherServlet。
4、 DispatcherServlet通過HandlerAdapter處理器適配器調用處理器
5、 執行處理器(Controller,也叫后端控制器)。
6、 Controller執行完成返回ModelAndView
7、 HandlerAdapter將controller執行結果ModelAndView返回給DispatcherServlet
8、 DispatcherServlet將ModelAndView傳給ViewReslover視圖解析器
9、 ViewReslover解析后返回具體View
10、 DispatcherServlet對View進行渲染視圖(即將模型數據填充至視圖中)。
11、 DispatcherServlet響應用戶
代碼編寫
1、配置web.xml文件
<?xml version="1.0" encoding="UTF-8"?> <web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"> <display-name></display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <servlet> <servlet-name>springmvc</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <!-- 指定springmvc.xml的路徑 --> <param-value>classpath:springmvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
3、配置springmvc.xml文件
<?xmlversion="1.0"encoding="UTF-8"?> <beansxmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" xmlns:dubbo="http://code.alibabatech.com/schema/dubbo"xmlns:mvc="http://www.springframework.org/schema/mvc" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 配置自動掃描 --> <context:component-scanbase-package="cn.test.springmvc.controller"/> <!-- 配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <!-- 前綴 --> <property name="prefix" value="/"></property> <!-- 后綴 --> <property name="suffix" value=".jsp"></property> </bean> </beans>
3、編寫測試類
@Controller publicclass ItemController { @RequestMapping("/itemList") public ModelAndView itemList() throws Exception { List<Items>itemList = new ArrayList<>(); //商品列表 Items items_1 = new Items(); items_1.setName("聯想筆記本_3"); items_1.setPrice(6000f); items_1.setDetail("ThinkPad T430 聯想筆記本電腦!"); Items items_2 = new Items(); items_2.setName("蘋果手機"); items_2.setPrice(5000f); items_2.setDetail("iphone6蘋果手機!"); itemList.add(items_1); itemList.add(items_2); //創建modelandView對象 ModelAndView modelAndView = new ModelAndView(); //添加model modelAndView.addObject("itemList", itemList); //添加視圖 modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp"); // modelAndView.setViewName("itemsList"); returnmodelAndView; } }
SpringMVC的注解
一、@RequestMapping
SpringMVC通過@RequestMapping注解將URL請求與業務方法進行進行映射。
參數:
1.value:指定URL請求的實際地址,是@RequestMapping的默認值。
2.method:指定請求的method類型, GET、POST、PUT、DELETE等。
3.params:指定request中必須包含某些參數值,否則無法調用該方法。
@RequestMapping(value="paramsTest",params={"name","id=10"}) public String paramsTest(){ System.out.println("paramsTest"); return "index"; }
二、參數綁定:
params是對URL請求的參數進行限制,不滿足條件的URL無法到達業務方法,這個特性並不是我們開發中常用的,我們需要用到的是在業務方法中獲取URL的參數,實現這一步很簡單。
1.在業務方法定義時聲明參數列表。
2.給參數列表添加@RequestParam注解。
@RequestMapping(value="paramsBind") public String paramsBind(@RequestParam("name") String name,@RequestParam("id") int id){ System.out.println(name); int num = id+10; System.out.println(num); return "index"; }
三、映射Cookie:
SpringMVC通過映射可以直接在業務方法中獲取Cookie的值。
@RequestMapping("/cookieTest") public String getCookie(@CookieValue(value="JSESSIONID") String sessionId){ System.out.println(sessionId); return "index"; }
使用pojo綁定參數
SpringMVC會根據請求參數名和pojo屬性名進行自動匹配,自動為該對象填充屬性值。並且支持級聯屬性。
1.創建實體類Address,User並進行級聯設置。
public class Address { private int id; private String name; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
public class User { private int id; private String name; private Address address; public Address getAddress() { return address; } public void setAddress(Address address) { this.address = address; } public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } }
2.創建addUser.jsp。
<%@ 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>Insert title here</title> </head> <body> <form action="addUser" method="post"> 編號:<input type="text" name="id"/><br/> 姓名:<input type="text" name="name"/><br/> 地址:<input type="text" name="address.name"/><br/> <input type="submit" value="提交"/> </form> </body> </html>
3.業務方法。
@RequestMapping("/addUser") public String getPOJO(User user){ System.out.println(user); return "index"; }
重定向和轉發
//重定向 @RequestMapping("redirectTest") public String redirectTest(){ return "redirect:/index.jsp"; } //轉發 @RequestMapping("forwardTest") public String forwardTest(){ return "forward:/index.jsp"; }