準(zhǔn)備
新建工程
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.neuedu</groupId>
<artifactId>springMVC_demo02_response</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>springMVC_demo02_response Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
<spring.version>5.0.2.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
<build>
<finalName>springMVC_demo02_response</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.1.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.22.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.2</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
web.xml
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!--配置前端控制器-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!--配置解決中文亂碼的過(guò)濾器-->
<filter>
<filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
springMVC.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
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
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 開(kāi)啟注解掃描 -->
<context:component-scan base-package="com.neuedu"/>
<!-- 視圖解析器對(duì)象 -->
<bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 開(kāi)啟SpringMVC框架注解的支持 -->
<mvc:annotation-driven />
</beans>
1. 返回值分類(lèi)
1.1字符串
<a href="user/testString" >testString</a>
實(shí)體類(lèi)User
package com.neuedu.domain;
import java.io.Serializable;
public class User implements Serializable {
private String username;
private String password;
private Integer age;
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
UserController類(lèi)
package com.neuedu.controller;
import com.neuedu.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 返回String
* @param model
* @return
*/
@RequestMapping("/testString")
public String testString(Model model){
System.out.println("testString方法執(zhí)行了...");
// 模擬從數(shù)據(jù)庫(kù)中查詢(xún)出User對(duì)象
User user = new User();
user.setUsername("哈哈");
user.setPassword("123");
user.setAge(30);
// model對(duì)象
model.addAttribute("user",user);
return "success";
}
}
success.jsp
<h3>執(zhí)行成功</h3>
${user.age}
${user.password}
1.2 void
<a href="user/testVoid" >testVoid</a>
/**
* 是void
* 請(qǐng)求轉(zhuǎn)發(fā)一次請(qǐng)求桩砰,不用編寫(xiě)項(xiàng)目的名稱(chēng)
*/
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("testVoid方法執(zhí)行了...");
// 編寫(xiě)請(qǐng)求轉(zhuǎn)發(fā)的程序
// request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request,response);
// 重定向
// response.sendRedirect(request.getContextPath()+"/index.jsp");
// 設(shè)置中文亂碼
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 直接會(huì)進(jìn)行響應(yīng)
response.getWriter().print("你好");
return;
}
1.3 ModelAndView
ModelAndView 是 SpringMVC 為我們提供的一個(gè)對(duì)象,該對(duì)象也可以用作控制器方法的返回值钾怔。
該對(duì)象中有兩個(gè)方法:
<a href="user/testModelAndView" >testModelAndView</a>
/**
* 返回ModelAndView
* @return
*/
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView(){
// 創(chuàng)建ModelAndView對(duì)象
ModelAndView mv = new ModelAndView();
System.out.println("testModelAndView方法執(zhí)行了...");
// 模擬從數(shù)據(jù)庫(kù)中查詢(xún)出User對(duì)象
User user = new User();
user.setUsername("哈哈");
user.setPassword("456");
user.setAge(30);
// 把user對(duì)象存儲(chǔ)到mv對(duì)象中幔欧,也會(huì)把user對(duì)象存入到request對(duì)象
mv.addObject("user",user);
// 跳轉(zhuǎn)到哪個(gè)頁(yè)面
mv.setViewName("success");
return mv;
}
2 轉(zhuǎn)發(fā)和重定向
2.1 forward
/**
* 使用關(guān)鍵字的方式進(jìn)行轉(zhuǎn)發(fā)或者重定向
* @return
*/
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
System.out.println("testForwardOrRedirect方法執(zhí)行了...");
// 請(qǐng)求的轉(zhuǎn)發(fā)
return "forward:/pages/success.jsp";
}
需要注意的是微姊,如果用了 formward :則路徑必須寫(xiě)成實(shí)際視圖 url亭螟,不能寫(xiě)邏輯視圖。
它相當(dāng)于“request.getRequestDispatcher("url").forward(request,response)”法褥。使用請(qǐng)求轉(zhuǎn)發(fā)谒臼,既可以轉(zhuǎn)發(fā)到 jsp朝刊,也可以轉(zhuǎn)發(fā)到其他的控制器方法。
2.2 Redirect 重定向
/**
* 使用關(guān)鍵字的方式進(jìn)行轉(zhuǎn)發(fā)或者重定向
* @return
*/
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
System.out.println("testForwardOrRedirect方法執(zhí)行了...");
// 重定向
return "redirect:/index.jsp";
}
它相當(dāng)于“response.sendRedirect(url)”屋休。需要注意的是坞古,如果是重定向到 jsp 頁(yè)面,則 jsp 頁(yè)面不能寫(xiě)在 WEB-INF 目錄中劫樟,否則無(wú)法找到痪枫。
3. ResponseBody響應(yīng)json數(shù)據(jù)
作用:
該注解用于將 Controller 的方法返回的對(duì)象,通過(guò) HttpMessageConverter 接口轉(zhuǎn)換為指定格式的數(shù)據(jù)如:json,xml 等叠艳,通過(guò) Response 響應(yīng)給客戶端
需求:
使用@ResponseBody 注解實(shí)現(xiàn)將 controller 方法返回對(duì)象轉(zhuǎn)換為 json 響應(yīng)給客戶端奶陈。
前置知識(shí)點(diǎn):
Springmvc 默認(rèn)用 MappingJacksonHttpMessageConverter 對(duì) json 數(shù)據(jù)進(jìn)行轉(zhuǎn)換,需要加入jackson 的包附较。
3.1 準(zhǔn)備
過(guò)濾靜態(tài)資源
導(dǎo)入jquery.js
response.jsp
<script src="/js/jquery-3.4.1.js"></script>
<script>
// 頁(yè)面加載吃粒,綁定單擊事件
$(function(){
$("#btn").click(function(){
alert("hello btn");
});
});
</script>
<button id="btn">發(fā)送ajax的請(qǐng)求</button>
3.1 使用說(shuō)明
點(diǎn)擊按鈕并沒(méi)有反應(yīng)
原理:web.xml文件中的前端控制器dispatcherServlet會(huì)進(jìn)行攔截
解決:告訴它,哪些靜態(tài)資源不能攔截拒课,在springMVC.xml中設(shè)置
<!--前端控制器徐勃,哪些靜態(tài)資源不攔截-->
<mvc:resources location="/css/" mapping="/css/**"/>
<mvc:resources location="/images/" mapping="/images/**"/>
<mvc:resources location="/js/" mapping="/js/**"/>
或者可以寫(xiě)成:
<mvc:default-servlet-handler></mvc:default-servlet-handler>
編寫(xiě)原生ajax請(qǐng)求
// 發(fā)送ajax請(qǐng)求
$.ajax({
// 編寫(xiě)json格式,設(shè)置屬性和值
url:"user/testAjax",
contentType:"application/json;charset=UTF-8",
data:'{"username":"hehe","password":"123","age":30}',
dataType:"json",
type:"post",
success:function(data){
// data服務(wù)器端響應(yīng)的json的數(shù)據(jù)早像,進(jìn)行解析
}
});
服務(wù)器UserController處理ajax請(qǐng)求數(shù)據(jù)
/**
* 模擬異步請(qǐng)求響應(yīng)
*/
@RequestMapping("/testAjax")
public void testAjax(@RequestBody String body){
System.out.println("testAjax方法執(zhí)行了...");
System.out.println(body);
}
3.2 使用示例
向pom.xml導(dǎo)入坐標(biāo)
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.9.0</version>
</dependency>
/**
* 模擬異步請(qǐng)求響應(yīng)
*/
@RequestMapping("/testAjax")
public @ResponseBody User testAjax(@RequestBody User user){
System.out.println("testAjax方法執(zhí)行了...");
// 客戶端發(fā)送ajax的請(qǐng)求僻肖,傳的是json字符串,后端把json字符串封裝到user對(duì)象中
System.out.println(user);
// 做響應(yīng)卢鹦,模擬查詢(xún)數(shù)據(jù)庫(kù)
user.setUsername("haha");
user.setAge(40);
// 做響應(yīng)
return user;
}
// 發(fā)送ajax請(qǐng)求
$.ajax({
// 編寫(xiě)json格式臀脏,設(shè)置屬性和值
url:"user/testAjax",
contentType:"application/json;charset=UTF-8",
data:'{"username":"hehe","password":"123","age":30}',
dataType:"json",
type:"post",
success:function(data){
// data服務(wù)器端響應(yīng)的json的數(shù)據(jù),進(jìn)行解析
alert(data);
alert(data.username);
alert(data.password);
alert(data.age);
}
});