Rodrigo E. Pinheiro
Rodrigo E. Pinheiro

Reputation: 97

Search in Spring MVC

Hello I have a simple search in my Spring MVC application. I can access my objects via URL. Like /application-web/search?searchString=Team1. How do make my search to work listing my Teams in the search view when I hit the Search button?

Here's the code:

@Controller
public class SearchController {

@Autowired    
SuperPlayerService sp;

@RequestMapping(value="/search")
public ModelAndView Search(@RequestParam(value = "searchTerm", required = false) 
 String pSearchTerm, HttpServletRequest request, HttpServletResponse response) {
   ModelAndView mav = new ModelAndView("search");

   mav.addObject("searchTerm", pSearchTerm);
   mav.addObject("searchResult", sp.findTeamByName(pSearchTerm));      

   return mav;
  }
}

JSP:

<%@ page contentType="text/html" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="t" tagdir="/WEB-INF/tags"%>
<%@ taglib uri="http://www.springframework.org/tags/form" prefix="form"%>

<t:MasterTag>
<jsp:attribute name="pageTitle">
    <c:out value="Search" />
</jsp:attribute>

<jsp:attribute name="currentMenuName">
    <c:out value="Search" />
</jsp:attribute>

<jsp:body>

<div class="row">
    <div class="small-3 columns">
        <input type="text" id="txt" name="searchString">
    </div>

    <div class="small-5 columns end">
        <button id="button-id" type="submit">Search Teams</button>
    </div>
</div>
<div class="row">
    <div>
        ${searchTerm}
    </div>
</div>

MY JS function(I'm using Foundation library to render my front end elements)

  <script>
    $(document).foundation();
    window.onload = function(){
        var a = document.getElementById("searchButton");
        a.onclick = function() {                  
      window.location.replace("${pageContext.request.contextPath}/search?query=" +   
      document.getElementById("searchInput").value);    
        };
    };      
    </script>

Upvotes: 0

Views: 2628

Answers (1)

chresse
chresse

Reputation: 5805

If your searchResult is a collection, you can iterate over them with a foreach loop:

<h2>Results for ${searchTerm}:<h2>
<c:forEach items="${searchResult}" var="result">
    <li>${result}</li>
</c:forEach>

If you want to check before if you have searchResults, you can surround it with:

<c:if test="${not empty searchResult}">
    //foreach loop
</c:if>

Upvotes: 1

Related Questions