一、页面跳转
1.直接返回字符串
2.返回ModelAndView
@Controller
@RequestMapping("/user")
public class UserController {
//页面跳转,返回字符串
@RequestMapping("/method1")
public String method1(){
return "success";
}
//页面跳转,返回ModelAndView
@RequestMapping("/method2")
public ModelAndView method2(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("success");
return modelAndView;
}
//页面跳转,返回ModelAndView
@RequestMapping("/method3")
public ModelAndView method3(ModelAndView modelAndView){
modelAndView.setViewName("success");
return modelAndView;
}
}
二、回写数据(需要加上@ResponseBody注解,否则会被当成页面跳转)
1.直接返回字符串
2.返回对象或集合(SpringMVC会把对象转换成json格式字符串)
2.1导入依赖
<dependencies>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.11.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.11.4</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-annotations</artifactId>
<version>2.11.4</version>
</dependency>
</dependencies>
2.2配置MVC驱动(含有json转换器)
<!--mvc注解驱动-->
<mvc:annotation-driven></mvc:annotation-driven>
@Controller
@RequestMapping("/user")
public class UserController {
//回写数据,返回字符串
@RequestMapping("/method1")
@ResponseBody
public String method1(){
return "success";
}
//回写数据,返回对象
@RequestMapping("/method2")
@ResponseBody
public User method2(){
User user = new User();
user.setId(1);
user.setName("1");
return user;
}
//回写数据,返回集合
@RequestMapping("/method3")
@ResponseBody
public List<User> method3(){
List<User> userList = new ArrayList<>();
User user1 = new User();
user1.setId(1);
user1.setName("1");
User user2 = new User();
user2.setId(2);
user2.setName("2");
userList.add(user1);
userList.add(user2);
return userList;
}
}