一 返回值分类
1. 字符串
2. void
3. ModelAndView
二 返回值类型为字符串
controller 方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。
案例:
1. index.jsp
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="user/testString">测试字符串类型的返回值</a>
</body>
</html>
2. UserController
package cn.itcast.controller;
import cn.itcast.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 {
@RequestMapping("/testString")
public String testString(Model model){
System.out.println("进入testString了...");
//模拟从数据库中查询数据,即查询出一个user对象
User user=new User();
user.setUsername("tom");
user.setPassword("123");
user.setAge(18);
model.addAttribute("user",user);
return "success";
}
}
3. success.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h3>执行成功...</h3>
<%--requestScope.可以省略--%>
${requestScope.user.username}
${requestScope.user.password}
${user.age}
</body>
</html>
执行结果
三 返回值类型为void
1. 如果返回值类型为void,那么是有一个默认的返回路径的
1) index1.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<a href="user/testVoid">测试void类型的返回值</a>
</body>
</html>
2) UserController
package cn.itcast.controller;
import cn.itcast.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 {
@RequestMapping("/testVoid")
public void testVoid(){
System.out.println("进入testVoid了...");
}
}
结果:从图中,我们可以看出,如果返回值类型为void,则默认跳转的路径为http://localhos