1. SpringMVC初識

1 SpringMVC的介紹

  1. springMVC是Spring框架的一部分,是基於java實現的一個輕量級web框架
  2. 學習SpringMVC框架最核心的就是DispatcherServlet的設計,掌握好DispatcherServlet是掌握SpringMVC的核心關鍵

2 基於XML的HelloWorld

  1. 創建maven項目–右鍵項目–Add Framework Support–勾選Web Application(4.0)
  2. 添加pom依賴
<dependencies>
    <!--可以不導該包,因爲下面的包會把這個包的內容一起導入進來-->
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-context -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-context</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-web -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-web</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
    <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-webmvc</artifactId>
        <version>5.2.3.RELEASE</version>
    </dependency>
</dependencies>
  1. 編寫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">
    <!--配置DispatcherServlet-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--1. 關聯springmvc的配置文件,其實init-param參數配置,可以在servlet中通過ServletConfig讀取到 -->
        <!--2. 默認將springmvc的配置文件添加到/WEB-INF/的目錄下,但配置文件名稱必須是"<servlet-name>-servlet.xml",例如"springmvc-servlet.xml"
            3. 但本例中,想把配置文件放到resources文件夾下,也就是classpath對應的路徑中,因此有如下配置-->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:applicationContext.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--1. /*和/都表示攔截所有請求,/會攔截的請求不包含*.jsp,而/*的範圍更大,還會攔截*.jsp這些請求,而DispatcherServlet中處理不了jsp文件,因此配成/*時,訪問jsp文件會報錯-->
        <!--2. 配置爲/後,想請求一個內部的html頁面會報錯
                1. 當前web.xml文件會繼承tomcat下的web.xml文件,而在tomcat-web.xml文件中,包含一個DefaultServlet處理類,用來處理靜態資源
                2. 使用了/的方式會覆蓋父web.xml對靜態資源的處理,所以此時所有靜態資源的訪問,也需要由DispatcherServlet進行處理,而DispatcherServlet也處理不了html文件,因此會報404,請求不到
                3. jsp能處理是因爲在父web.xml中,使用了JspServlet的處理類單獨處理jsp文件,因此jsp文件會交給tomcat進行處理,而不是我們定義的DispatcherServlet,自然也不會報錯-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--1. 爲了html好用,可以添加如下內容,爲了使用DefaultServlet,需要添加catalina.jar-->
    <!--2. 可以在web下直接創建html文件,通過http://localhost:8080/linux.html請求,發現好用-->
    <servlet>
        <servlet-name>default</servlet-name>
        <servlet-class>org.apache.catalina.servlets.DefaultServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
    </servlet-mapping>
</web-app>
  1. applicationContext.xml:在resources下編寫spring配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置前綴,最後/必須存在-->
        <property name="prefix" value="/WEB-INF/jsp/"></property>
        <!--配置後綴-->
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!--需要加/否則不生效-->
    <bean id="/hello" class="com.mashibing.controller.HelloController"></bean>
</beans>
  1. HelloController.java:需要導入servlet和jsp的jar包,否則編譯不過去
package com.mashibing.controller;


import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloController implements Controller {
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
        //創建模型和視圖對象
        ModelAndView mv = new ModelAndView();
        //將需要的值傳遞到model中
        mv.addObject("msg","helloSpringMVC");
        //設置要跳轉的視圖,也就是要跳轉的頁面的名稱
        mv.setViewName("hello");
        return mv;
    }
}
  1. 創建hello.jsp頁面
<%--
  Created by IntelliJ IDEA.
  User: root
  Date: 2020/3/5
  Time: 20:25
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>
  1. Artifacts–右鍵WEB-INF–Create Directory–lib–右鍵lib–Add Copy Of–Library Files–選中Tomcat中沒有的所有jar包
  2. 配置tomcat,發送請求:http://localhost:8080/hello

3 基於註解的HelloWorld

  1. 添加pom依賴
  2. web.xml
  3. spring配置文件:applicationContext.xml
<!--注意添加該條,保證Spring能夠管理HelloController對象-->
<context:component-scan base-package="com.mashibing"></context:component-scan>
  1. HelloController.java
package com.mashibing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class HelloController{
    /*
    * 1. @RequestMapping:就是用來標識此方法用來處理什麼請求
    * 2. /可以取消,取消後默認也是從當前項目的根目錄開始查找,一般在編寫的時候看個人習慣
    * 3. @RequestMapping也可以用來加在類上,添加在類上時,表示爲當前類的所有方法的請求地址添加一個前置路徑,訪問的時候必須要添加此路徑,即需要訪問/hello/hello才能訪問到hello方法
    * 4. 當包含多個Controller,同時在不同Controller中包含同名請求時,需要在類上也添加@RequestMapping註釋,因爲很可能不同模塊不同人編寫,結果起了同樣的名字,訪問時就會報錯
    * */
    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","hello,SpringMVC");
        //1. 視圖解析器會將這個字符串與自身定義的前綴後綴進行拼接,從而找到真正要請求的jsp文件
        //2. 此處也可以返回一個視圖對象,那麼就不用視圖解析器再對字符串進行處理了
        return "hello";
    }
}
  1. 編寫hello.jsp
  2. 輸入請求http://localhost:8080/hello

4 @RequestMapping

4.1 屬性值

  1. value:要匹配的請求
  2. method:限制發送請求的方式: method={RequestMethod.POST}
  3. params:表示請求要接受的參數,如果定義了這個屬性,那麼發送的時候必須要添加該參數
    1. 直接寫參數的名稱:params = {“username”}
    2. 表示請求不能包含的參數:params = {"!username"}
    3. 表示請求中需要要包含的參數但是可以限制值:params = {“username!=123”,“age”}
  4. headers:request中必須包含指定的header值,該方法才能處理請求
  5. consumes:方法只處理Content-Type爲指定值的請求,在request中,Content-Type用來告訴服務器當前發送的數據是什麼格式
  6. produces:方法只處理Accept中包含指定值的請求,在request中,Accept用來告訴服務器,客戶端能認識哪些格式,最好返回這些格式中的其中一種
package com.mashibing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/mashibing")
public class HelloController{

    @RequestMapping("/hello")
    public String hello(Model model){
        model.addAttribute("msg","hello,SpringMVC");
        return "hello";
    }
    @RequestMapping(value = "/hello2",method = RequestMethod.POST)
    public String hello2(){
        return "hello";
    }

    @RequestMapping(value = "/hello3",params = {"username!=123","age"})
    public String hello3(String username){
        System.out.println(username);
        return "hello";
    }

    @RequestMapping(value = "/hello4",headers = {"User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:73.0) Gecko/20100101 Firefox/73.0"})
    public String hello4(){
        return "hello";
    }
}

4.2 通配符

  1. @RequestMapping包含三種模糊匹配的方式
    1. ?:能替代任意一個字符
    2. *: 能替代任意多個字符和一層路徑
    3. **:能代替多層路徑
@RequestMapping(value = "/**/h*llo?")
public String hello5(){
    System.out.println("hello5");
    return "hello";
}

5 @PathVariable

  1. 可以獲取請求路徑中的值
  2. 如果不加@PathVariable,默認爲url中,?name="zhangsan"中的這個name
@RequestMapping(value = "/pathVariable/{name}")
//如果參數列表中名稱與url中佔位符名稱不一樣,可以爲PathVariable添加屬性,表示該變量匹配url中哪個變量,建議填寫
public String pathVariable(@PathVariable("name") String name){
    System.out.println(name);
    return "hello";
}

6 REST

  1. REST爲表現層狀態轉化,是目前最流行的一個互聯網軟件架構,可以降低開發的複雜性,提高系統的可伸縮性
  2. 我們在獲取資源的時候就是進行增刪改查的操作,如果是原來的架構風格,需要發送四個請求
    1. 查詢:localhost:8080/query?id=1
    2. 增加:localhost:8080/insert
    3. 刪除:localhost:8080/delete?id=1
    4. 更新:localhost:8080/update?id=1
  3. 按照此方式發送請求的時候比較麻煩,需要定義多種請求,而在HTTP協議中,有不同的發送請求的方式,分別是GET、POST、PUT、DELETE等,我們如果能讓不同的請求方式表示不同的請求類型就可以簡化我們的查詢
    1. 查詢:localhost:8080/book/1:發送get請求
    2. 增加:localhost:8080/book:發送post請求
    3. 刪除:localhost:8080/book/1:發送delete請求
    4. 更新:localhost:8080/book/1:發送put請求
  4. 我們在發送請求的時候只能發送post或者get,沒有辦法發送put和delete請求,因此需要在頁面中,對請求類型進行轉換,這也就是REST表現層狀態轉換的名稱由來
  5. RestController.java
package com.mashibing.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.view.InternalResourceViewResolver;

@Controller
public class RestController {

    @RequestMapping(value = "/user",method = RequestMethod.POST)
    public String add(){
        System.out.println("添加");
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.DELETE)
    public String delete(@PathVariable("id") Integer id){
        System.out.println("刪除:"+id);
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.PUT)
    public String update(@PathVariable("id") Integer id){
        System.out.println("更新:"+id);
        return "success";
    }

    @RequestMapping(value = "/user/{id}",method = RequestMethod.GET)
    public String query(@PathVariable("id") Integer id){
        System.out.println("查詢:"+id);
        return "success";
    }
}
  1. 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">
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--添加過濾器,該過濾器可以完成請求方式的轉換,將post請求轉換爲put或delete-->
    <filter>
        <filter-name>hiddenFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>hiddenFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
  1. rest.jsp
<%--
    Created by IntelliJ IDEA.
    User: root
        Date: 2020/3/6
            Time: 23:01
                To change this template use File | Settings | File Templates.
                --%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        <form action="/user" method="post">
            <input type="submit" value="增加">
        </form>
        <form action="/user/1" method="post">
            <!--在form表單中,需要配置一個input,name固定爲_method,value配置爲想轉換成的請求-->
            <input name="_method" value="delete" type="hidden">
            <input type="submit" value="刪除">
        </form>
        <form action="/user/1" method="post">
            <input name="_method" value="put" type="hidden">
            <input type="submit" value="修改">
        </form>
        <a href="/user/1">查詢</a><br/>
    </body>
</html>
  1. success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isErrorPage="true" %>
<html>
    <head>
        <title>Title</title>
    </head>
    <body>
        666
    </body>
</html>
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章