一、返回值分類
1、String
controller 方法返回字符串可以指定邏輯視圖名,通過視圖解析器解析爲物理視圖地址,也就是在 SpringMVC.xml 中配置視圖解析器
<bean id="resolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/pages/"/>
<property name="suffix" value=".jsp"/>
</bean>
jsp代碼
<a href="${pageContext.request.contextPath}/user/add">添加</a>
java代碼
@RequestMapping("/add")
public String add(){
System.out.println("添加成功");
return "success";
}
2、void
在 controller 方法形參上可以定義 request 和 response,使用 request 或 response 指定響應結果
1、使用 request 轉向頁面
2、也可以通過 response 頁面重定向
3、也可以通過 response 指定響應結果
jsp 代碼
<a href="${pageContext.request.contextPath}/response/void">點擊跳轉</a>
java 代碼
@RequestMapping("/void")
public void responseDemo(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("請求:" + request + "\t" + ",響應:" + response);
//第一種方式:request 轉發
//request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
//第二種方式:通過 response 頁面重定向
//需要注意的是,如果是重定向到 jsp 頁面,則 jsp 頁面不能寫在 WEB-INF 目錄中,否則無法找到。
response.sendRedirect(request.getContextPath() + "/pages/success.jsp");
//第三種方式:通過 response 指定響應結果,例如響應 json 數據
response.setCharacterEncoding("utf-8");
response.setContentType("application/json; charset=utf-8");
response.getWriter().print("{'success' : 'true', 'msg' : '響應成功'}");
}
3、ModelAndView
ModelAndView 是 SpringMVC 爲我們提供的一個對象,該對象也可以用作控制器方法的返回值。
方法:
addObject(String attributeName,Object attributeValue)
:添加模型到該對象中,作用類似於request對象的setAttribute方法的作用、${requestScope.attributeName}
setView(String viewName)
:設置邏輯視圖名稱,視圖解析器會根據名稱前往指定的視圖
jsp 代碼
<a href="${pageContext.request.contextPath}/response/string">點擊跳轉</a><br>
<a href="${pageContext.request.contextPath}/response/model">點擊跳轉</a>
java 代碼
package cn.lemon.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/response")
public class ResponseController {
@RequestMapping("/string")
public String testString(Model model) {
model.addAttribute("key", "value");// 在model 裏存數據
return "success";
}
//下面這段代碼與上面的代碼等價
@RequestMapping("/model")
public ModelAndView modelAndView(){
ModelAndView mv = new ModelAndView();
mv.addObject("key", "value");
mv.setViewName("success");
return mv;
}
}
返回的 jsp 代碼
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>成功</title>
</head>
<body>
<h1>恭喜您,訪問成功了!!!!</h1>
<h2>取出的值爲:key=${requestScope.key}</h2><%--會出現:value,也就是取出了數據--%>
</body>
</html>
二、轉發和重定向
1、forward 轉發
controller 方法在提供了 String 類型的返回值之後,默認就是請求轉發
jsp 代碼
<a href="${pageContext.request.contextPath}/response/forward">點擊跳轉</a>
java 代碼
@RequestMapping("/forward")
public String forward(){
System.out.println("forward 執行成功");
//return "success";//這個是經過視圖解析器的
/*
需要注意的是,如果用了 formward:則路徑必須寫成實際視圖 url,不能寫邏輯視圖。
它相當於“request.getRequestDispatcher("url").forward(request,response)”。
使用請求轉發,既可以轉發到 jsp,也可以轉發到其他的控制器方法
*/
return "forward:/WEB-INF/pages/success.jsp";
}
2、Redirect 重定向
contrller 方法提供了一個 String 類型返回值之後,它需要在返回值裏使用:redirect
jsp 代碼
<a href="${pageContext.request.contextPath}/response/redirect">點擊跳轉</a>
java 代碼
@RequestMapping("/redirect")
public String redirect(){
System.out.println("redirect 執行成功");
//return "success";//這個是經過視圖解析器的
/*
它相當於“response.sendRedirect(url)”。
需要注意的是,如果是重定向到 jsp 頁面,則 jsp 頁面不能寫在 WEB-INF 目錄中,否則無法找到。
*/
return "redirect:/success.jsp";
}
三、ResponseBody 響應 json 數據
該註解用於將 Controller 的方法返回的對象,通過 HttpMessageConverter 接口轉換爲指定格式的數據如:json,xml 等,通過 Response 響應給客戶端
提醒:
Springmvc 默認用 MappingJacksonHttpMessageConverter 對 json 數據進行轉換,需要加入jackson 的包。(jackson-databind、jackson-core、jackson-annotations)
jsp 代碼
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>首頁</title>
</head>
<script src="${pageContext.request.contextPath}/js/jquery-1.11.0.min.js"></script>
<script>
$(function () {
$("#btn").click(function () {
var json = {"id": "1", "username": "科比", "password": "123", "age": "12"};
var stringJson = JSON.stringify(json);
$.ajax({
method: "POST",
url: "${pageContext.request.contextPath}/response/json",
contentType: "application/json; charset=UTF-8",
data: stringJson,
success: function (data) {
alert(data);
}
});
});
})
</script>
<body>
<input type="button" value="測試Ajax 請求json 和響應 json" id="btn">
</body>
</html>
java 代碼
package cn.lemon.controller;
import cn.lemon.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import java.io.PrintWriter;
@Controller
@RequestMapping("/response")
public class ResponseController {
@RequestMapping("/json")
public @ResponseBody User json(@RequestBody User user, PrintWriter printWriter){
System.out.println("異步請求 User,user = " + user);
printWriter.print("ajax success");
return null;
}
}
把 User 對象反序列化爲 json 對象,代碼爲:
jsp 代碼
<a href="${pageContext.request.contextPath}/response/user">點擊跳轉</a>
java 代碼
@RequestMapping("/user")
public @ResponseBody User testUser(){
User user = new User();
user.setId(2);
user.setUsername("詹姆斯");
user.setPassword("123");
user.setAge(13);
return user;
}
運行顯示: