返回值是String、void、ModelAndView類型
/**
* 返回值是字符串類型
*
* @param model
* @return
*/
@RequestMapping("/testString")
public String testString(Model model) {
System.out.println("testString方法執行了");
User user = new User();
user.setUsername("張三");
user.setPassword("123456");
user.setAge(20);
model.addAttribute("user", user);
//指定邏輯視圖的名稱,根據視圖解析器爲物理視圖的地址
//跳轉到某個頁面
return "success";
}
/**
* 返回值是void
* 如果控制器的方法返回值編寫成void,執行程序報404的異常,默認查找JSP頁面沒有找到
* 默認會跳轉到@RequestMapping(value="/initUpdate") initUpdate的頁面
*
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("testVoid方法執行了");
//1.轉發
//request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
//2.重定向
//response.sendRedirect(request.getContextPath() + "/index.jsp");
//解決中文亂碼
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//直接進行響應
response.getWriter().write("你好");
return;
}
/**
* 返回值是ModelAndView
* ModelAndView對象是Spring提供的一個對象,可以用來調整具體的JSP視圖
*
* @return
*/
@RequestMapping("/testModelAndView")
public ModelAndView testModelAndView() {
//創建ModelAndView對象
ModelAndView mv = new ModelAndView();
User user = new User();
user.setUsername("李四");
user.setPassword("123456");
user.setAge(20);
System.out.println("testModelAndView方法執行了");
//將User對象存入mv,User對象會同時存入request對象中
mv.addObject("user", user);
//設置跳轉到哪個頁面
mv.setViewName("success");
return mv;
}
/**
* 返回值中使用關鍵字進行轉發或重定向
*
* @return
*/
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect() {
//使用關鍵字進行轉發和重定向的時候不能再使用視圖解析器對象,需自己補全路徑
//轉發
//return "forward:/WEB-INF/pages/success.jsp";
//重定向
return "redirect:/index.jsp";
}
響應JSON數據
jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
<script>
$(function () {
$("#btn").click(function () {
$.ajax({
url: "user/testAjax",
contentType: "application/json;charset=utf-8",
data: '{"username":"張三","password":"123456","age":30}',
dataType: "json",
type: "post",
async: true,
success: function (data) {
alert("響應的姓名:" + data.username)
}
});
});
});
</script>
</head>
<body>
<button id="btn">ajax異步請求</button>
</body>
</html>
Controller
@RequestMapping("/testAjax")
public @ResponseBody
User testAjax(@RequestBody User user) {
//客戶端發送ajax請求,將json字符串封裝到User中
System.out.println(user);
//返回一個新的User
user.setUsername("lisi");
user.setPassword("abcd");
user.setAge(12);
return user;
}