[spring] Passing parameters from jsp to Spring Controller method

I am working in a Spring MVC application which uses Hibernate.

In the JSP page I have a function which lists the values stored in the database(currently all the value).

I have written a method, where the list is only limited to an ID passed in the JSP file. I got the HQL query working right, so I know it is retrieving data based upon the ID as a parameter.

Now, I would like to use this method in the controller. For that I have to pass a parameter of ID to the list, so in the controller side, the function is called which will retrieve list based upon that ID.

Unfortunately I don't know how to pass parameters from a JSP file.

JSP File :

  <c:url var="addAction" value="/note/add" ></c:url>
<form:form action="${addAction}" commandName="notices">
    <table>
        <c:if test="${!empty notices.notetext}">
            <tr>
                <td>
                    <form:label path="noticesid">
                        <spring:message text="noticesid"/>
                    </form:label>
                </td>
                <td>
                    <form:input path="noticesid" readonly="true" size="8"  disabled="true" />
                    <form:hidden path="noticesid" />
                </td>
            </tr>
        </c:if>
        <tr>
            <td>
                <form:label path="notetext">
                    <spring:message text="notetext"/>
                </form:label>
            </td>
            <td>
                <form:input path="notetext"  />
            </td>
        </tr>
        <tr>
            <td>
                <form:label path="notetag" >
                    <spring:message text="notetag"/>
                </form:label>
            </td>
            <td>
                <form:input path="notetag"/>
            </td>
        </tr>
        <tr>
            <td>
                <form:label path="notecolor">
                    <spring:message text="notecolor"/>
                </form:label>
            </td>
            <td>
                <form:input path="notecolor" />
            </td>
        </tr>

        <tr>
            <td>
                <form:label path="canvasid">
                    <spring:message text="canvasid"/>
                </form:label>
            </td>
            <td>
                <form:input path="canvasid" />
            </td>
        </tr>

        <tr>
            <td>
                <form:label path="sectionid">
                    <spring:message text="sectionid"/>
                </form:label>
            </td>
            <td>
                <form:input path="sectionid"  />
            </td>
        </tr>

        <tr>
            <td>
                <form:label path="canvasnName">
                    <spring:message text="canvasnName"/>
                </form:label>
            </td>
            <td>
                <form:input path="canvasnName"  />
            </td>
        </tr>


        <tr>
            <td colspan="2">
                <c:if test="${!empty notices.noticesid}">
                    <input type="submit"
                           value="<spring:message text="Edit note"/>" />
                </c:if>
                <c:if test="${empty notices.notetext}">
                    <input type="submit"
                           value="<spring:message text="Add note"/>" />
                </c:if>
            </td>
        </tr>
    </table>
</form:form>
<br>
<h3>Notes List</h3>

<c:url var="listAction" value="/note/list/2323" ></c:url>
<c:if test="${!empty notices.noticesid}">
    <table class="tg">
        <tr>
            <th width="80">Notes ID</th>
            <th width="120">Notes text</th>
            <th width="120">Note Tag</th>
            <th width="120">Note color</th>
            <th width="120">Note section</th>
            <th width="120">Canvas id</th>
            <th width="120">Canvas name</th>
            <th width="120">Other id</th>
            <th width="60">Edit</th>
            <th width="60">Delete</th>
        </tr>
        <c:forEach items="${listNotes}" var="notices">
            <tr>
                <td>${notices.noticesid}</td>
                <td>${notices.notetext}</td>
                <td>${notices.notetag}</td>
                <td>${notices.notecolor}</td>
                <td>${notices.sectionid}</td>
                <td>${notices.canvasid}</td>
                <td>${notices.canvasnName}</td>
                <td>${notices.personid}</td>
                <td><a href="<c:url value='/editnote/${notices.noticesid}' />" >Edit</a></td>
                <td><a href="<c:url value='/removenote/${notices.noticesid}' />" >Delete</a></td>
            </tr>
        </c:forEach>
    </table>
</c:if>

Controller file with list function :

@RequestMapping(value = "/note/list/{id}", method=RequestMethod.GET)
    public String listNotes(@PathVariable int id,Model model) {
        Person person = personService.getCurrentlyAuthenticatedUser();
        this.setSectionid(id);
        model.addAttribute("person", new Person());
        model.addAttribute("listPersons", this.personService.listPersons());
       model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
        return "note";
    }

@RequestMapping(value= "/note/add")
    public String addNote(@ModelAttribute("notices") Notes p,Model model) {
        Person person = personService.getCurrentlyAuthenticatedUser();
        model.addAttribute("listNotes",this.notesService.listNotes());

        int id = getSectionid();
        System.out.println("Section id is"+id);
         model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
        this.notesService.addNote(p, person);
        return "note";
    }

I tried looking up the net, but I don't know what it is called that I am looking for, so having a hard time. Any help would be good. Thank you.

This question is related to spring jsp spring-mvc

The answer is


Your controller method should be like this:

@RequestMapping(value = " /<your mapping>/{id}", method=RequestMethod.GET)
public String listNotes(@PathVariable("id")int id,Model model) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    int id = 2323;  // Currently passing static values for testing
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes",this.notesService.listNotesBySectionId(id,person));
    return "note";
}

Use the id in your code, call the controller method from your JSP as:

/{your mapping}/{your id}

UPDATE:

Change your jsp code to:

<c:forEach items="${listNotes}" var="notices" varStatus="status">
    <tr>
        <td>${notices.noticesid}</td>
        <td>${notices.notetext}</td>
        <td>${notices.notetag}</td>
        <td>${notices.notecolor}</td>
        <td>${notices.sectionid}</td>
        <td>${notices.canvasid}</td>
        <td>${notices.canvasnName}</td>
        <td>${notices.personid}</td>
        <td><a href="<c:url value='/editnote/${listNotes[status.index].noticesid}' />" >Edit</a></td>
        <td><a href="<c:url value='/removenote/${listNotes[status.index].noticesid}' />" >Delete</a></td>
    </tr>
</c:forEach>

Use the @RequestParam to pass a parameter to the controller handler method. In the jsp your form should have an input field with name = "id" like the following:

<input type="text" name="id" />
<input type="submit" />

Then in your controller, your handler method should be like the following:

@RequestMapping("listNotes")
public String listNotes(@RequestParam("id") int id) {
    Person person = personService.getCurrentlyAuthenticatedUser();
    model.addAttribute("person", new Person());
    model.addAttribute("listPersons", this.personService.listPersons());
    model.addAttribute("listNotes", this.notesService.listNotesBySectionId(id, person));
    return "note";
}

Please also refer to these answers and tutorial:


Examples related to spring

Are all Spring Framework Java Configuration injection examples buggy? Two Page Login with Spring Security 3.2.x Access blocked by CORS policy: Response to preflight request doesn't pass access control check Failed to configure a DataSource: 'url' attribute is not specified and no embedded datasource could be configured ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Failed to auto-configure a DataSource: 'spring.datasource.url' is not specified Spring Data JPA findOne() change to Optional how to use this? After Spring Boot 2.0 migration: jdbcUrl is required with driverClassName The type WebMvcConfigurerAdapter is deprecated No converter found capable of converting from type to type

Examples related to jsp

Difference between request.getSession() and request.getSession(true) A child container failed during start java.util.concurrent.ExecutionException The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path Using if-else in JSP Passing parameters from jsp to Spring Controller method how to fix Cannot call sendRedirect() after the response has been committed? How to include js and CSS in JSP with spring MVC How to create an alert message in jsp page after submit process is complete getting error HTTP Status 405 - HTTP method GET is not supported by this URL but not used `get` ever? How to pass the values from one jsp page to another jsp without submit button?

Examples related to spring-mvc

Two Page Login with Spring Security 3.2.x ApplicationContextException: Unable to start ServletWebServerApplicationContext due to missing ServletWebServerFactory bean Spring 5.0.3 RequestRejectedException: The request was rejected because the URL was not normalized The type WebMvcConfigurerAdapter is deprecated RestClientException: Could not extract response. no suitable HttpMessageConverter found Spring boot: Unable to start embedded Tomcat servlet container UnsatisfiedDependencyException: Error creating bean with name 8080 port already taken issue when trying to redeploy project from Spring Tool Suite IDE Error creating bean with name 'entityManagerFactory' defined in class path resource : Invocation of init method failed Difference between the annotations @GetMapping and @RequestMapping(method = RequestMethod.GET)