简体   繁体   中英

How can I send form values from jsp file to controller in Spring, JSP?

I'm trying to design a web page allows users to make comments on eachothers' profiles. To do this, the logged in user clicks the name of another user and see his/her detailed profile page and can make comment on that page. So the Comment table has two foreign key columns as commentator_id and owner_id . When a user makes a comment on another user's profile, the comment table will keep the both users' id and the text, title of comment and so on.

Here's my Controller :

 @RequestMapping(value = "/comment", method = RequestMethod.GET)
    public ModelAndView comment(Principal principal, String username, @ModelAttribute Comment c) {

        ModelAndView result = new ModelAndView("result");

        User user = userService.findByUsername(username); // the user who gets the comment

        String username2 = (String) ((Authentication) principal).getPrincipal(); //logged in user who makes the comment
        User authenticatedUser = userService.findByUsername(username2);


        c.setCommentator(authenticatedUser);;
        c.setOwner(user);


        user.getComments().add(c);

        userService.save(host);

        String message = "Com was successfully added.";
        result.addObject("message", message);
        return result;

    }

My jsp file :

<body>
  <form method="post" action="comment">
            <center>
            <table border="1" width="30%" cellpadding="5">
                <thead>
                    <tr>
                        <th colspan="2">Leave a referance</th>
                    </tr>
                </thead>
                <tbody>
                <tr>
                        <td>Title</td>
                        <td><input type="text" name="title" value="" /></td>
                    </tr>
                    <tr>
                        <td>Text</td>
                        <td><input type="text" name="message" value="" /></td>
                    </tr>

       // ...

                </tbody>
            </table>
            </center>
             <a href="<c:url value="/comment"><c:param name="username" value="${user.getUsername()}"/></c:url>">Send</a>
                      </form>
</body>

With this way, a user can make comment on another user's profile but the Comment table only keeps the id of both user but not the text, title and other values which I get from the form. How can I also keep form values in the db?

use ModelAttribute annotation

   public ModelAndView getMessage(@ModelAttribute("s") Student s){
       ModelAndView model=new ModelAndView("Successpage");
     return model;
   }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM