Spring MVC 3.0 Request/ Response Object

How do I get hold of the  HTTP req/ res  object in Spring MVC 3.0 Controller.

I have a form (say employee name and id) with a serach button and when I click serach i go to the Controller method.  Does the controller method needs to have  request & response as a part of the parameter? Please help or send me a link that shows how to display a simple list of search results in  Spring MVC 3.0.

thanks
lotrzzAsked:
Who is Participating?
 
objectsCommented:
just add them as parameters to the method that needs them
0
 
objectsCommented:
better to bind the parameters

... search(@RequestParam("id") int id, @RequestParam("name") String name)
0
The new generation of project management tools

With monday.com’s project management tool, you can see what everyone on your team is working in a single glance. Its intuitive dashboards are customizable, so you can create systems that work for you.

 
lotrzzAuthor Commented:
It is not working.  Here is the example I am trying
http://viralpatel.net/blogs/2010/07/spring-3-mvc-handling-forms.html

Everything is same except I replaced the add with a search button in the  contact.jsp that will return a list of serach results back to the page.

1) here is my modfied controller method (I just added  a static list - everything else is same)
2)  I am also attaching the  ressults.jsp

Pls let me know what I am missing


//controller
package net.viralpatel.spring3.controller;  

 

import net.viralpatel.spring3.form.Contact;  


import java.util.ArrayList;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;



import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes
public class ContactController {
	
	public static final String SEARCH_RESULTS_NAME 	= "ContactSearchResults";

	@RequestMapping(value = "/addContact", method = RequestMethod.POST)
	public String addContact(@ModelAttribute("contact")
							Contact contact, BindingResult result,
							HttpServletRequest request, HttpServletResponse response) {

		System.out.println("First Name:" + contact.getFirstname() +
					"Last Name:" + contact.getLastname());
		Contact con = new Contact();
		con.setFirstname("subir");
		con.setLastname("chow");
		con.setEmail("sub@gmail.com");
		con.setTelephone("111-222-3333");
		Contact con2 = new Contact();
		con2.setFirstname("ser");
		con2.setLastname("hhyu");
		con2.setEmail("gfrt@gmail.com");
		con2.setTelephone("222-777-0987");
		ArrayList list = new ArrayList();
		list.add(con);
		list.add(con2);
		request.setAttribute(SEARCH_RESULTS_NAME, list);

		return "redirect:contacts.html";
	}
	@RequestMapping("/contacts")
	public ModelAndView showContacts() {

		return new ModelAndView("contact", "command", new Contact());
	}
}
//end controller


//results.jsp
	<%@ page import="java.util.*" %>
	<%@ page import net.viralpatel.spring3.form.Contact;%>
	<% List resultsList = (List)request.getAttribute("ContactSearchResults"); 
	%>
<c:if test="${!empty requestScope.ContactSearchResults}">
<table>
	  <tr>
	    <td>
  	      <table id="resultsTable" name="resultsTable" border="1" width="100%">
  	      <tr>	  
		  	<th>firstName</th>
		  	<th >lastName</th>
		  	<th >email</th>
		  	<th >telephone</th>
	        </tr>
	        <c:forEach items="${requestScope.ContactSearchResults}" var="st">
	        <tr>
			  <td ><nobr><ftl:writeBean name="st" property="firstName"/></nobr></td>
			  <td ><nobr><ftl:writeBean name="st" property="lastName"/></nobr></td>
			  <td ><nobr><ftl:writeBean name="st" property="email"/></nobr></td>
			  <td ><nobr><ftl:writeBean name="st" property="telephone"/></nobr></td>
		      </tr>		
		    </c:forEach>	  
	  	  </table>  	  
	    </td>
	  </tr>	  
	  </table>
	  </c:if>

Open in new window

0
 
lotrzzAuthor Commented:
Also I modified  contact.jsp so that now it includes the  contact results when there is data. Let me know If i am missing something


<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
	<title>Spring 3 MVC Series - Contact Manager</title>
	<link href="style/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<h2>Contact Manager</h2>
<form:form method="post" action="addContact.html">

	<table>
	
	<tr>
		<td><form:label path="firstname">First Name</form:label></td>
		<td><form:input path="firstname" /></td>
	</tr>
	<tr>
		<td><form:label path="lastname">Last Name</form:label></td>
		<td><form:input path="lastname" /></td>
	</tr>
	<tr>
		<td><form:label path="lastname">Email</form:label></td>
		<td><form:input path="email" /></td>
	</tr>
	<tr>
		<td><form:label path="lastname">Telephone</form:label></td>
		<td><form:input path="telephone" /></td>
	</tr>
	<tr>
		<td colspan="2"><input type="submit" value="Search"/></td>
	</tr>
	
</table>	

<!-- If the userResultsList is NOT empty then collapse the search form -->
	<c:if test="${!empty requestScope.ContactSearchResults}">
	  <%@ include file="contactResults.jsp" %>
	  <br>
	</c:if>

</form:form>
</body>
</html>

Open in new window

0
 
lotrzzAuthor Commented:
objects,
everything is same as the above example , except  I added the results.jsp and modfied the controller and the contact.jsp (to display the results to it)
0
 
objectsCommented:
> <form:form method="post" action="addContact.html">

>       @RequestMapping(value = "/addContact", method = RequestMethod.POST)

your method is mapped to /addContact, but your forms action is /addContact.html
0
 
lotrzzAuthor Commented:
<bean id="viewResolver"
            class="org.springframework.web.servlet.view.UrlBasedViewResolver">
            <property name="viewClass"
                  value="org.springframework.web.servlet.view.JstlView" />
            <property name="prefix" value="/WEB-INF/jsp/" />
            <property name="suffix" value=".jsp" />
      </bean>

This is how my spring-servlet looks like.   Do you want me to remove the .html and try?

0
 
objectsCommented:
yes
0
 
lotrzzAuthor Commented:
I am actually getting a NullPointerException now , it seems it is actually not liking the c:if tag initially because initially the result list is always  null.  What do i do?

<c:if test="${!empty requestScope.ContactSearchResults}">
        <%@ include file="contactResults.jsp" %>
        <br>
      </c:if>

0
 
lotrzzAuthor Commented:
Objects,
pls send me a example or  a link where user clicks a serach button and a list of results is returned to the screen. That'll help me a lot.
0
 
objectsCommented:
>             return "redirect:contacts.html";

you redirect to another path, that will lose the request param
just return the view you want to display
and you're better off putting list into model instead of requests params
0
 
lotrzzAuthor Commented:
But in the example, that's how it was.  
http://viralpatel.net/blogs/2010/07/spring-3-mvc-handling-forms.html

The redirect worked corrected, how come when I add the list it didn't work.  How do I put a list into my model and then display it in the jsp ?
0
 
objectsCommented:
but they weren't adding any request params
0
 
lotrzzAuthor Commented:
Okay, so how do I put the list in the ModelAndView object.  As you see my controller has two methods,  
addContact and showContacts. And, I have two buttons ?  How do I have the add go to the addContact function and search go to the showContacts function?  

Then in the showContacts method I can build a list and forward to view.
0
 
lotrzzAuthor Commented:
In other words how do I map each button to a  different method (corresponding to the operation) from the jsp to the controller  like in  DispatAction in Struts.  I am very new to Spring MVC
0
 
objectsCommented:
see the example I posted above
0
 
lotrzzAuthor Commented:
I went through the example that you send me but in my case it is slightly different. The serach results are a part of the serachform.  Even if they are different I am not getting any results

here is my  contact.jsp

<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<html>
<head>
      <title>Spring 3 MVC Series - Contact Manager</title>
</head>
<body>
<h2>Contact Manager</h2>
<form:form method="post" action="addContact.html">

      <table>
      <tr>
            <td><form:label path="firstname">First Name</form:label></td>
            <td><form:input path="firstname" /></td>
      </tr>
      <tr>
            <td><form:label path="lastname">Last Name</form:label></td>
            <td><form:input path="lastname" /></td>
      </tr>
      <tr>
            <td><form:label path="email">Email</form:label></td>
            <td><form:input path="email" /></td>
      </tr>
      <tr>
            <td><form:label path="telephone">Telephone</form:label></td>
            <td><form:input path="telephone" /></td>
      </tr>
      <tr>
            <td>
                  <input type="submit" name="add" value="Add Contact"/><br>
                  <input type="submit" name="search" value="Search"/>
                  <input type="submit" name="showAdd" value="Show Add"/>
            </td>
      </tr>
</table>      


</form:form>
</body>
</html>
------------------------------------------
here is my contactResults.jsp
      <%@ page import="java.util.*" %>
      <%@ page import="com.fruit.spring3.form.*" %>
      <%@page contentType="text/html" pageEncoding="UTF-8"%>
      <%@ page isELIgnored="false"%>
      <% ArrayList<Contact> resultsList = (ArrayList)request.getAttribute("ContactSearchResults");
        System.out.println("size results list = "+ resultsList.size());
        for(Contact con : resultsList){
              System.out.println("first name =====> "+ con.getFirstname());  
        }
      %>
      <html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
    <title>Contact Search</title>
    <link href="style/style.css" rel="stylesheet" type="text/css" />
</head>
<body>
<c:choose>
<c:when test="${!empty ContactSearchResults}">
   <table>
        <tr>
          <td>
              <table id="resultsTable" name="resultsTable" border="1" width="100%">
              <tr>       
                    <th>firstName</th>
                    <th>lastName</th>
                    <th>email</th>
                    <th>telephone</th>
            </tr>
              <c:forEach var="item" items="${ContactSearchResults}">
              <tr>
                    <td ><nobr><c:out value="${item.firstname}"/></nobr></td>
                    <td ><nobr><c:out value="${item.lastname}"/></nobr></td>
                    <td ><nobr><c:out value="${item.email}"/></nobr></td>
                    <td ><nobr><c:out value="${item.telephone}"/></nobr></td>
                </tr>            
                </c:forEach>       
                </table>         
          </td>
        </tr>       
   </table>
</c:when>
<c:otherwise>
      No results found
</c:otherwise>
</c:choose>
</body>
</html>

------------------------------
Here is my  Controller after all changes

package com.fruit.spring3.controller;

import java.awt.List;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import com.fruit.spring3.form.Contact;
import com.fruit.spring3.form.AddContact;

import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.SessionAttributes;
import org.springframework.web.servlet.ModelAndView;

@Controller
@SessionAttributes
public class ContactController {

      @RequestMapping(value = "/addContact", params="add", method = RequestMethod.POST)
      public String addContact(@ModelAttribute("contact")
                                          Contact contact, BindingResult result) {

            System.out.println("First Name:" + contact.getFirstname() +
                              "Last Name:" + contact.getLastname());
            

            return "redirect:contacts.html";
      }
      
      @RequestMapping(value = "/addContact", params="search", method = RequestMethod.POST)
      public ModelAndView searchContact(@ModelAttribute("contact")Contact contact, BindingResult result) {
            System.out.println("i m here-2");       
            Contact con = new Contact();
            con.setFirstname("me");
            con.setLastname("you");
            Contact con2 = new Contact();
            con2.setFirstname("me2");
            con2.setLastname("you2");
            con2.setTelephone("111-222-3333");
            ArrayList<Contact> myList = new ArrayList<Contact>();
            myList.add(con);
            myList.add(con2);
            
            Map model = new HashMap();
            model.put("ContactSearchResults", myList);

            return new ModelAndView("contactResults",  model);
      }
      
      @RequestMapping(value="/addContact", params="showAdd", method = RequestMethod.POST)
      public ModelAndView showAdd() {
            System.out.println("i m here-3");
            return new ModelAndView("addContact");
      }

      @RequestMapping(value="/contacts")
      public ModelAndView showContacts(HttpServletRequest req) {
            //System.out.println("i m here-1");

            return new ModelAndView("contact", "command", new Contact());
      }
      
}

Let me know what I am missing

0
 
lotrzzAuthor Commented:
If I print out the list I am seeing  size =2 but  the c:foreach tag is printing nothing and I am getting no results found
0
 
lotrzzAuthor Commented:
objects,  

do you see anything wrong with the  contactresults.jsp?  I could able to print the list in the system.out on top but the for:each tag is printing nothing.  It seems there is something wrong with the for:each tag.
0
 
lotrzzAuthor Commented:
yes that example finally helped
0
All Courses

From novice to tech pro — start learning today.