創建MVC步驟
導入Spring MVC包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${sping-version}</version>
</dependency>
在web.xml配置
<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:spring-mvc.xml</param-value>
</init-param>
<!-- <load-on-startup>1</load-on-startup> -->
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
在resources中創建spring-mvc.xml
<beans xmlns:mvc="http://www.springframework.org/schema/mvc"
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<!--掃描-->
<!--如果spring已經有掃描所有的包,下面這句可以省略-->
<context:component-scan base-package="com.werner.controller"/>
<!-- 開啓springmvc註解 -->
<mvc:annotation-driven/>
<!--不要處理靜態資源-->
<mvc:default-servlet-handler/>
<!-- 推薦 不要處理資源文件 -->
<mvc:resources mapping="/images/**" location="/WEB-INF/img"/>
<mvc:resources mapping="/js/**" location="/WEB-INF/js"/>
<mvc:resources mapping="/css/**" location="/WEB-INF/css"/>
<mvc:resources mapping="/view/**" location="/WEB-INF/view"/>
<
<!-- 配置視圖解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"
id="internalResourceViewResolver">
<!-- 前綴 -->
<property name="prefix" value="/WEB-INF/jsp/" />
<!-- 後綴 -->
<property name="suffix" value=".jsp" />
</bean>
MVC註解部分
一、@Controller
作用
負責註冊一個bean 到spring 上下文中
栗子
@Controller
public class UserController{
}
二、@RequestMapping(重點)
作用
這個註解主要作用其實就是一個路徑.專業名字叫關係映射.他一般用於 Controller 的類與某個方法中
栗子
使用到類或者方法上
@Controller
@RequestMapping("/account")
public class AccountController {
// 訪問地址 /account/login
@RequestMapping("/login")
public String login() {
return "登錄";
}
}
參數說明
參數 | 說明 |
---|---|
String[] value() | **(重點)**指定請求的實際地址,指定的地址可以是URI Template 模式 等同path |
RequestMethod[] method() | **(重點)**指定請求的method類型, RequestMethod.GET、RequestMethod.POST、RequestMethod.PUT、RequestMethod.DELETE等; |
String[]consumes | 指定處理請求的提交內容類型(Content-Type),例如application/json, text/html; |
String[] produces | 指定返回的內容類型,僅當request請求頭中的(Accept)類型中包含該指定類型才返回; |
String[] params() | **(掌握)**指定限制請求參數的條件。支持簡單的表達式。就是請求地址上的key=value |
String[] headers() | 指定request中必須包含某些指定的header值,才能讓該方法處理請求; |
三、@RequestBody
作用
該註解用於讀取Request請求的body部分數據(get請求沒有請求體,所以不能使用)
栗子
@Controller
@RequestMapping("/body")
public class RequestBodyController {
@RequestMapping(value = "/test1", method = RequestMethod.POST)
public String method1(@RequestBody String name) {
System.out.println(name);
return "請求體參數";
}
}
屬性
參數 | 說明 |
---|---|
boolean required() | 是否必須有請求體。默認值是:true。當取值爲 true 時, |
四、@ResponseBody
作用
該註解用於將Controller的方法返回的對象,通過適當的HttpMessageConverter轉換爲指定格式後
五、@RequestParam
作用
在處理方法入參處使用 @RequestParam 可以把請求參數傳遞給請求方法
集成fastjson
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.58</version>
</dependency>
配置轉化器
<!-- 設置配置方案 -->
<mvc:annotation-driven>
<!-- 消息轉化器 -->
<mvc:message-converters register-defaults="false">
<bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!-- 加入支持的媒體類型:返回contentType -->
<property name="supportedMediaTypes">
<list>
<!-- 這裏順序不能反,一定先寫text/html,不然IE下會出現下載提示 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<property name="fastJsonConfig">
<bean class="com.alibaba.fastjson.support.config.FastJsonConfig">
<property name="features">
<list>
<value>AllowArbitraryCommas</value>
<value>AllowUnQuotedFieldNames</value>
<value>DisableCircularReferenceDetect</value>
</list>
</property>
<!--配置特定的日期格式-->
<property name="dateFormat" value="yyyy-MM-dd HH:mm:ss"/>
</bean>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
引用fastjson之後
@Controller
public class ResponseBodyController {
@RequestMapping("/body")
@ResponseBody
public Shop testResponseBody() {
Shop shop = new Shop();
shop.setShopId(1);
shop.setName("娃娃");
shop.setTitle("白天麼麼噠,晚上怕怕怕");
return shop;
}
}
栗子
給參數起別名
@Controller
@RequestMapping("/params")
public class RequestParamController {
@RequestMapping("/test1")
public String method1(@RequestParam(value = "name") String username) {
System.out.println(username);
return "參數別名"
}
}
//請求地址 /params/test1?name='喬碧蘿殿下'
使用默認值參數
@RestController
@RequestMapping("/params")
public class RequestParamController {
// 請求地址 /params/test2?page=1 或者/params/test2?page=1&size=10
@RequestMapping("/test2")
public String method2(@RequestParam(value = "page", defaultValue = "1") int page ,
@RequestParam(value = "size",required = false,defaultValue = "10") int size) {
System.out.println(page);
System.out.println(size);
return "使用默認值參數+可選參數";
}
}
六、@PathVariable
作用
用於綁定 url 中的佔位符。例如:請求 url 中 /list/{page},這個{page}就是 url 佔位符。url 支持佔位符是 spring3.0 之後加入的。是 springmvc 支持 rest 風格 URL 的一個重要標誌。
屬性
屬性 | 說明 |
---|---|
String value() | 用於指定 url 中佔位符名稱。 |
boolean required() | 是否必須提供佔位符。 |
栗子
@Controller
public class PathController {
@RequestMapping("/path/{page}/{size}")
public String pathTest(@PathVariable(value = "page") int page, @PathVariable String size) {
System.out.println(page);
System.out.println(size);
return "動態路徑匹配";
}
}