RESTful使用方法


1.什么是RESTful

 

 

 2.對應增刪改查

 

 

 注意:HTTP協議中並無PUT和DELETE的操作因此需在web.xml添加HiddenHttpMethodFilter用於識別PUT和DELETE操作

   原理是:從POST操作中額外分出PUT和DELETE操作

  <filter>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
  </filter>
  <filter-mapping>
    <filter-name>hiddenHttpMethodFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>
</web-app>

並且使用PUT操作和DELETE操作時需在jsp頁面添加隱藏的input標簽,以表示PUT或DELETE

如使用刪除操作:

                            <form action="${pageContext.request.contextPath}/delete/${course.id}" method="post">
                                <button class="btn btn-danger btn-sm delete_btn" type="submit">
                                    <input type="hidden" name="_method" value="DELETE"/>    <%-- 應添加此input標簽 --%>
                                    <span class="glyphicon glyphicon-trash">刪除</span>
                                </button>
                            </form>

3.controller的定義:

package com.yzy.controller;


import com.yzy.dao.courseDao;
import com.yzy.entity.Course;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;

@Controller
public class courseController {

    @Resource(name = "courseDao")
    private courseDao courseDao;

    @PostMapping("/add")
    public String add(Course course){
        courseDao.add(course);
        return "redirect:/getAll";   //重定向回getAll
    }

    @GetMapping("/getAll")
    public ModelAndView getAll(){
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("courses",courseDao.getAll());
        modelAndView.setViewName("index");
        return modelAndView;
    }

    @GetMapping("/getById/{id}")
    public ModelAndView updateBefore(@PathVariable int id){     //id從路徑中的{id}獲取
        ModelAndView modelAndView=new ModelAndView();
        modelAndView.addObject("course",courseDao.getById(id));
        modelAndView.setViewName("edit");
        return modelAndView;
    }

    @PutMapping("/update")
    public String update(Course course){
        courseDao.update(course);
        return "redirect:/getAll";
    }

    @DeleteMapping("/delete/{id}")
    public String delete(@PathVariable int id){
        courseDao.delete(id);
        return "redirect:/getAll";
    }
}

 

 

 

HiddenHttpMethodFilter


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM