user1067665
user1067665

Reputation: 495

How to send values from autocomplete search with jquery to a controller in spring mvc

I have have a search table with two autocomplete fields for searching user within the fields. The table and the autocomplete working great. But my question is how i can get the values from the search fields and with only one button save them in database? How can I get the values from the search?

Here are my codes :

autocomplete.jsp

 <%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"    import="java.util.*"%>
    ......
  </head>


  <script type='text/javascript'>
$().ready(function() {
    $('#search_input').focus()
});// focus search area
  </script>
  <script type='text/javascript'>
$().ready(function() {
    $('#blocked').focus()
});// focus search area
  </script>

 <style type="text/css">
 .halfDiv {
padding: 1em;
width: 42%;
float: left;
   }
.rightDiv {
padding: 1em;
width: 7%;
float: right;
  }

  </style>
  </head>
  <body>
<div class="halfDiv">
 <div id='header'>
 <h1 class="font2">Blocker User</h1>
 <form action='javascript:void(0);'>
<h3> <input id='search_input' size="32" style="height:20px"   name='search_input' type='text' autocomplete="on" />
 </h3>
 </form>
</div>
<div style="clear:left; height:30px;"></div>
<c:forEach items="${imageList}" var="blocker_images">
<div id='content'>
<div class='volcano search_item'>
<h4 class='search_text'>
<div class=fontstyle >
  ${blocker_images.user.userid }                            
 ${blocker_images.user.firstname } 
 ${images.user.lastname}
 ${blocker_images.user.email }
</div>
</h4>
<div class="infor_div">
<img alt="pictures" src="<c:url value='${request.contextPath}/image/${blocker_images.imageid}'/>" />    </div>
<div class="picture_div">
<p>${blocker_images.user.address.street }<br/>${blocker_images.user.address.zipcode }    ${blocker_images.user.address.city }</p> </div>
</div>
</div>
</c:forEach>
</div>
<div class="halfDiv">
<div id='header'>
<h1 class="font2">Blocked User</h1>
<form action='javascript:void(0);'>
<h3>
<input id='blocked' size="32" style="height:20px" name='blocked' type='text' autocomplete="off" />
</h3>
</form>
</div>
<div style="clear:left; height:30px;"></div>
<c:forEach items="${imageList}" var="blocked_images">
<div id='content'>
<div class='volcano search_item_blocked'>
<h4 class='search_text_blocked'>
<div class="fontstyle">
${blocked_images.user.userid }
${blocked_images.user.firstname }
${blocked_images.user.lastname} ${blocked_images.user.email }</div>
</h4>
<div class="picture_div">
<img alt="pictures" src="<c:url value='${request.contextPath}/image/${blocked_images.imageid}'/>"/>
</div>
<div class="infor_div">                                   
${blocked_images.user.address.street }
 ${blocked_images.user.address.city } ${blocked_images.user.address.zipcode }</p>
</div></div>
</div>
</c:forEach>
</div>
<form:form action="" method="post" modelAttribute="user">
        <div  class="rightDiv"> <button class="button blue" type="submit">Save</button></div>
        </form:form>
    </div>
 </div>
 </body> 
 </html>

Here is The autocomplete.js

$().ready(function(){
// Instant Search
$('#search_input').keyup(function(){
$('.search_item').each(function(){
  var re = new RegExp($('#search_input').val(), 'i');
  if($(this).children('.search_text')[0].innerHTML.match(re)){
    $(this).show();
  }else{
    $(this).hide();
  };
 });
 });
});
 $().ready(function(){
// Instant Search
$('#blocked').keyup(function(){
    $('.search_item_blocked').each(function(){
        var re = new RegExp($('#blocked').val(), 'i');
        if($(this).children('.search_text_blocked')[0].innerHTML.match(re)){
            $(this).show();
        }else{
            $(this).hide();
        };
    });
});
   });

here is my Controller

 @Controller
 @RequestMapping
 public class BlockeeController
 {
@Autowired
private static BlockeeService blockeeService = new BlockeeService();
@Autowired
private static UserService us = new UserService();
@Autowired
private static DisplayImageService imgService = new DisplayImageService();

    @RequestMapping(value = "/autocomplete", method = RequestMethod.GET)
public String autocomplete(@ModelAttribute("blocker") User  blocker,     @ModelAttribute("blocked") User blocked, ModelMap model, HttpServletRequest request)
{
    System.out.println("blocker "+blocker);
    System.out.println("blocked "+blocked);

    model.addAttribute("currentUser", getCurrentUsername());

    Collection<User> users = us.findAllUsers();
    model.addAttribute("allUsers", users);

    Collection<UploadImage> imageList = imgService.showAllPictures();
    model.addAttribute("imageList", imageList);
            model.addAttribute("blocker", blocker);
    model.addAttribute("blocked", blocked);

    return "autocomplete";

}

The question here is: what should it be here @RequestParam or @ModelAttribute? Can I have two different Modelattribute ? I just wrote some code here as example.

@RequestMapping(value = "/autocomplete", method = RequestMethod.POST)
public String blockeeImages(@ModelAttribute("blocker") User  blocker, @ModelAttribute("blocked") User blocked, Model model)
{

    System.out.println(blocker);
    System.out.println(blocked);
    model.addAttribute("currentUser", getCurrentUsername());


    UploadImage blockerImage = imgService.showImageByUserId(blocker.getUserid());
    model.addAttribute("blockerImage", blockerImage.getImageid());
    model.addAttribute("blockerUser", blockerImage);

    UploadImage blockedImage = imgService.showImageByUserId(blocked.getUserid());
    model.addAttribute("blockedImage", blockedImage.getImageid());
    model.addAttribute("blockedUser", blockedImage);

    Blockee blockee= new Blockee(blocker,blocked);
    blockeeService.addUserToBlockee(blockee);

    return "/blockeeIndex";
}


private String getCurrentUsername()
{
    Object obj = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
    return obj instanceof UserDetails ? ((UserDetails) obj).getUsername() : obj.toString();
}

 } 

Thanks for any help!

Upvotes: 3

Views: 1575

Answers (2)

Eduardo Quintana
Eduardo Quintana

Reputation: 2388

You can send the JSON representing the User that you want to retrieve in your controller.

For example if you send a JSON like this:

$.ajax({url:'autocomplete',
  type:'POST',
  dataType:'json',
  contentType:'application/json',
  data:JSON.stringify([
                 {blockerImage : someValue, ... }
                 ,{blockerImage: otherValue, ...}])
});

(I'm assuming some values for the User POJO)

This will send to your controller a List of blocker objects you can retrieve them in your controller bi having something like this.

public String blockeeImages(@RequestBody List<User> blockerParams, Model model){

}

Having the POJO for your User object sending the JSON will create the user objects and then you can use them as you wish.

And add jackson-mapper to your project to work more easily with JSON reprentations.

Upvotes: 1

Jeevan Patil
Jeevan Patil

Reputation: 6079

You have not mentioned any <form></form> tags in your JSP page. Save button type is mentioned to be Submit, so add a form and get all the form attributes in controller using @ModelAttribute annotation, provided you write a POJO containing JSP attributes in it.

Other option is make an AJAX call on click of Save button. Prepare a Javascript object, assign variables to it along with values and stringify it. Stringify operation will convert it to JSON, pass this JSON to controller which will convert it to Java Object representing the Javascript object. Controller will accept this obkect using @RequestBody annotation.

Upvotes: 1

Related Questions