Search code examples
springargs

Args with Spring MVC


I need help to pars args in a method inside my controller.

i have a form for sending my parameter to function

    <form method="post" action="/">
<input type="text" id="query" placeholder="file to search ...">
<input type="submit" id="submit" value="fetch!">
    </form>

and in my controller :

@RestController
public class mainController {

    @RequestMapping(value = "/index", method = RequestMethod.POST)
    public String index(Model model) throws IOException, GeneralSecurityException {
        DriveQuickstart drive = new DriveQuickstart("c:/temp/credentials.json");
        model.addAttribute("query");
        String res = drive.checkFile("query");

        return res;

the query is a string send via the form. and return res in the same view. Do you have any tips?

thanks you very mutch


Solution

  • In Spring MVC It will be like this:

    @Controller
    public class mainController {
    
    @PostMapping( "/index")
    public String index(@ModelAttribute FormDataObjectClass object) throws IOException, GeneralSecurityException {
        DriveQuickstart drive = new DriveQuickstart("c:/temp/credentials.json");
    
        //model.addAttribute("query");
        String name = object.getName();
        String address = object.getAddress();
        String res = drive.checkFile("query");
    
        return res;
    }
    

    Here no need of passing Model as argument as we need a custom Object(FormDataObjectClass) to be used. Create a class FormDataObjectClass as per you data in HTML form/JQuery post method