SpringMVC之响应数据和结果视图
一、返回值类型
字符串(String)
controller 方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。
例如,我们再controller层 return "success";
,那么,当通过视图解析器的时候,
就会被解析为jsp 物理路径:/WEB-INF/pages/success.jsp
简单案例核心代码如下:
@Controller
@RequestMapping("/type")
public class ReturnType {
@RequestMapping("/testReturnString")
public String testReturnString(){
System.out.println("ReturnType 的 testReturnString 方法执行了!");
//返回字符串,由MVC框架最终会被解析为/WEB-INF/pages/success.jsp
return "success";
}
}
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="type/testReturnString">testReturnString</a>
</body>
</html>
success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<span id="address"></span>
<script type="text/javascript">
var url = document.location;
document.getElementById("address").innerHTML=url;
</script>
</body>
</html>
稍复杂的案例
@RequestMapping("/userReturnString")
public String userReturnString(Model model){
User user = new User();
user.setUsername("陈美嘉");
user.setAge(25);
user.setGender("female");
model.addAttribute("user", user);
System.out.println("ReturnType 的 testReturnString 方法执行了!");
return "success";
}
public class User {
private String username;
private String gender;
private Integer age;
//setter and getter
//toString
}
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="type/testReturnString">简单案例</a>
<hr>
<a href="type/userReturnString">稍复杂的案例</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<span id="address"></span>
<script type="text/javascript">
var url = document.location;
document.getElementById("address").innerHTML=url;
</script>
<br>
<input type="text" name="username" value="${user.username}"><br>
<input type="text" name="age" value="${user.age}"><br>
<input type="text" name="gender" value="${user.gender}"><br>
</body>
</html>
void类型
没有返回值,我们可以现运行一下,看看SpringMVC框架有没有给我们默认的视图页面。
代码如下:
@Controller
@RequestMapping("/typev")
public class ReturnTypeVoid {
@RequestMapping("/testReturnVoid")
public void testReturnVoid(){
System.out.println("typev的testReturnVoid方法执行了");
}
}
<a href="typev/testReturnVoid">返回void简单案例</a>
所以我们现在两种方法
第一种就是我们写一个默认的jsp页面
如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
我是testReturnVoid.jsp页面
</body>
</html>
另一种是通过HttpServletRequest和HttpServletResponse发送请求转发
@RequestMapping("/testReturnVoid")
public void testReturnVoid(HttpServletRequest request, HttpServletResponse response){
try {
System.out.println("typev的testReturnVoid方法执行了");
request.getRequestDispatcher("/WEB-INF/pages/success.jsp").forward(request, response);
} catch (ServletException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
<a href="typev/testReturnVoid">返回void简单案例</a>
@RequestMapping("/testReturnVoid")
public void testReturnVoid(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("typev的testReturnVoid方法执行了");
response.sendRedirect("userReturnString");
}
/**
*
* @param model
* @return
*/
@RequestMapping("/userReturnString")
public String userReturnString(Model model){
User user = new User();
user.setUsername("陈美嘉");
user.setAge(25);
user.setGender("female");
model.addAttribute("user", user);
System.out.println("ReturnType 的 testReturnString 方法执行了!");
return "success";
}
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="type/testReturnString">返回String简单案例</a>
<hr>
<a href="type/userReturnString">返回String稍复杂的案例</a>
<hr>
<a href="typev/testReturnVoid">返回void简单案例</a>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<span id="address"></span>
<script type="text/javascript">
var url = document.location;
document.getElementById("address").innerHTML=url;
</script>
<br>
<input type="text" name="username" value="${user.username}"><br>
<input type="text" name="age" value="${user.age}"><br>
<input type="text" name="gender" value="${user.gender}"><br>
</body>
</html>
@RequestMapping("/testReturnVoid")
public void testReturnVoid(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("typev的testReturnVoid方法执行了");
//response.sendRedirect("userReturnString");
response.sendRedirect(request.getContextPath()+"/response.jsp");
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
重定向
</body>
</html>
@RequestMapping("/testReturnVoid")
public void testReturnVoid(HttpServletRequest request, HttpServletResponse response) throws IOException {
System.out.println("typev的testReturnVoid方法执行了");
//response.sendRedirect("userReturnString");
//直接向页面写入数据
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html; charset=UTF-8");
response.getWriter().println("lol偷懒"); ;
}
ModelAndViwe类型
ModelAndView 是 SpringMVC 为我们提供的一个对象,该对象也可以用作控制器方法的返回值
示例如下:
@Controller
@RequestMapping("/model")
public class ReturnModelAndView {
@RequestMapping("/returnModelAndView")
public ModelAndView returnModelAndView(){
ModelAndView mv = new ModelAndView();
User user = new User();
user.setUsername("陈美嘉");
user.setAge(25);
user.setGender("female");
mv.addObject("user", user);
mv.setViewName("success");
return mv;
}
}
<a href="model/returnModelAndView">返回returnModelAndView简单案例</a>
二、转发和重定向
转发:forward
@Controller
@RequestMapping("/forwardandredirect")
public class ForwardAndRedirect {
@RequestMapping("/forward")
public String sendForward(){
System.out.println("sendForward方法执行了");
return "forward:/WEB-INF/pages/success.jsp";
}
}
重定向:Redirect
@Controller
@RequestMapping("/forwardandredirect")
public class ForwardAndRedirect {
@RequestMapping("/redirect")
public String sendRedirect(){
System.out.println("sendRedirect方法执行了");
return "redirect:returnModelAndView";
}
@RequestMapping("/returnModelAndView")
public ModelAndView returnModelAndView(){
ModelAndView mv = new ModelAndView();
User user = new User();
user.setUsername("陈美嘉");
user.setAge(25);
user.setGender("female");
mv.addObject("user", user);
mv.setViewName("success");
return mv;
}
}
三、ResponseBody 响应 json 数据
**作用:**该注解用于将 Controller 的方法返回的对象,通过 HttpMessageConverter 接口转换为指定格式的数据如:json,xml 等,通过 Response 响应给客户端。
既然通过Ajax等来返回,所以我们需要在项目中导入静态资源,所以我们就可以在springmvc.xml中进行配置静态资源的访问,因为我们前端控制器(DispatcherServlet或叫核心控制器),一般拦截所有的请求,所以我们需要配置,告诉前端控制器,那些资源我们不进行拦截。配置我呢见如下:
<!--告诉前端控制器,那些资源不拦截-->
<mvc:resources mapping="/js/" location="/js/**"/>
<mvc:resources mapping="/css/" location="/css/**"/>
下面我们来写一个小案例,来证明我们的配置是有效的
核心代码如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery.min.js"></script>
<!-- Jquery写法-->
<script type="text/javascript">
$(function () {
$("#btn").click(function () {
alert("hello");
});
});
</script>
<!--纯js写法-->
<script type="text/javascript">
window.onload=function () {
document.getElementById("btn").onclick=function () {
alert("hello");
}
}
</script>
</head>
<body>
<input id="btn" type="button" value="发送Ajax请求"/>
</body>
</html>
js函数可以正常执行
前端发送Ajax请求到后端,并在控制台输出
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery.min.js"></script>
<script>
// 页面加载,绑定单击事件
$(function(){
$("#btn").click(function(){
// alert("hello btn");
// 发送ajax请求
$.ajax({
// 编写json格式,设置属性和值
url:"test/testAjax",
contentType:"application/json;charset=UTF-8",
data:'{"username":"hehe","password":"123","age":30}',
dataType:"json",
type:"post",
success:function(data){}
});
});
});
</script>
</head>
<body>
<input id="btn" type="button" value="发送Ajax请求"/>
</body>
</html>
@Controller
@RequestMapping("/test")
public class TestAjax {
@RequestMapping("/testAjax")
public void testAjax(@RequestBody String user){
System.out.println("testAjax方法执行了...");
// 客户端发送ajax的请求,传的是json字符串,后端把json字符串封装到user对象中
System.out.println(user);
}
}
响应json数据格式
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
<script src="js/jquery.min.js"></script>
<!-- Jquery写法-->
<script type="text/javascript">
$(function () {
$("#btn_submit").click(function () {
var username =$("#username").val();
var age =$("#age").val();
var gender =$("#gender").val();
$.ajax({
type:"post",
url:"test/testAjax",
contentType:"application/json",
data:JSON.stringify({
username:username,
gender:gender,
age:age
}),
dataType:'json',
success:function (data) {
// data服务器端响应的json的数据,进行解析
alert(data);
alert(data.username);
alert(data.gender);
alert(data.age);
}
});
/*$.post("test/testAjax", JSON.stringify({username:username, gender:gender, age:age}), function (data) {
// data服务器端响应的json的数据,进行解析
alert(data);
alert(data.username);
alert(data.gender);
alert(data.age);
},"JSON");*/
});
});
</script>
</head>
<body>
<form id="ajaxdemo" method="post">
<input id="username" type="text" name="username" ><br>
<input id="age" type="text" name="age" ><br>
<input id="gender" type="text" name="gender"><br>
<input id="btn_submit" type="submit" value="提交">
</form>
</body>
</html>
@RequestMapping("/testAjax")
@ResponseBody
public User testAjax(@RequestBody User user){
System.out.println("testAjax方法执行了...");
// 客户端发送ajax的请求,传的是json字符串,后端把json字符串封装到user对象中
System.out.println(user);
//作响应,模拟查询数据库
user.setUsername("陈美嘉");
user.setGender("女");
user.setAge(30);
return user;
}