SringMVC
- 1. 搭建環境
-
- 1.1 建立一個Moudle,springmvc-03-hello-annotation 。添加web支援!
- 1.2 标題由于Maven可能存在資源過濾的問題,我們将配置完善
- 1.3 在pom.xml檔案引入相關的依賴:主要有Spring架構核心庫、Spring MVC、servlet , JSTL等。我們在父依賴中已經引入了!
- 1.4 配置web.xml
- 1.5 添加springmvc-servlet.xml配置檔案
- 1.6 建立controller類
- 1.7 建立視圖層
- 1.8 配置tomcat
- 2.Controller和RequestMap
-
- 2.1 控制器Controller
- 2.2 RequestMapping
- 2.3 RestFul 風格
- 3.跳轉與資料處理
-
- 3.1 頁面跳轉
- 3.2 資料處理
- 3.3 亂碼問題
- MVC是模型(Model)、視圖(View)、控制器(Controller)的簡寫,是一種軟體設計規範。
- 是将業務邏輯、資料、顯示分離的方法來組織代碼。
- MVC主要作用是降低了視圖與業務邏輯間的雙向偶合。
MVC不是一種設計模式,MVC是一種架構模式。當然不同的MVC存在差異。
- Model(模型):資料模型,提供要展示的資料,是以包含資料和行為,可以認為是領域模型或JavaBean元件(包含資料和行為),不過現在一般都分離開來:Value Object(資料Dao) 和 服務層(行為Service)。也就是模型提供了模型資料查詢和模型資料的狀态更新等功能,包括資料和業務。
- View(視圖):負責進行模型的展示,一般就是我們見到的使用者界面,客戶想看到的東西。
- Controller(控制器):接收使用者請求,委托給模型進行處理(狀态改變),處理完畢後把傳回的模型資料傳回給視圖,由視圖負責展示。也就是說控制器做了個排程員的工作。控制器,取得表單資料,調用業務邏輯,轉向指定的頁面。
1. 搭建環境
1.1 建立一個Moudle,springmvc-03-hello-annotation 。添加web支援!
1.2 标題由于Maven可能存在資源過濾的問題,我們将配置完善
<build>
<resources>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
</build>
1.3 在pom.xml檔案引入相關的依賴:主要有Spring架構核心庫、Spring MVC、servlet , JSTL等。我們在父依賴中已經引入了!
1.4 配置web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<!--1.注冊servlet-->
<servlet>
<servlet-name>SpringMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--通過初始化參數指定SpringMVC配置檔案的位置,進行關聯-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!-- 啟動順序,數字越小,啟動越早 -->
<load-on-startup>1</load-on-startup>
</servlet>
<!--所有請求都會被springmvc攔截 -->
<servlet-mapping>
<servlet-name>SpringMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
/ 和 / 的差別:< url-pattern > / </ url-pattern > 不會比對到.jsp, 隻針對我們編寫的請求;即:.jsp 不會進入spring的 DispatcherServlet類 。< url-pattern > /* </ url-pattern > 會比對 .jsp,會出現傳回 jsp視圖 時再次進入spring的DispatcherServlet 類,導緻找不到對應的controller是以報404錯。
DispatcherServlet 是什麼
DispatcherServlet本質上就如其名字所展示的那樣是一個Java Servlet。同時它是Spring MVC中最為核心的一塊——前端控制器。它主要用來攔截符合要求的外部請求,并把請求分發到不同的控制器去處理,根據控制器處理後的結果,生成相應的響應發送到用戶端。
DispatcherServlet作為統一通路點,主要進行全局的流程控制。
- 注意web.xml版本問題,要最新版!
- 注冊DispatcherServlet
- 關聯SpringMVC的配置檔案
- 啟動級别為1
映射路徑為 / 【不要用/*,會404】
1.5 添加springmvc-servlet.xml配置檔案
在resource目錄下添加springmvc-servlet.xml配置檔案,配置的形式與Spring容器配置基本類似,為了支援基于注解的IOC,設定了自動掃描包的功能,具體配置資訊如下:
<?xml version="1.0" encoding="UTF-8"?>
<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
https://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!-- 自動掃描包,讓指定包下的注解生效,由IOC容器統一管理 -->
<context:component-scan base-package="com.kuang.controller"/>
<!-- 讓Spring MVC不處理靜态資源 -->
<mvc:default-servlet-handler />
<!--
支援mvc注解驅動
在spring中一般采用@RequestMapping注解來完成映射關系
要想使@RequestMapping注解生效
必須向上下文中注冊DefaultAnnotationHandlerMapping
和一個AnnotationMethodHandlerAdapter執行個體
這兩個執行個體分别在類級别和方法級别處理。
而annotation-driven配置幫助我們自動完成上述兩個執行個體的注入。
-->
<mvc:annotation-driven />
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 字首 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 字尾 -->
<property name="suffix" value=".jsp" />
</bean>
</beans>
在視圖解析器中我們把所有的視圖都存放在/WEB-INF/目錄下,這樣可以保證視圖安全,因為這個目錄下的檔案,用戶端不能直接通路。
讓IOC的注解生效
靜态資源過濾 :HTML . JS . CSS . 圖檔 , 視訊 …
MVC的注解驅動
配置視圖解析器
1.6 建立controller類
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/HelloController")
public class HelloController {
//真實通路位址 : 項目名/HelloController/hello
@RequestMapping("/hello")
public String sayHello(Model model){
//向模型中添加屬性msg與值,可以在JSP頁面中取出并渲染
model.addAttribute("msg","hello,SpringMVC");
//web-inf/jsp/hello.jsp
return "hello";
}
}
- @Controller是為了讓Spring IOC容器初始化時自動掃描到;
- @RequestMapping是為了映射請求路徑,這裡因為類與方法上都有映射是以通路時應該是/HelloController/hello;
- 方法中聲明Model類型的參數是為了把Action中的資料帶到視圖中;
- 方法傳回的結果是視圖的名稱hello,加上配置檔案中的前字尾變成WEB-INF/jsp/hello.jsp。
在WEB-INF/ jsp目錄中建立hello.jsp , 視圖可以直接取出并展示從Controller帶回的資訊;
可以通過EL表示取出Model中存放的值,或者對象;
1.7 建立視圖層
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>SpringMVC</title>
</head>
<body>
${msg}
</body>
</html>
1.8 配置tomcat
注意:打開project settings的artifacts,在WEB-INF下添加lib檔案夾,點+把包全部添加。不然會404
使用springMVC必須配置的三大件:
處理器映射器、處理器擴充卡、視圖解析器
通常,我們隻需要手動配置視圖解析器,而處理器映射器和處理器擴充卡隻需要開啟注解驅動即可,而省去了大段的xml配置
2.Controller和RequestMap
2.1 控制器Controller
- 控制器複雜提供通路應用程式的行為,通常通過接口定義或注解定義兩種方法實作。
- 控制器負責解析使用者的請求并将其轉換為一個模型。
- 在Spring MVC中一個控制器類可以包含多個方法。
- 在Spring MVC中,對于Controller的配置方式有很多種(實作controller接口和使用@controller注解),注解方式常用。
使用注解@controller、
- @Controller注解類型用于聲明Spring類的執行個體是一個控制器(在講IOC時還提到了另外3個注解);
- Spring可以使用掃描機制來找到應用程式中所有基于注解的控制器類,為了保證Spring能找到你的控制器,需要在配置檔案中聲明元件掃描。
<!-- 自動掃描指定的包,下面所有注解類交給IOC容器管理 -->
<context:component-scan base-package="com.kuang.controller"/>
- 增加一個ControllerTest2類,使用注解實作;
//@Controller注解的類會自動添加到Spring上下文中
@Controller
public class ControllerTest2{
//映射通路路徑
@RequestMapping("/t2")
public String index(Model model){
//Spring MVC會自動執行個體化一個Model對象用于向視圖中傳值
model.addAttribute("msg", "ControllerTest2");
//傳回視圖位置
return "test";
}
}

可以發現,我們的兩個請求都可以指向一個視圖,但是頁面結果的結果是不一樣的,從這裡可以看出視圖是被複用的,而控制器與視圖之間是弱偶合關系。
2.2 RequestMapping
- @RequestMapping注解用于映射url到控制器類或一個特定的處理程式方法。可用于類或方法上。用于類上,表示類中的所有響應請求的方法都是以該位址作為父路徑。
- 為了測試結論更加準确,我們可以加上一個項目名測試 myweb
- 隻注解在方法上面
@Controller
public class TestController {
@RequestMapping("/h1")
public String test(){
return "test";
}
}
通路路徑:http://localhost:8080 / 項目名 / h1
- 同時注解類與方法
@Controller
@RequestMapping("/admin")
public class TestController {
@RequestMapping("/h1")
public String test(){
return "test";
}
}
通路路徑:http://localhost:8080 / 項目名/ admin /h1 , 需要先指定類的路徑再指定方法的路徑;
2.3 RestFul 風格
概念
Restful就是一個資源定位及資源操作的風格。不是标準也不是協定,隻是一種風格。基于這個風格設計的軟體可以更簡潔,更有層次,更易于實作緩存等機制。
功能
資源:網際網路所有的事物都可以被抽象為資源
資源操作:使用POST、DELETE、PUT、GET,使用不同方法對資源進行操作。
分别對應 添加、 删除、修改、查詢。
傳統方式操作資源 :通過不同的參數來實作不同的效果!方法單一,post 和 get
http://127.0.0.1/item/queryItem.action?id=1 查詢,GET
http://127.0.0.1/item/saveItem.action 新增,POST
http://127.0.0.1/item/updateItem.action 更新,POST
http://127.0.0.1/item/deleteItem.action?id=1 删除,GET或POST
使用RESTful操作資源 :可以通過不同的請求方式來實作不同的效果!如下:請求位址一樣,但是功能可以不同!
http://127.0.0.1/item/1 查詢,GET
http://127.0.0.1/item 新增,POST
http://127.0.0.1/item 更新,PUT
http://127.0.0.1/item/1 删除,DELETE
學習測試
- 建立一個類 RestFulController
@Controller
public class RestFulController {
}
- 在Spring MVC中可以使用 @PathVariable 注解,讓方法參數的值對應綁定到一個URI模闆變量上。
@Controller
public class RestFulController {
//映射通路路徑
@RequestMapping("/commit/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable int p2, Model model){
int result = p1+p2;
//Spring MVC會自動執行個體化一個Model對象用于向視圖中傳值
model.addAttribute("msg", "結果:"+result);
//傳回視圖位置
return "test";
}
}
- 測試
SSM------------------SpringMVC1. 搭建環境2.Controller和RequestMap3.跳轉與資料處理 -
使用路徑變量的好處
使路徑變得更加簡潔;
獲得參數更加友善,架構會自動進行類型轉換。
通過路徑變量的類型可以限制通路參數,如果類型不一樣,則通路不到對應的請求方法,如這裡通路是的路徑是/commit/1/a,則路徑與方法不比對,而不會是參數轉換失敗。
修改正确再測試SSM------------------SpringMVC1. 搭建環境2.Controller和RequestMap3.跳轉與資料處理
//映射通路路徑
@RequestMapping("/commit/{p1}/{p2}")
public String index(@PathVariable int p1, @PathVariable String p2, Model model){
String result = p1+p2;
//Spring MVC會自動執行個體化一個Model對象用于向視圖中傳值
model.addAttribute("msg", "結果:"+result);
//傳回視圖位置
return "test";
}
使用method屬性指定請求類型
用于限制請求的類型,可以收窄請求範圍。指定請求謂詞的類型如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE等
//映射通路路徑,必須是POST請求
@RequestMapping(value = "/hello",method = {RequestMethod.POST})
public String index2(Model model){
model.addAttribute("msg", "hello!");
return "test";
}
如果頁面請求是get則報錯
方法級别的注解變體有如下幾個:
@GetMapping
等價@RequestMapping(method =RequestMethod.GET)
@PostMapping
@PutMapping
@DeleteMapping
@PatchMapping
3.跳轉與資料處理
3.1 頁面跳轉
- ModelAndView
設定ModelAndView對象 , 根據view的名稱 , 和視圖解析器跳到指定的頁面 .
頁面 : {視圖解析器字首} + viewName +{視圖解析器字尾}
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 字首 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 字尾 -->
<property name="suffix" value=".jsp" />
</bean>
對應的controller類
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//傳回一個模型視圖對象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
- ServletAPI
通過設定ServletAPI , 不需要視圖解析器 .
1、通過HttpServletResponse進行輸出
2、通過HttpServletResponse實作重定向
3、通過HttpServletResponse實作轉發
@Controller
public class ResultGo {
@RequestMapping("/result/t1")
public void test1(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.getWriter().println("Hello,Spring BY servlet API");
}
@RequestMapping("/result/t2")
public void test2(HttpServletRequest req, HttpServletResponse rsp) throws IOException {
rsp.sendRedirect("/index.jsp");
}
@RequestMapping("/result/t3")
public void test3(HttpServletRequest req, HttpServletResponse rsp) throws Exception {
//轉發
req.setAttribute("msg","/result/t3");
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,rsp);
}
}
- SpringMVC
通過SpringMVC來實作轉發和重定向 - 無需視圖解析器;
測試前,需要将視圖解析器注釋掉
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 字首 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 字尾 -->
<property name="suffix" value=".jsp" />
</bean>
@Controller
public class ResultSpringMVC {
@RequestMapping("/rsm/t1")
public String test1(){
//轉發
return "/index.jsp";
}
@RequestMapping("/rsm/t2")
public String test2(){
//轉發二
return "forward:/index.jsp";
}
@RequestMapping("/rsm/t3")
public String test3(){
//重定向
return "redirect:/index.jsp";
}
}
通過SpringMVC來實作轉發和重定向 - 有視圖解析器;
重定向 , 不需要視圖解析器 , 本質就是重新請求一個新地方嘛 , 是以注意路徑問題.
可以重定向到另外一個請求實作 .
@Controller
public class ResultSpringMVC2 {
@RequestMapping("/rsm2/t1")
public String test1(){
//轉發
return "test";
}
@RequestMapping("/rsm2/t2")
public String test2(){
//重定向
return "redirect:/index.jsp";
//return "redirect:hello.do"; //hello.do為另一個請求/
}
}
3.2 資料處理
處理送出資料
1、送出的域名稱和處理方法的參數名一緻
送出資料 : http://localhost:8080/hello?name=kuangshen
處理方法 :
@RequestMapping("/hello")
public String hello(String name){
System.out.println(name);
return "hello";
}
背景輸出 : kuangshen
2、送出的域名稱和處理方法的參數名不一緻
送出資料 : http://localhost:8080/hello?username=kuangshen
處理方法 :
//@RequestParam("username") : username送出的域的名稱 .
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name){
System.out.println(name);
return "hello";
}
背景輸出 : kuangshen
3、送出的是一個對象
要求送出的表單域和對象的屬性名一緻 , 參數使用對象即可
1、實體類
public class User {
private int id;
private String name;
private int age;
//構造
//get/set
//tostring()
}
2、送出資料 : http://localhost:8080/mvc04/user?name=kuangshen&id=1&age=15
3、處理方法 :
@RequestMapping("/user")
public String user(User user){
System.out.println(user);
return "hello";
}
背景輸出 : User { id=1, name='kuangshen', age=15 }
說明:如果使用對象的話,前端傳遞的參數名和對象名必須一緻,否則就是null。
資料顯示到前端
第一種 : 通過ModelAndView
我們前面一直都是如此 . 就不過多解釋
public class ControllerTest1 implements Controller {
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//傳回一個模型視圖對象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","ControllerTest1");
mv.setViewName("test");
return mv;
}
}
第二種 : 通過ModelMap
ModelMap
@RequestMapping("/hello")
public String hello(@RequestParam("username") String name, ModelMap model){
//封裝要顯示到視圖中的資料
//相當于req.setAttribute("name",name);
model.addAttribute("name",name);
System.out.println(name);
return "hello";
}
第三種 : 通過Model
Model
@RequestMapping("/ct2/hello")
public String hello(@RequestParam("username") String name, Model model){
//封裝要顯示到視圖中的資料
//相當于req.setAttribute("name",name);
model.addAttribute("msg",name);
System.out.println(name);
return "test";
}
對比
就對于新手而言簡單來說使用差別就是:
Model 隻有寥寥幾個方法隻适合用于儲存資料,簡化了新手對于Model對象的操作和了解; 繼承了 LinkedMap ,除了實作了自身的一些方法,同樣的繼承 LinkedMap 的方法和特性;
ModelAndView 可以在儲存資料的同時,可以進行設定傳回的邏輯視圖,進行控制展示層的跳轉。
3.3 亂碼問題
測試步驟:
1、我們可以在首頁編寫一個送出的表單
2、背景編寫對應的處理類
不得不說,亂碼問題是在我們開發中十分常見的問題,也是讓我們程式猿比較頭大的問題!
以前亂碼問題通過過濾器解決 , 而SpringMVC給我們提供了一個過濾器 , 可以在web.xml中配置 .
修改了xml檔案需要重新開機伺服器!
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>utf-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
但是我們發現 , 有些極端情況下.這個過濾器對get的支援不好 .
處理方法 :
1、修改tomcat配置檔案 :設定編碼!
<Connector URIEncoding="utf-8" port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
2、自定義過濾器
package com.kuang.filter;
import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletRequestWrapper;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.Map;
/**
* 解決get和post請求 全部亂碼的過濾器
*/
public class GenericEncodingFilter implements Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//處理response的字元編碼
HttpServletResponse myResponse=(HttpServletResponse) response;
myResponse.setContentType("text/html;charset=UTF-8");
// 轉型為與協定相關對象
HttpServletRequest httpServletRequest = (HttpServletRequest) request;
// 對request包裝增強
HttpServletRequest myrequest = new MyRequest(httpServletRequest);
chain.doFilter(myrequest, response);
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
}
//自定義request對象,HttpServletRequest的包裝類
class MyRequest extends HttpServletRequestWrapper {
private HttpServletRequest request;
//是否編碼的标記
private boolean hasEncode;
//定義一個可以傳入HttpServletRequest對象的構造函數,以便對其進行裝飾
public MyRequest(HttpServletRequest request) {
super(request);// super必須寫
this.request = request;
}
// 對需要增強方法 進行覆寫
@Override
public Map getParameterMap() {
// 先獲得請求方式
String method = request.getMethod();
if (method.equalsIgnoreCase("post")) {
// post請求
try {
// 處理post亂碼
request.setCharacterEncoding("utf-8");
return request.getParameterMap();
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
} else if (method.equalsIgnoreCase("get")) {
// get請求
Map<String, String[]> parameterMap = request.getParameterMap();
if (!hasEncode) { // 確定get手動編碼邏輯隻運作一次
for (String parameterName : parameterMap.keySet()) {
String[] values = parameterMap.get(parameterName);
if (values != null) {
for (int i = 0; i < values.length; i++) {
try {
// 處理get亂碼
values[i] = new String(values[i]
.getBytes("ISO-8859-1"), "utf-8");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
}
}
}
hasEncode = true;
}
return parameterMap;
}
return super.getParameterMap();
}
//取一個值
@Override
public String getParameter(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
if (values == null) {
return null;
}
return values[0]; // 取回參數的第一個值
}
//取所有值
@Override
public String[] getParameterValues(String name) {
Map<String, String[]> parameterMap = getParameterMap();
String[] values = parameterMap.get(name);
return values;
}
}
然後在web.xml中配置這個過濾器即可!
亂碼問題,需要平時多注意,在盡可能能設定編碼的地方,都設定為統一編碼 UTF-8!