SpringMVC响应数据类型可以是String类型,void类型,ModelAndView类型,并且可以通过使用forward和redirect进行页面条状来响应。
控制器类:
package com.heima.controller;
import com.heima.domain.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
@Controller
@RequestMapping("/user")
public class UserController {
/**
* 响应返回值是String
* @param model
* @return
*/
@RequestMapping("/testString")
public String testString(Model model){
User user = new User();
user.setUsername( "小太阳" );
user.setPassword( "123" );
user.setAge( 12 );
System.out.println("哈哈哈哈,劳资执行啦");
model.addAttribute( "user",user );
return "success";
}
/**
* 响应返回值是void
*/
@RequestMapping("/testVoid")
public void testVoid(HttpServletRequest request, HttpServletResponse response) throws Exception {
System.out.println("嘿嘿嘿嘿,劳资也执行啦");
//转发
//request.getRequestDispatcher( "/WEB-INF/pages/success.jsp" ).forward( request,response );
// 重定向
//response.sendRedirect(request.getContextPath()+"/index.jsp");
// 设置中文乱码
response.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=UTF-8");
// 直接会进行响应
response.getWriter().print("你好");
return;
}
/**
* 响应返回值是ModelAndView
* @return
*/
@RequestMapping("/findAll")
public ModelAndView findAll(){
ModelAndView mv = new ModelAndView();
// 跳转到list.jsp的页面
mv.setViewName("success");
// 模拟从数据库中查询所有的用户信息
User user = new User();
user.setUsername("赵四");
user.setPassword("456");
// 添加对象
mv.addObject("user", user);
return mv;
}
/**
* 使用关键字的方式进行转发或者重定向
* @return
*/
@RequestMapping("/testForwardOrRedirect")
public String testForwardOrRedirect(){
System.out.println("testForwardOrRedirect方法执行了...");
// 请求的转发
// return "forward:/WEB-INF/pages/success.jsp";
// 重定向
return "redirect:/index.jsp";
}
}
测试jsp:
<%--
Created by IntelliJ IDEA.
User: FANG2
Date: 2018/10/30
Time: 11:03
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery.min.js"></script>
</head>
<body>
<a href="user/testString">testString</a>
<br>
<a href="user/testVoid">testVoid</a>
<br>
<a href="user/findAll">testModelAndView</a>
<br>
<a href="user/testForwardOrRedirect">testForwardOrRedirect</a>
</body>
</html>