Vue中axios發送GET, POST, DELETE, PUT四種異步請求,參數攜帶和接收問題
web.xml配置如下
<!-- 注冊SpringMVC的前端控制器DispatcherServlet --> <servlet> <servlet-name>springMVC</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:springmvc.xml</param-value> </init-param> <!-- 將DispatcherServlet設置為隨Web應用一起啟動 --> <load-on-startup>1</load-on-startup> </servlet> <!--過濾所有的.do請求--> <servlet-mapping> <servlet-name>springMVC</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--配置請求方式過濾器,HiddenHttpMethodFilter可將_method = POST請求方式轉化為PUT,DELETE,PATCH三種中的一種,使用hidden標簽提交同步請求使用, axios異步請求直接指定方式即可--> <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>
1、GET請求
發送GET請求:
<!--params是關鍵字,說明所攜帶的參數,json格式參數--> axios.get('/edit.do', {params: {id: value}}) .then((response) => { //TODO })
Controller接收GET請求:
@GetMapping("/edit") public Result edit(Integer id){ //TODO }
2、POST請求
發送POST請求:
var params = { currentPage: this.pagination.currentPage, //當前頁碼 pageSize: this.pagination.pageSize, //頁面大小 queryString: this.pagination.queryString //搜索條件 } <!--POST請求第二個參數,可直接攜帶json格式的參數--> axios.post('/findPage.do', params) .then(response => { //TODO })
Controller接收POST請求:
public class QueryPageBean implements Serializable { private Integer currentPage;//頁碼 private Integer pageSize;//每頁記錄數 private String queryString;//查詢條件 } @PostMapping("/findPage") public PageResult findPage(@RequestBody QueryPageBean queryPageBean){ //TODO }
3、DELETE請求
發送DELETE請求:
<!--DELETE請求第二個參數,可攜帶多個json格式的參數,但需要params作為json參數的關鍵字--> axios.delete('/delete.do', {params: {id: value}}) .then((response) => { //TODO })
Controller接收DELETE請求:
@DeleteMapping("/delete") public Result delete(Integer id){ //TODO }
4、PUT請求
發送PUT請求:
<!--PUT請求第二個參數,可直接攜帶json格式的參數--> axios.put('/update.do', {name:userName,age:userAge,address:userAddress}) .then((response) => { //TODO })
Controller接收PUT請求:
public class User implements Serializable { private String name; private Integer age; private String address; } @PutMapping("/update") public Result update(@RequestBody User user){ //TODO }