Solved

Spring MVC 3.0 Request/ Response Object

Posted on 2010-09-15
25
1,604 Views
Last Modified: 2013-11-24
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
0
Comment
Question by:lotrzz
  • 13
  • 8
25 Comments
 
LVL 92

Expert Comment

by:objects
Comment Utility
just add them as parameters to the method that needs them
0
 
LVL 92

Expert Comment

by:objects
Comment Utility
better to bind the parameters

... search(@RequestParam("id") int id, @RequestParam("name") String name)
0
 

Author Comment

by:lotrzz
Comment Utility
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
 

Author Comment

by:lotrzz
Comment Utility
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
 

Author Comment

by:lotrzz
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
> <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
 

Author Comment

by:lotrzz
Comment Utility
<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
 
LVL 92

Expert Comment

by:objects
Comment Utility
yes
0
 

Author Comment

by:lotrzz
Comment Utility
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
 

Author Comment

by:lotrzz
Comment Utility
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
How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

 
LVL 92

Expert Comment

by:objects
Comment Utility
>             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
 
LVL 92

Accepted Solution

by:
objects earned 500 total points
Comment Utility
0
 

Author Comment

by:lotrzz
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
but they weren't adding any request params
0
 

Author Comment

by:lotrzz
Comment Utility
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
 

Author Comment

by:lotrzz
Comment Utility
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
 
LVL 92

Expert Comment

by:objects
Comment Utility
see the example I posted above
0
 

Author Comment

by:lotrzz
Comment Utility
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
 

Author Comment

by:lotrzz
Comment Utility
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
 

Author Comment

by:lotrzz
Comment Utility
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
 

Author Closing Comment

by:lotrzz
Comment Utility
yes that example finally helped
0

Featured Post

Highfive + Dolby Voice = No More Audio Complaints!

Poor audio quality is one of the top reasons people don’t use video conferencing. Get the crispest, clearest audio powered by Dolby Voice in every meeting. Highfive and Dolby Voice deliver the best video conferencing and audio experience for every meeting and every room.

Join & Write a Comment

This was posted to the Netbeans forum a Feb, 2010 and I also sent it to Verisign. Who didn't help much in my struggles to get my application signed. ------------------------- Start The idea here is to target your cell phones with the correct…
Introduction This article is the first of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article explains our test automation goals. Then rationale is given for the tools we use to a…
Viewers will learn about arithmetic and Boolean expressions in Java and the logical operators used to create Boolean expressions. We will cover the symbols used for arithmetic expressions and define each logical operator and how to use them in Boole…
This tutorial explains how to use the VisualVM tool for the Java platform application. This video goes into detail on the Threads, Sampler, and Profiler tabs.

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

10 Experts available now in Live!

Get 1:1 Help Now