I'm new to Spring MVC, and I'm trying to do a simple search. Here's my Controller and View. How do I make the search to actually work? The findTeamByName is already implemented from a interface and the Teams are already populated in memory. Thank you in advance guys!
@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>
you can return your values i.e in a ModelAndView
@RequestMapping(value="/search/{searchTerm}")
public ModelAndView Search(@PathVariable("searchTerm") String pSearchTerm) {
ModelAndView mav = new ModelAndView("search");
mav.addObject("searchTerm", pSearchTerm);
mav.addObject("searchResult", sp.findTeamByName(pSearchTerm));
return mav;
}
This field can be accessed in your search.jsp by ${searchTerm}
EDIT:
if you want so search like: search?searchTerm=java
then you can do it with:
@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;
}
Spring MVC Controller method can accept a wide range of arguments and one of them is org.springframework.ui.Model.
You can add values to the Model which will become available in your JSP at requestScope.
In your case, your Java code would look like this
@RequestMapping(value = "/search")
public String Search(@RequestParam("searchString") String searchString, Model model) {
if(searchString != null){
Object searchResult = sp.findTeamByName(searchString);
model.addAttribute("searchResult", searchResult);
}
return "search";
}
In your JSP, you could then access the result as usual object in requestScope like ${searchResult}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With