我的UserController类:
package org.peronalitymeet.controller;
import org.peronalitymeet.entity.User;
import org.peronalitymeet.entity.request.AddUserRequest;
import org.peronalitymeet.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import java.util.List;
@RestController
public class UserController {
private UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@RequestMapping(value="/users", method = RequestMethod.GET)
public List<User> findAllUsers(){
return userRepository.findAll();
}
@RequestMapping(value="/signup", method = RequestMethod.POST)
public void addUser(@RequestBody AddUserRequest addUserRequest){
User user = new User();
user.setFirstname(addUserRequest.getFirstname());
user.setSurname(addUserRequest.getSurname());
userRepository.save(user);
}
}
我的问题是,现在如果我打开localhost:8080 / users URL, 我将以JSON格式获得所有用户。以前我按照Spring mvc教程,在那里他们使用ModelAndView方法在调用URL时自动打开jsp页面。
有没有办法使用FindAll Users()并同时打开一个jsp或html页面并列出该方法的结果?
答案 0 :(得分:1)
@RestController
是一个元注释,它告诉Spring返回它按原样返回给用户的文本。这相当于向您的班级添加@ResponseBody @Controller
。
如果你想用JSP做一些事情,你的类应该看起来像我下面的内容。我只是在改变/users
端点,但这个想法无处不在。
package org.peronalitymeet.controller;
import org.peronalitymeet.entity.User;
import org.peronalitymeet.entity.request.AddUserRequest;
import org.peronalitymeet.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.Controller;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import java.util.List;
@Controller
public class UserController {
private UserRepository userRepository;
@Autowired
public UserController(UserRepository userRepository) {
this.userRepository = userRepository;
}
@RequestMapping(value="/users", method = RequestMethod.GET)
public ModelAndView findAllUsers(ModelAndView mav){
List<User> users = userRepository.findAll();
mav.addObject("users", users);
mav.setViewName("users");
return mav;
}
@ResponseBody
@RequestMapping(value="/signup", method = RequestMethod.POST)
public void addUser(@RequestBody AddUserRequest addUserRequest){
User user = new User();
user.setFirstname(addUserRequest.getFirstname());
user.setSurname(addUserRequest.getSurname());
userRepository.save(user);
}
}
然后设置名为users.jsp
的视图页面以显示users
变量中的项目,您应该进行设置。