SpringMVC-Restful风格

restful简介

rest: 表现层(视图view及控制层controller)资源状态转移

restful实现

具体说就是http协议里面,四个表示操作方式的动词: GET POST PUT DELETE

它们分别对应四种基本操作: GET 用来表示获取资源, POST用来新建资源, PUT用来更新资源,DELETE 用来删除资源.

REST风格提倡URL地址使用统一的风格设计,从前到后各个单词使用斜杠分开,不使用问号键值对方式携带请求参数,而是将要发送给服务器的数据作为url地址的一部分,以保证整体风格的一致性.

restful实现 查询全部,根据id查询,添加

 @Controller
 public class UserController {
 ​
 ​
     /** 使用restful 模拟 用户资源的增删改查
      *     /user   GET    查询所有用户信息
      *     /user/1   GET  根据用户id查询用户信息
      *     /user   POST   添加用户信息
      *     /user/1 DELETE  根据id删除用户信息
      *     /user   PUT    修改用户信息
      */
       @RequestMapping(value="/user",method = RequestMethod.GET)
       public String getAllUser(){
           System.out.println("查询所有用户信息");
           return "success";
       }
     @RequestMapping(value="/user/{id}",method = RequestMethod.GET)
     public String getUserById(){
         System.out.println("根据用户id查询用户信息");
         return "success";
     }
     @RequestMapping(value="/user",method = RequestMethod.POST)
     public String insertUser(String username,String pwd){
         System.out.println("添加用户信息");
         System.out.println(username+"----"+pwd);
         return "success";
     }
 ​
 }

在test_rest.html中

 
查询所有用户信息
 根据id查询用户信息
 
  用户名
  密码
     

在springmvc配置文件

 

     
   如果 实体类中 存在 Date 属性 ,则 需要再 属性上增加 @DataTimeFormat(pattern="yyyy-MM-dd") 配合
    即可 将 jsp string 转为date

控制台输出结果

查询所有用户信息 16:05:49.088 [http-nio-8080-exec-6] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 200 OK 16:05:57.525 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.DispatcherServlet - GET "/user/1", parameters={} 16:05:57.525 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to ly.controller.UserController#getUserById() 根据用户id查询用户信息 16:05:57.527 [http-nio-8080-exec-5] DEBUG org.springframework.web.servlet.DispatcherServlet - Completed 200 OK 16:06:07.606 [http-nio-8080-exec-8] DEBUG org.springframework.web.servlet.DispatcherServlet - POST "/user", parameters={masked} 16:06:07.607 [http-nio-8080-exec-8] DEBUG org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping - Mapped to ly.controller.UserController#insertUser(String, String) 添加用户信息 123----123333

HiddenHttpMethodFilter

由于浏览器只 支持get 和post 方式的请求,那么该 如何发送 put和delete 请求呢?

springmvc提供了HiddenHttpMethodFilter 帮助我们将post 请求转换为delete或put 请求

HiddenHttpMethodFilter 处理

再web.xml 中增加

 

  
      HiddenHttpMethodFilter
      org.springframework.web.filter.HiddenHttpMethodFilter
  
 
     HiddenHttpMethodFilter
     /*
 

修改html页面 ,为form 添加 隐藏域,name 必须为 _method,值 为put或PUT

 
          用户名
    密码
       
 
@RequestMapping(value="/user",method = RequestMethod.PUT)
 public String updateUser(String username,String pwd){
     System.out.println("修改用户信息");
     System.out.println(username+"----"+pwd);
     return "success";
 }

执行结果:

修改用户信息 opuuu----123

web.xml过滤器顺序问题

此时再web.xml 里面配置了 两个过滤器,一定要先执行编码过滤器,再执行HiddenHttpMethodFilter,

 
 
     CharacterEncodingFilter
     org.springframework.web.filter.CharacterEncodingFilter
     
         encoding
         UTF-8
     
     
         forceResponseEncoding
         true
     
 ​
 
 ​
 
     CharacterEncodingFilter
     /*
 
 
 
     HiddenHttpMethodFilter
     org.springframework.web.filter.HiddenHttpMethodFilter
 
 
     HiddenHttpMethodFilter
     /*
 

因为再HiddenHttpMethodFilter 获取了 请求参数 _method, 否则会出现乱码问题

RESTFul 案例

和传统的CRUD一样,实现对员工信息的增删改查

web.xml 配置

 

 
     CharacterEncodingFilter
     org.springframework.web.filter.CharacterEncodingFilter
     
         encoding
         UTF-8
     
     
         forceResponseEncoding
         true
     
 ​
 
 ​
 
     CharacterEncodingFilter
     /*
 
 
 
     HiddenHttpMethodFilter
     org.springframework.web.filter.HiddenHttpMethodFilter
 
 
     HiddenHttpMethodFilter
     /*
 
 
 
     springmvc
     org.springframework.web.servlet.DispatcherServlet
     
     
         contextConfigLocation
         classpath:springmvc.xml
     
     
     1
 
 
     springmvc
     
     /
 

springmvc.xml

 
 
    
     
     
     
         
         
         
             
                 
                     
 ​
                         
                         
                         
                         
                     
                 
             
         
     
 ​
 
     
 package ly.entity
 public class Emp {
     //属性 get/set 构造器全参及无参
     private Integer id;
     private String lastName;
     private String email;
     private Integer gender;
     }
 package ly.dao;
 ​
 import ly.entity.Emp;
 import org.springframework.stereotype.Repository;
 ​
 import java.util.Collection;
 import java.util.HashMap;
 import java.util.Map;
 ​
 // 没有链接数据库,使用Map 存储数据
 @Repository
 public class EmpDao {
 ​
     private static Map emps = null;
     static{
         emps = new HashMap<>();
         emps.put(1001,new Emp(1001,"aaa","[email protected]",1));
         emps.put(1002,new Emp(1002,"bbb","[email protected]",0));
         emps.put(1003,new Emp(1003,"ccc","[email protected]",1));
         emps.put(1004,new Emp(1004,"ddd","[email protected]",0));
     }
     private static Integer initId=1005;
     public void save(Emp emp){
         if(emp.getId() ==null){
             emp.setId(initId++);
         }
         emps.put(emp.getId(),emp);
     }
 ​
 ​
 ​
     public Collection getAll(){
         return emps.values();
     }
 ​
     public Emp get(Integer id){
         return emps.get(id);
     }
 ​
     public void delete(Integer id){
         emps.remove(id);
     }
 }

查询全部

编写EmpController.java

 @Controller
 public class EmpController {
     @Autowired
     private EmpDao empDao;
 ​
     @RequestMapping(value="/employee",method = RequestMethod.GET)  //可以使用@GetMapping("/employee")代替
     public String getAll(Model model){
        Collection emps =  empDao.getAll();
        model.addAttribute("emps",emps);
         return "emps_list";
     }
 }

编写emps_list.html

 

   
     
   
   
     
     
     
     
     
 ​
   
    
   
     
     
     
     
     
   
 ​
 
员工列表
idlastnameemailgenderoptions
       delete        update      

SpringMVC-Restful风格_第1张图片

删除员工

再web.xml 中配置 HiddenHttpMethodFilter 过滤器 , 她必须位于CharacterEncodingFilter过滤器的后面

编写 emps_list.html

 
   
     
   
   
     
     
     
     
     
 ​
   
 ​
   
      
     
     
     
     
   
 ​
 
员工列表
idlastnameemailgenderoptions
       delete 写法1        delete 写法2        update      
   
     ​  
 ​        ​  

这里需要访问 静态资源, 这里需要给springmvc.xml增加一个配置mvc:default-servlet-handler

   
 
     
     
     

编写 controller

 @Controller
 public class EmpController {
     @Autowired
     private EmpDao empDao;
 ​
     @RequestMapping(value="/employee",method = RequestMethod.GET)
     public String getAll(Model model){
        Collection emps =  empDao.getAll();
        model.addAttribute("emps",emps);
         return "emps_list";
     }
 ​
     @DeleteMapping(value="/employee/{id}")
     public String delById(@PathVariable("id")int id){
         empDao.delete(id);
         return "redirect:/employee"; //删除后 重定向到 列表页面,这里没有使用转发,转发在url地址栏不变
     }
 ​
 ​
 }
 ​

添加功能

再emps_list.html 添加

 add

因为 只是简单的页面跳转,不需要编写controller, 再springmvc.xml 中添加

 

emp_add.html

 
  lastname:
  email:
  gender: female    male
     
 EmpController.java
     
     
   
  @PostMapping("/employee")
     public String save(Emp emp){
         empDao.save(emp);
         return "redirect:/employee"; //添加后 返回列表页面
     }

实现修改(先回显 再修改)

再emps_list.html

  update 写法1
  update 写法2

再EmpController.java

 @GetMapping("/findById/{id}")
 public String findById(@PathVariable("id") int id,Model model) {
     Emp emp = empDao.get(id);
     model.addAttribute("emp", emp);
     return "emp_edit";
 }
 ​
     @PutMapping("/employee")
     public String update(Emp emp){
         empDao.save(emp);
         return "redirect:/employee";
     }

emp_edit.html ---注意 _method及id

 
              lastname:
  email:
  gender: female    male
     

注意使用 高版本的tomcat 处理 rest put 及 delete 需要再成功页面 增加

在DELETE和PUT后提交的jsp页面中加入isErrorPage=“true”

高版本的Tomcat的Rest不接受DELETE和PUT

 
                   
  • ${u.id}----${u.name}    编辑    删除  
  •      
     
 添加用户  ​  ​    
       
 ​  

你可能感兴趣的:(springmvc,restful,后端,spring)