×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Java
Posted by: ture ture
Added: Apr 8, 2018 10:33 PM
Views: 3012
Tags: no tags
  1. Creating Controller Layer
  2. Create a UserController class under package springmvc_example.controller package and write the following code in it
  3.  
  4. package springmvc_example.controller;
  5.  
  6. import java.util.List;
  7.  
  8. import org.springframework.beans.factory.annotation.Autowired;
  9. import org.springframework.web.bind.annotation.PathVariable;
  10. import org.springframework.web.bind.annotation.RequestBody;
  11. import org.springframework.web.bind.annotation.RequestMapping;
  12. import org.springframework.web.bind.annotation.RequestMethod;
  13. import org.springframework.web.bind.annotation.ResponseBody;
  14. import org.springframework.web.bind.annotation.RestController;
  15.  
  16. import springmvc_example.model.User;
  17. import springmvc_example.service.UserService;
  18.  
  19. @RestController
  20. public class UserController {
  21.  
  22.  @Autowired
  23.  UserService userService;
  24.  
  25.  @RequestMapping(value="/user/", method=RequestMethod.GET, headers="Accept=application/json")
  26.  public @ResponseBody List getListUser(){
  27.   List users = userService.getListUser();
  28.  
  29.   return users;
  30.  }
  31.  
  32.  @RequestMapping(value="/add/", method=RequestMethod.POST)
  33.  public @ResponseBody User add(@RequestBody User user){
  34.   userService.saveOrUpdate(user);
  35.  
  36.   return user;
  37.  }
  38.  
  39.  @RequestMapping(value="/update/{id}", method=RequestMethod.PUT)
  40.  public @ResponseBody User update(@PathVariable("id") int id, @RequestBody User user){
  41.   user.setId(id);
  42.   userService.saveOrUpdate(user);
  43.  
  44.   return user;
  45.  }
  46.  
  47.  @RequestMapping(value="/delete/{id}", method=RequestMethod.DELETE)
  48.  public @ResponseBody User delete(@PathVariable("id") int id){
  49.   User user = userService.findUserById(id);
  50.   userService.deleteUser(id);
  51.  
  52.   return user;
  53.  }
  54.  
  55. }