1 SpringMVC的介紹
springMVC是Spring框架的一部分,是基於java實現的一個輕量級web框架
學習SpringMVC框架最核心的就是DispatcherServlet的設計,掌握好DispatcherServlet是掌握SpringMVC的核心關鍵
2 基於XML的HelloWorld
創建maven項目–右鍵項目–Add Framework Support–勾選Web Application(4.0)
添加pom依賴
< dependencies>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-context</ artifactId>
< version> 5.2.3.RELEASE</ version>
</ dependency>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-web</ artifactId>
< version> 5.2.3.RELEASE</ version>
</ dependency>
< dependency>
< groupId> org.springframework</ groupId>
< artifactId> spring-webmvc</ artifactId>
< version> 5.2.3.RELEASE</ version>
</ dependency>
</ dependencies>
編寫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:applicationContext.xml</ param-value>
</ init-param>
</ servlet>
< servlet-mapping>
< servlet-name> springmvc</ servlet-name>
< url-pattern> /</ url-pattern>
</ servlet-mapping>
< 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>
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>
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 ( ) ;
mv. addObject ( "msg" , "helloSpringMVC" ) ;
mv. setViewName ( "hello" ) ;
return mv;
}
}
創建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>
Artifacts–右鍵WEB-INF–Create Directory–lib–右鍵lib–Add Copy Of–Library Files–選中Tomcat中沒有的所有jar包
配置tomcat,發送請求:http://localhost:8080/hello
3 基於註解的HelloWorld
添加pom依賴
web.xml
spring配置文件:applicationContext.xml
< context: component-scan base-package = " com.mashibing" > </ context: component-scan>
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 {
@RequestMapping ( "/hello" )
public String hello ( Model model) {
model. addAttribute ( "msg" , "hello,SpringMVC" ) ;
return "hello" ;
}
}
編寫hello.jsp
輸入請求http://localhost:8080/hello
4 @RequestMapping
4.1 屬性值
value:要匹配的請求
method:限制發送請求的方式: method={RequestMethod.POST}
params:表示請求要接受的參數,如果定義了這個屬性,那麼發送的時候必須要添加該參數
直接寫參數的名稱:params = {“username”}
表示請求不能包含的參數:params = {"!username"}
表示請求中需要要包含的參數但是可以限制值:params = {“username!=123”,“age”}
headers:request中必須包含指定的header值,該方法才能處理請求
consumes:方法只處理Content-Type爲指定值的請求,在request中,Content-Type用來告訴服務器當前發送的數據是什麼格式
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 通配符
@RequestMapping包含三種模糊匹配的方式
?:能替代任意一個字符
*: 能替代任意多個字符和一層路徑
**:能代替多層路徑
@RequestMapping ( value = "/**/h*llo?" )
public String hello5 ( ) {
System. out. println ( "hello5" ) ;
return "hello" ;
}
5 @PathVariable
可以獲取請求路徑中的值
如果不加@PathVariable,默認爲url中,?name="zhangsan"中的這個name
@RequestMapping ( value = "/pathVariable/{name}" )
public String pathVariable ( @PathVariable ( "name" ) String name) {
System. out. println ( name) ;
return "hello" ;
}
6 REST
REST爲表現層狀態轉化,是目前最流行的一個互聯網軟件架構,可以降低開發的複雜性,提高系統的可伸縮性
我們在獲取資源的時候就是進行增刪改查的操作,如果是原來的架構風格,需要發送四個請求
查詢:localhost:8080/query?id=1
增加:localhost:8080/insert
刪除:localhost:8080/delete?id=1
更新:localhost:8080/update?id=1
按照此方式發送請求的時候比較麻煩,需要定義多種請求,而在HTTP協議中,有不同的發送請求的方式,分別是GET、POST、PUT、DELETE等,我們如果能讓不同的請求方式表示不同的請求類型就可以簡化我們的查詢
查詢:localhost:8080/book/1:發送get請求
增加:localhost:8080/book:發送post請求
刪除:localhost:8080/book/1:發送delete請求
更新:localhost:8080/book/1:發送put請求
我們在發送請求的時候只能發送post或者get,沒有辦法發送put和delete請求,因此需要在頁面中,對請求類型進行轉換,這也就是REST表現層狀態轉換的名稱由來
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" ;
}
}
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>
< 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>
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>
success.jsp
< % @ page contentType= "text/html;charset=UTF-8" language= "java" isErrorPage= "true" % >
< html>
< head>
< title> Title< / title>
< / head>
< body>
666
< / body>
< / html>