推薦博客:https://www.cnblogs.com/hellokuangshen/p/11270742.html
師傅博客很優秀的
Controller配置
控制器Controller
控制器複雜提供訪問應用程序的行爲,通常通過接口定義或註解定義兩種方法實現。 控制器負責解析用戶的請求並將其轉換爲一個模型。在Spring MVC中一個控制器類可以包含多個方法;
在SpringMVC中,對於Controller的配置方式有很多種;
控制器實現方式:實現Controller接口
控制器實現方式:實現Controller接口
Controller是一個接口,在org.springframework.web.servlet.mvc包下,接口中只有一個方法;
//實現該接口的類獲得控制器功能
public interface Controller {
//處理請求且返回一個模型與視圖對象
ModelAndView handleRequest(HttpServletRequest var1, HttpServletResponse var2) throws Exception;
}
1.新建一個Maven的Web項目,導入相應jar包,保險起見,同之前一樣,也需要處理資源過濾問題!
2.配置web.xml 中的 DispatcherServlet ,同之前一樣
3.配置springmvc-servlet.xml
<?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
http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd">
<!--=======SpringMVC_Start=======-->
<!-- 視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前綴 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 後綴 -->
<property name="suffix" value=".jsp" />
</bean>
<!--=======SpringMVC_END=======-->
</beans>
4.編寫一個Controller類
注意點:不要導錯包,實現Controller接口,重寫方法;
//定義控制器
public class Test1Controller implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
//返回一個模型視圖對象
ModelAndView mv = new ModelAndView();
mv.addObject("msg","Test1Controller");
mv.setViewName("test");
return mv;
}
}
編寫完畢後,去Spring配置文件中註冊請求的bean;name對應請求路徑,class對應處理請求的類
<bean name="/233" class="com.kuang.controller.Test1Controller"/>
5.編寫前端test.jsp,注意在WEB-INF/jsp目錄下編寫,對應我們的視圖解析器
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Kuangshen</title>
</head>
<body>
${msg}
</body>
</html>
6.配置Tomcat運行測試,我這裏沒有項目發佈名配置的就是一個 / ,所以請求不用加項目名,OK!
實現接口Controller定義控制器是較老的辦法,缺點是:一個控制器中只有一個方法,如果要多個方法則需要定義多個Controller;定義的方式比較麻煩;
項目實現
項目結構:
pom.xml文件:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.kuang</groupId>
<artifactId>SpringMVC</artifactId>
<packaging>pom</packaging>
<version>1.0-SNAPSHOT</version>
<modules>
<module>demo01_servlet</module>
<module>demo02_springmvc_li</module>
</modules>
<!--導入依賴-->
<dependencies>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
</dependency>
<!--Mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.6</version>
</dependency>
<!--mysql驅動-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
<!--Mybatis-spring-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<!--spring系列-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>4.3.24.RELEASE</version>
</dependency>
<!--servlet-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
</dependency>
<!--jsp-jstl-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<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>
</project>
web.xml文件配置:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
id="WebApp_ID" version="3.0">
<!--1.註冊DispatcherServlet-->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!--關聯一個springmvc的配置文件:【servlet-name】-servlet.xml-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc-servlet.xml</param-value>
</init-param>
<!--啓動級別-1-->
<load-on-startup>1</load-on-startup>
</servlet>
<!--/ 匹配所有的請求;(不包括.jsp)-->
<!--/* 匹配所有的請求;(包括.jsp)-->
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
resources文件:
springmvc-servlet.xml文件配置
<?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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--Handler-->
<bean id="/hello" class="com.kuang.controller.HelloController"/>
<!--自動掃描指定包下的註解,將他放到Spring的IOC容器-->
<!-- <context:component-scan base-package="com.kuang.controller"/>-->
<!--靜態資源過濾處理-->
<!-- <mvc:default-servlet-handler/>-->
<!--註解驅動
在spring中一般採用@RequestMapping註解來完成映射關係
要想使@RequestMapping註解生效
必須向上下文中註冊DefaultAnnotationHandlerMapping
和一個AnnotationMethodHandlerAdapter實例
這兩個實例分別在類級別和方法級別處理。
而annotation-driven配置幫助我們自動完成上述兩個實例的注入。
-->
<!-- <mvc:annotation-driven/>-->
<!--2.處理器映射器:通過url找到對應的DispatcherServlet改調用的適配器controller:/hello->helloController-->
<!--<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>-->
<!--3.處理器適配器:helloController去適配Controller,找helloController-->
<!--<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>-->
<!--視圖解析器:DispatcherServlet給他的ModelAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前綴-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--後綴-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
controller文件:
HelloController:
package com.kuang.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 {
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
//ModelAndView 模型和視圖
ModelAndView mv = new ModelAndView();
//封裝對象,放在ModelAndView中。Model
mv.addObject("msg","HelloSpringMVC!");
//封裝要跳轉的視圖,放在ModelAndView中
mv.setViewName("hello"); //: /WEB-INF/jsp/hello.jsp
return mv;
}
}
jsp頁面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Kuangshen</title>
</head>
<body>
${msg}
</body>
</html>
項目輸出:
這裏項目名爲mvc
使用註解@Controller定義控制器(推薦)
@Controller註解類型用於聲明Spring類的實例是一個控制器(在講IOC時還提到了另外3個註解);
Spring可以使用掃描機制來找到應用程序中所有基於註解的控制器類,爲了保證Spring能找到你的控制器,需要在配置文件中聲明組件掃描。
<!-- 自動掃描指定的包,下面所有註解類交給IOC容器管理 -->
<context:component-scan base-package="com.kuang.controller"/>
修改我們的TestController類,使用註解實現;
//@Controller註解的類會自動添加到Spring上下文中
@Controller
public class Test1Controller{
//映射訪問路徑
@RequestMapping("/233")
public String index(Model model){
//Spring MVC會自動實例化一個Model對象用於向視圖中傳值
model.addAttribute("msg", "註解");
//返回視圖位置
return "test";
}
}
運行tomcat測試
可以發現,我們的兩個請求都可以指向一個視圖,但是頁面結果的結果是不一樣的,從這裏可以看出視圖是被複用的,而控制器與視圖之間是弱偶合關係。
@RequestMapping
@RequestMapping註釋用於映射url到控制器類或一個特定的處理程序方法。可用於類或方法上。用於類上,表示類中的所有響應請求的方法都是以該地址作爲父路徑。
只註解在方法上面
@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 , 需要先指定類的路徑再指定方法的路徑;
項目實現
修改resources文件:
springmvc-servlet配置文件:
<?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
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--Handler-->
<!-- <bean id="/hello" class="com.kuang.controller.HelloController"/>-->
<!--自動掃描指定包下的註解,將他放到Spring的IOC容器-->
<context:component-scan base-package="com.kuang.controller"/>
<!--靜態資源過濾處理-->
<mvc:default-servlet-handler/>
<!--註解驅動
在spring中一般採用@RequestMapping註解來完成映射關係
要想使@RequestMapping註解生效
必須向上下文中註冊DefaultAnnotationHandlerMapping
和一個AnnotationMethodHandlerAdapter實例
這兩個實例分別在類級別和方法級別處理。
而annotation-driven配置幫助我們自動完成上述兩個實例的注入。
-->
<mvc:annotation-driven/>
<!--2.處理器映射器:通過url找到對應的DispatcherServlet改調用的適配器controller:/hello->helloController-->
<!--<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>-->
<!--3.處理器適配器:helloController去適配Controller,找helloController-->
<!--<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>-->
<!--視圖解析器:DispatcherServlet給他的ModelAndView-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<!--前綴-->
<property name="prefix" value="/WEB-INF/jsp/"/>
<!--後綴-->
<property name="suffix" value=".jsp"/>
</bean>
</beans>
編寫controller文件:
AnnoController
package com.kuang.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class AnnoController {
//請求映射:url
@RequestMapping("/hello")
public String hello(Model model){
model.addAttribute("msg","Hello,SpringMVC");
return "hello";
}
@RequestMapping("/hello2")
public String hello2(Model model){
model.addAttribute("msg","Hello,SpringMVC2");
return "hello";
}
}
項目輸出:
Restful風格
概念
Restful就是一個資源定位及資源操作的風格。不是標準也不是協議,只是一種風格。基於這個風格設計的軟件可以更簡潔,更有層次,更易於實現緩存等機制。
功能
資源:互聯網所有的事物都可以被抽象爲資源
資源操作:使用POST、DELETE、PUT、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
在Spring MVC可以使用@PathVariable 註釋方法參數的值對應綁定到一個URI模板變量上。
package com.kuang.controller;
import com.sun.org.apache.regexp.internal.RE;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/item")
public class MappingController {
//@RequestMapping("/add?p1=1&p2=2")
@RequestMapping("/add/{p1}/{p2}/{name}")
public String add(@PathVariable int p1,@PathVariable int p2,@PathVariable String name, Model model){
String sum = p1 + p2 + name;
//String sum = name+ p1 + p2;
model.addAttribute("msg",sum);
return "hello";
}
}
我們請求查看下
使用路徑變量的好處:使路徑變得更加簡潔;獲得參數更加方便,框架會自動進行類型轉換。通過路徑變量的類型可以約束訪問參數,如果類型不一樣,則訪問不到對應的請求方法,如這裏訪問是的路徑是/mvc/item/add/1/2/yalu,則路徑與方法不匹配,而不會是參數轉換失敗。
我們來修改下對應的參數類型
@Controller
@RequestMapping("/item")
public class MappingController {
// @RequestMapping("/add?p1=1&p2=2")
@RequestMapping("/add/{p1}/{p2}/{name}")
public String add(@PathVariable int p1,@PathVariable int p2,@PathVariable String name, Model model){
// String sum = p1 + p2 + name;
String sum = name+ p1 + p2;
model.addAttribute("msg",sum);
return "hello";
}
這裏我們可以看出兩者的區別!
method屬性指定請求類型
用於約束請求的類型,可以收窄請求範圍。指定請求謂詞的類型如GET, POST, HEAD, OPTIONS, PUT, PATCH, DELETE, TRACE等
我們來測試一下:
package com.kuang.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("/m")
public class MethodController {
//method:限定請求的方法:get。post
//這個方法的意思就是,請求 服務器/項目名/m/post 這個請求只能使用post方法提交
//@RequestMapping(value = "/post",method ={RequestMethod.GET} )
@RequestMapping(value = "/post",method ={RequestMethod.POST} )
public String onlyPost(Model model){
model.addAttribute("msg","允許Post請求進入");
return "hello";
}
}
我們使用瀏覽器地址欄進行訪問默認是Get請求,會報錯405:
如果將POST修改爲GET則正常了;
@Controller
@RequestMapping("/m")
public class MethodController {
//method:限定請求的方法:get。post
//這個方法的意思就是,請求 服務器/項目名/m/post 這個請求只能使用post方法提交
@RequestMapping(value = "/post",method ={RequestMethod.GET} )
// @RequestMapping(value = "/post",method ={RequestMethod.POST} )
public String onlyPost(Model model){
model.addAttribute("msg","允許Post請求進入");
return "hello";
}
}
訪問:
Spring MVC 的 @RequestMapping 註解能夠處理 HTTP 請求的方法, 比如 GET, PUT, POST, DELETE 以及 PATCH。
所有的請求默認都會是 HTTP GET 類型的。
方法級別的註解變體有如下幾個:
@GetMapping
@PostMapping
@PutMapping
@DeleteMapping
@PatchMappin
@GetMapping 是一個組合註解,它所扮演的是 @RequestMapping(method =RequestMethod.GET) 的一個快捷方式。
結果跳轉方式
設置ModelAndView對象,根據View名稱,和視圖解析器,跳轉到指定的頁面;
頁面 :{視圖解析器的前綴} + viewName + {視圖解析器的後綴}
1.ModelAndView
//ModelAndView
@RequestMapping("/t1")
public ModelAndView test1(HttpServletRequest request, HttpServletResponse response){
ModelAndView mv = new ModelAndView();
mv.addObject("msg","test1Controller");
mv.setViewName("test");
return mv;
}
2.ServletAPi
//使用ServletApi
@RequestMapping("/t2")
public void test2(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setAttribute("msg","test2Controller");
//request.getSession().setAttribute();
request.getRequestDispatcher("index.jsp").forward(request,response);//請求轉發
//response.sendRedirect("index.jsp");
}
3.SpringMVC不帶視圖解析器
//使用SpringMVC,不用視圖解析器
@RequestMapping("/t3")
public String test3(HttpServletRequest request){
request.setAttribute("msg","test3Controller");
//return "index.jsp"; //請求轉發
return "forward:index.jsp";//請求轉發
//return "redirect:index.jsp";//重定向
}
4.SpringMVC帶視圖解析器
//使用SpringMVC,有視圖解析器
@RequestMapping("/t4")
public String test4(){
return "test";
}
數據處理
處理前端傳遞過來的數據;
1. 名字規範的數據
@RequestMapping("/hello")
//請求參數名和處理參數名一樣的情況下,我們直接接收到前端傳遞的數據;
//Model主要作用:爲了給前端傳遞我們封裝好的參數;
public String hello(String name, Model model){
System.out.println(name);
model.addAttribute("aaa",name);
return "user";
}
2. 名字不規範的數據
//請求參數名和處理參數名不一樣的情況下
//狀況:用戶傳遞的參數名和我們要處理的參數名不一致,需要使用一個註解@RequestParam("username")來進行匹配
@RequestMapping("/hello2")
public String hello2(@RequestParam(value = "username",required = false) String name){
System.out.println(name);
return "user";
}
3. 傳遞對象
儘量規範的編程:提交表單的數據和對象的屬性名一致
//如何傳遞一個對象
//要求:提交表單的數據和對象的屬性名一致;參數直接使用對象即可;否則按照上面方式處理
//http://localhost:8080/mvc04/hello3?id=1&name=qinjiang&age=18;
@RequestMapping("/hello3")
public String hello3(User user,Model model){
System.out.println(user);
model.addAttribute("user",user);
return "user";
}