spring前后端分離,前端傳值三種方式


1.建立HelloController類

之前的工作請看https://www.cnblogs.com/zc-blog-com/p/13356910.html

@RestController
public class HelloController {

//    @ResponseBody//將方法的返回值以json字符串的形式進行返回

    @RequestMapping("/hello.do")
    public String action() {
        System.out.println(123);
        return "null";
    }
}
View Code

 

 

在webapp下建一個hello.html文件

 

 2.hello.html文件中寫一個表單

<body>
<form action="/hello.do" method="get">
    姓名:<input type="text" name="username">
    密碼:<input type="password" name="password">
    <input type="submit" value="提交">
</form>
</body>

下面是第一種方法傳值:

使用servlet方法

導入servlet依賴

<dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.5</version>
    </dependency>
View Code

修改HelloController類里面的內容

@RestController
public class HelloController {

//    @ResponseBody//將方法的返回值以json字符串的形式進行返回

    @RequestMapping("hello.do")
    public String action(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        System.out.println(username+ " "+password);
        return null;
    }
}

username和password要和HTML里面的名字一樣

 

 

運行項目,輸入信息,可以在控制台看到輸入的信息

 

 

2.通過反射,匹配參數名來注入值,用的比較多一種方法

參數比較少時

修改HelloController類里面的內容

@RequestMapping("hello1.do")
    //通過反射,匹配參數名來注入值
    //java反射機制本身會注入失敗,使用@RequestParam來解決。當有多個參數時,發現某個參數接收不到,可以試試這個注解
    public String action1(@RequestParam ("username")String username, String password) {
        System.out.println(username+ " "+password);
        return null;
    }
}

修改HTML內容

 

<form action="/hello1.do" method="get">
    姓名:<input type="text" name="username">
    密碼:<input type="password" name="password">
    <input type="submit" value="提交1">
</form>

運行項目,輸入信息,可以在控制台看到輸入的信息

3參數比較多時:

創建一個實體類User

 

 

引入lombok依賴

 <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <version>1.18.12</version>
    </dependency>

這時User就會自動生成set,get方法

修改HelloController類里面的內容

//針對參數比較多時
@RequestMapping("hello2.do")
//通過反射,匹配參數名來注入值
public String action2(User user) {
System.out.println(user);
return null;
}

修改HTML內容

<form action="/hello2.do" method="get">
    姓名:<input type="text" name="username">
    密碼:<input type="password" name="password">
    <input type="submit" value="提交2">
</form>

 運行項目,輸入信息,可以在控制台看到輸入的信息

 

 最后說一下怎么獲取多個值

 

 

那就結束了

加油哦


免責聲明!

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



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