Search code examples
javaspring-bootmodelfreemarker

Extract data from HTML to controller without using model in JAVA - freemarker


<html>
    <head>
        <title>Report Preview</title>
    </head>
    <body>
        <div class="container">
            <h2>Patient Data</h2>
            <form action = "reportUpdate" method = "post" >
              <input  type="text" name="fvalue" value="testingData1"/>
              <input  type="text"  name="svalue" value="testingData2"/>
              <input  type="submit" value="Submit"/>
            </form>
        </div>
        <script type = "text/javascript" src = "main.js"></script>
    </body>
</html>

I have a SpringBootProject and I'm using the above Freemarker code template file(*.ftl). I tried to display some input field with the values(binded), after editing I want to extract the data from HTML input tags(fvalue,svalue) to controller without using any model. How to get the values?

My controller code:

@PostMapping({ "/reportUpdate"})
    public String reportToUpdate( ) {
        
        String firstName = ""; // I should get fvalue here
        String secondName = ""; // I should get svalue here
        
        //Some other logics which will use above value.
        
        return "Data saved!";
    }

Solution

  • By using HttpServletRequest request, HttpServletResponse response we can get the data from HTML form. Using the below code.

    public void getDataFromForm(HttpServletRequest request, HttpServletResponse response) throws ServletException{
                    
         // Get the values from the request using 'getParameter'
         String name = request.getParameter("name");
                    
    }
    

    For more info, you can see this.