1. 程式人生 > 其它 >Restful風格路徑程式碼編寫

Restful風格路徑程式碼編寫

常規路徑get提交

前端頁面

<%--
  Created by IntelliJ IDEA.
  User: wsh
  Date: 2022/5/31
  Time: 9:08
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</
head> <body> <form action="/spring_mvc02_war_exploded/add" method="get"> <input type="text" name="a"> <br/> <input type="text" name="b"> <br/> <input type="submit"> </form> </body> </html>

瀏覽器傳遞地址

controller後端處理程式碼

 @GetMapping("/add")
    public String test2( String a,String b,Model model){
        String res=a+b;
        model.addAttribute("msg","結果為:"+res);

        return "hello";
    }

注意:springMVC的Controller類裡面Mapping對映下所有方法裡的引數都可匹配瀏覽器地址傳遞的引數

用Restful方式傳遞引數,可在需要傳遞的引數前加

@PathVariable
註解

可用

@RequestMapping

不同的延申註解接收相同地址的不同提交方式的資料

如下

post提交頁面

<%--
  Created by IntelliJ IDEA.
  User: wsh
  Date: 2022/5/31
  Time: 9:45
  To change this template use File | Settings | File Templates.
--%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> </head> <body> <form action="/spring_mvc02_war_exploded/add/2/3" method="post"> <input type="submit"> </form> </body> </html>

/2/3為restful傳輸方式的資料用url傳遞

後端Controller類程式碼:

@Controller
public class restfulController {
    @RequestMapping(value = "/add/{a}/{b}",method = {RequestMethod.POST})
    public String test(@PathVariable int a, @PathVariable int b, Model model){
        model.addAttribute("msg","結果為:"+a+b);

        return "hello";
    }

最後hello.jsp顯示頁面,補充

<%--
  Created by IntelliJ IDEA.
  User: wsh
  Date: 2022/5/30
  Time: 9:06
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
${msg}
</body>
</html>