Home > Mobile >  How to send Basic HTML Form data to Spring Boot controller?
How to send Basic HTML Form data to Spring Boot controller?

Time:08-28

How to send HTML Form request i.e; value of 'input' to @PostMapping in controller without creating any POJO class or jsp?

<body>
    <form method="post" id="form">
        <input type ="text"/>
    </form>
    
    <button type="button" id="button2" >Submit2</button>
    <script src="script2.js"></script>
</body>

Script2.js

var select = document.getElementById('form');

document.getElementById("button2").onclick = function(){
    var value = select.value
    window.location.href = "/posting";
};

MyController.java

@PostMapping(value="/posting")
    public String po() {
        return "hello";
    }

CodePudding user response:

Specify the name for your input element:

<body>
  <form method="post" id="form">
    <input type ="text" name="someName"/>
  </form>

  <button type="button" id="button2" >Submit2</button>
  <script src="script2.js"></script>
</body>

In your script create HTTPRequest and send data:

var select = document.getElementById('form');
    
document.getElementById("button2").onclick = function(){
  var data = new FormData(select);

  var req = new XMLHttpRequest();
  req.open("POST", "/posting");
  req.send(data);
};

You may also want to send JSON data. Convert data to JSON and send json variable

var object = {};
data.forEach(function(value, key){
   object[key] = value;
});
var json = JSON.stringify(object);
req.send(json);

And in java controller you have to specify that the method parameter is a request body. Something like this:

@PostMapping("/posting")
public String po(@RequestBody String someName) {
    return "hello"   someName;
}

Check if controller class has @RequestMapping("/") annotation

CodePudding user response:

you can use @RequestParam see RequestParam in Spring

add action attribute to form and make button in form (not needed js file because send direct by form):

<body>
  <form action="/posting" method="post" id="form">
    <input type ="text" name="someName"/>
    <button type="submit" id="button2" >Submit2</button>
  </form>
</body>

and change in controller :

@PostMapping("/posting")
public String po(@RequestParam("someName") String someName) {
   return "hello"   someName;
}

but if need use js file you can use XMLHttpRequest see XMLHttpRequest api or ajax see jQuery.ajax or fetch fetch api

  • Related