Solved

Spring MVC 3.0 Request/ Response Object

Posted on 2010-09-15
25
1,606 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
ID: 33688395
just add them as parameters to the method that needs them
0
 
LVL 92

Expert Comment

by:objects
ID: 33688414
better to bind the parameters

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

Author Comment

by:lotrzz
ID: 33688504
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
ID: 33688515
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
ID: 33688542
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
ID: 33688550
> <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
ID: 33688569
<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
ID: 33688584
yes
0
 

Author Comment

by:lotrzz
ID: 33688667
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
ID: 33688713
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
DevOps Toolchain Recommendations

Read this Gartner Research Note and discover how your IT organization can automate and optimize DevOps processes using a toolchain architecture.

 
LVL 92

Expert Comment

by:objects
ID: 33688795
>             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
ID: 33688812
0
 

Author Comment

by:lotrzz
ID: 33688821
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
ID: 33688837
but they weren't adding any request params
0
 

Author Comment

by:lotrzz
ID: 33688855
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
ID: 33688863
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
ID: 33689088
see the example I posted above
0
 

Author Comment

by:lotrzz
ID: 33695000
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
ID: 33695037
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
ID: 33695884
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
ID: 33752562
yes that example finally helped
0

Featured Post

3 Use Cases for Connected Systems

Our Dev teams are like yours. They’re continually cranking out code for new features/bugs fixes, testing, deploying, testing some more, responding to production monitoring events and more. It’s complex. So, we thought you’d like to see what’s working for us.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
JAVA part two 5 57
couple of eclipse 5 23
reverse digits of a number using for loop 5 36
even odd program using while loop 3 29
Java contains several comparison operators (e.g., <, <=, >, >=, ==, !=) that allow you to compare primitive values. However, these operators cannot be used to compare the contents of objects. Interface Comparable is used to allow objects of a cl…
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 learn about the “while” loop and how to utilize it correctly in Java. Additionally, viewers begin exploring how to include conditional statements within a while loop and avoid an endless loop. Define While Loop: Basic Example: Explanatio…
Viewers learn about the scanner class in this video and are introduced to receiving user input for their programs. Additionally, objects, conditional statements, and loops are used to help reinforce the concepts. Introduce Scanner class: Importing…

920 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

12 Experts available now in Live!

Get 1:1 Help Now