package com.bee.sample.smartmap.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.servlet.ModelAndView; import com.bee.sample.ch3.entity.User; import com.bee.sample.ch3.service.UserService; @Controller @RequestMapping("/model") public class ModelAndViewController { @Autowired UserService userService; /** * A beetl template test. Because the view extension name is btl * @param userId * @param model * @return */ @GetMapping(path = "/{userId}/get.html") public String getUser(@PathVariable Long userId,Model model) { User userInfo = userService.getUserById(userId); // model.addAttribute(userInfo); does the same as the following line, but there are potential problems model.addAttribute("user" , userInfo); return "/userInfo.html" ; } /** * Use freemaker template test, freemaker will look for /userInfo.ftl template * @param userId * @param view * @return */ @GetMapping(path = "/{userId}/get2.html") public ModelAndView getUser2(@PathVariable Long userId,ModelAndView view) { User userInfo = userService.getUserById(userId); //model.addAttribute(userInfo); view.addObject("user", userInfo); view.setViewName("/userInfo"); return view; } }
package com.bee.sample.smartmap.controller; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.ModelAttribute; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.PostMapping; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.ResponseBody; import com.bee.sample.ch3.controller.form.OrderPostForm; import com.bee.sample.ch3.service.UserService; @Controller @RequestMapping("/modelattribute") public class ModelAttributeController { @Autowired UserService userService; /** * Public in the Controller method, call this method before calling the method. * @param id * @param model */ @ModelAttribute public void findUserById (athPathVariable Long id, Model model) model.addAttribute("user", userService.getUserById(id)); } @GetMapping(path = "/{id}/get.json") @ResponseBody public String getUser(Model model) { System.out.println(model.containsAttribute("user")); return "success"; } }