• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 1713
  • Last Modified:

Spring mvc redisplay the same JSP

Hi,

i have a scenario where the user enters data in the form and submits the form.  So upon submission of the form, the same jsp must be displayed with the results.  The jsp must also retain the values entered by user on top and in the bottom of the page it should display the results.  The part of retaining the values after submission is done and is working but the displaying of the results in the same JSP page is not showing up.  here is the code:

VtqForm.jsp
---------------
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%@page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>

<!-- Global declaration -->
<%
   String viewValue = request.getParameter("view");
   if(viewValue == null)viewValue = "Choose One";
   String applicationValue = request.getParameter("application");
   if(applicationValue == null)applicationValue = "Choose One";
   String timeRangeSel = request.getParameter("timeRangeSel");
   if(timeRangeSel == null) timeRangeSel = "15 Minute";
   String novusSel = request.getParameter("novusSel");
   if(novusSel == null) novusSel = "Production";
   String middleTierSel = request.getParameter("middleTierSel");
   if(middleTierSel == null) middleTierSel = "Client";
%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1"/>
<title>Tremor VTQ Page</title>

<style type="text/css">
.even {
	background-color: silver;
	width: 20px;
	border: thin;
	border-color: black;
	font-size: 12pt;
}
.setFont{
	font: normal;
	font-size: 10pt;
}
.setSpecialFont{
	font-size: 12pt;
	font: italic;
	font-weight: bold; 
	color: blue;
}
</style>

<style type="text/css" media="screen">
    .jqplot-axis {
      font-size: 0.85em;
    }
    .jqplot-title {
      font-size: 1.1em;
    }
</style>

<link rel="stylesheet" type="text/css" href="<c:url value="/css/jquery-ui-timepicker-addon.css"/>"></link>

<link rel="stylesheet" type="text/css" href="<c:url value="/css/jquery.jqplot.css"/>"></link>
<link rel="stylesheet" type="text/css" href="<c:url value="/css/jquery-ui.css"/>"></link>

<script language="javascript" type="text/javascript" src="<c:url value="/jquery/jquery.js"/>"></script>
<script language="javascript" type="text/javascript" src="<c:url value="/jquery/jquery.jqplot.js"/>"></script>
<script language="javascript" type="text/javascript" src="<c:url value="/jquery/jqplot.canvasTextRenderer.min.js"/>"></script>
<script language="javascript" type="text/javascript" src="<c:url value="/jquery/jqplot.canvasAxisLabelRenderer.min.js"/>"></script>
<script language="javascript" type="text/javascript" src="<c:url value="/jquery/jqplot.LinearAxisRenderer.js"/>"></script>

<script type="text/javascript" src="<c:url value="/jquery/jqplot.dateAxisRenderer.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/jquery/jqplot.highlighter.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/jquery/jqplot.cursor.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/jquery/jqplot.canvasTextRenderer.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/jquery/jqplot.canvasAxisTickRenderer.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/jquery/jqplot.categoryAxisRenderer.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/jquery/jqplot.pointLabels.min.js"/>"></script>
<script type="text/javascript" src="<c:url value="/jquery/jqplot.cursor.min.js"/>"></script>

<!-- jQuery date picker included -->
<script type="text/javascript" src="<c:url value="/jquery/jquery.ui.core.js"/>"></script>
<script type="text/javascript" src="<c:url value="/jquery/jquery.ui.widget.js"/>"></script>
<script type="text/javascript" src="<c:url value="/jquery/jquery.ui.datepicker.js"/>"></script>
<link rel="stylesheet" type="text/css" href="<c:url value="/css/demos.css"/>"></link>


function retainValue(){
    var element1 = document.forms[0].view;
    for(x = 0; x < element1.length; x++){
            if(element1.options[x].value == "<%=viewValue%>"){
                  element1.options[x].selected = true;
                  break;
       	} 
    }
    var element2 = document.forms[0].application;
    for(x = 0; x < element2.length; x++){
            if(element2.options[x].value == "<%=applicationValue%>"){
                  element2.options[x].selected = true;
                  break;
       	} 
    }
    var element3 = document.forms[0].timeRangeSel;
    for(x = 0; x < element3.length; x++){
            if(element3.options[x].value == "<%=timeRangeSel%>"){
                  element3.options[x].selected = true;
                  break;
       	} 
    }
    var element4 = document.forms[0].novusSel;
    for(x = 0; x < element4.length; x++){
            if(element4.options[x].value == "<%=novusSel%>"){
                  element4.options[x].selected = true;
                  break;
       	} 
    }
    var element5 = document.forms[0].middleTierSel;
    for(x = 0; x < element5.length; x++){
            if(element5.options[x].value == "<%=middleTierSel%>"){
                  element5.options[x].selected = true;
                  break;
       	} 
    }
};
</script>
</head>
<body onload="retainValue();">
<div id="mainDiv" title="Main Block" style="border: 1px;border-color: black; background-color: white">
<form action="VtqForm.do" method="post" id="teForm">
	<div id="dataEntryPoint" style=" background-color: activeborder; table-layout: auto; margin: 2px; margin-top:10px; margin-left:10px; width:1200px; height:80px; border: thin; border-color: black; border-style: dotted; ">
		<table>
			<tr>
				<td style="width: 2pc"></td>
				<td>
					<label id="startDateLbl" class="setFont" >Start Date/Time : </label>
				</td>
				<td>
					<input id="startDate" class="setFont" name="startDate" title="Start Date/Time" type="text" value="<% out.write(request.getParameter("startDate")); %>"/>
				</td>
				<td style="width: 2pc"></td>
				<td>
					<label id="endDateLbl" class="setFont" >End Date/Time : </label>
				</td>
				
				<td>
					<input id="endDate" name="endDate" class="setFont" title="End Date/Time" type="text" value="<% out.write(request.getParameter("endDate")); %>"/>
				</td>
				<td style="width: 2pc"></td>
				<td>
					<label id="view" class="setFont" >View : </label>
				</td>
				<td>
					<select id="view" name="view" class="setFont" style="width: auto;" tabindex="0" >
                    	<option value="Choose One" selected="selected">Choose One</option>
                    	<option value="Vertical">Vertical</option>
                   		<option value="Component">Component</option>
                     	<option value="Widget">Widget</option>
                       	<option value="user Guid">User Guid</option>
                    	<option value="Session Id">Session Id</option>
                      	<option value="Root Guid">Root Guid</option>
                	</select>
				</td>
				<td style="width: 2pc"></td>
				<td>
					<label id="applicationLbl" class="setFont" >Application : </label>
				</td>
				<td>
					<select id="application" name="application" class="setFont" style="width: auto;" tabindex="0">
                  		<option value="Choose One">Choose One</option>
                      	<option value="Build Reports">Build Reports</option>
                       	<option value="Clear App">Clear App</option>
                       	<option value="Security">Security</option>
                      	<option value="Document">Document</option>
                       	<option value="Clear EDD">Clear EDD</option>
                       	<option value="Unknown">Unknown</option>
                 	</select>
				</td>
			</tr>	
			<tr style="height: 20px;">
			</tr>
			<tr>
				<td style="width: 2pc"></td>
				<td>
					<label id="timeRangeLbl" class="setFont" >Time Range: </label>
				</td>
				<td>
					<select id="timeRangeSel" name="timeRangeSel" class="setFont" style="width: auto;" tabindex="0">
						<option selected="selected">15 Minute</option>
						<option>Minute</option>
						<option>Day</option>
						<option>Month</option>
					</select>
				</td>
				<td style="width: 2pc"></td>
				<td>
					<label id="novusLbl" class="setFont" >Novus : </label>
				</td>
				<td>
					<select id="novusSel" name="novusSel" class="setFont" style="width: auto;" tabindex="0">
						<option selected="selected">Production</option>
						<option>Client</option>
					</select>
				</td>
				<td style="width: 2pc"></td>
				<td>
					<label id="middleTierLbl" class="setFont" >Middle Tier : </label>
				</td>
				<td>
					<select id="middleTierSel" name="middleTierSel" class="setFont" style="width: auto;" tabindex="0">
						<option selected="selected">Client</option>
						<option>Production</option>
					</select>
				</td>
				<td style="width: 80px;">
				</td>
				<td>
					<span id="submitSpan">
							<input id="submitBtn" value="Submit" type="submit"/>
							<input id="hiddenBtn" type="hidden"/>
					</span>
				</td>
			</tr>
		</table>
	</div>
</form>

<div id="gapDiv" style="background-color: activeborder; table-layout: auto; margin: 2px; margin-top:10px; margin-left:10px; width:1200px; height:10px; border: thin; border-color: black; border-style: dotted; " />
<div id="dataDiv" >
	<table id="mainTab">
		<tr id="graphrow">
		<td>
			<table>
				<tr>
					<td style="margin-top:2px; margin-left:20px; width:860px; height:360px;">
						<div id="chart1" class="setSpecialFont" style="margin-top:20px; margin-left:20px; width:800px; height:500px; border: medium;"></div>
					</td>
				</tr>
				<tr>
					<td>
						<input id="resetBtn" name="ResetButton" value="Reset" type="button"/>
					</td>					
				</tr>
			</table>
			</td>
			<td>
				<div id="dataDiv" style="margin-top:30px; margin-left:10px; width: auto; height:500px; overflow: auto;" >
					<c:if test="${fn:length(numOccurrences) > 0}">
						<table id = "tableGraph" class="setFont" style="border: thin; border-color: black; border-style: inset; width: 20pc;" cellspacing="2" cellpadding="5">
							<thead id="tableheader" valign="top">
								<tr class="even">
									<th>Number of Occurrences </th>
									<th>Generated Time </th>
								</tr>
							</thead>
							<c:forEach items="${numOccurrences}" varStatus="status">
							<tr>
								<td id="numOccurences${status.index}">${numOccurrences[status.index]}</td>
								<td id="timeInterval${status.index}">${timeInterval[status.index]}</td>
							</tr>
							</c:forEach>
						</table>
					</c:if>
				</div>
			</td>
		</tr>
	</table>
	<span id="graphFooter" style="font-size: 18px; font-style: italic;">Total Points: ${totalOccurrences}</span>
	<input type = "hidden" id="maxOccur" value="${hsOccurNum}"/>
	<input type="hidden" id="totalRecs" value = "${totalOccurrences}"/>
</div>
</div>
</div>
</body>
</html>

Springapp-servlet.xml
----------------------------
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd"> 


	<!--  ================================================ -->
				<!-- Hibernate related mappings  -->
	<!--  ================================================ -->
	
	<bean id="tremorDataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
		<property name="driverClassName" value="oracle.jdbc.driver.OracleDriver"/>
		<property name="url" value="jdbc:oracle:thin:@AAA-bbb:1521/abc.def.com"/>
		<property name="username" value="AAA"/>
		<property name="password" value="XXX"/>
	</bean>
	
	<bean id="mysessionFactory" class="org.springframework.orm.hibernate3.annotation.AnnotationSessionFactoryBean">
		<property name="dataSource" ref="tremorDataSource" />
		<property name="packagesToScan" value = "com.tlrg.clear.web.domain" />
		
		<property name="hibernateProperties">
			<props>
				<prop key="hibernate.dialect">org.hibernate.dialect.OracleDialect</prop>
				<prop key="hibernate.default_schema">dummy</prop>
				<prop key="hibernate.show_sql">true</prop>
				<prop key="hibernate.hbm2ddl.auto">none</prop>
				<prop key="connection.pool_size">10</prop>
				<!-- prop key="current_session_context_class">thread</prop -->
				<!-- prop key="hibernate.query.factory_class">org.hibernate.hql.classic.ClassicQueryTranslatorFactory</prop -->  
				<prop key="cache.provider_class">org.hibernate.cache.NoCacheProvider</prop>
			</props>
		</property>
	</bean>
	
	<!--  ================================================ -->
	  <!-- DAO to Controller Mapping at Persistence Layer -->
	<!--  ================================================ -->
	
	<!-- Vertical Transaction Qtr bean injection -->
	
	<bean id="tremorVtqDao" class="com.tlrg.clear.web.dao.VerticalTransactionQtrDAOimpl">
		<property name="sessionFactory" ref="mysessionFactory"/>
	</bean>
	
	<!--  ================================================ -->
				<!-- Jsp view resolver mappings -->
	<!--  ================================================ -->
	
	<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
		<property name="prefix" value="/WEB-INF/jsp/"/>
		<property name="suffix" value=".jsp"/>
	</bean>
	
	<!-- URL Mapping through proper controller -->
	
	<bean id="urlHandler" class="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping" >
		<property name="mappings">
			<map>
				<entry key="/VtqForm.do" value="vtQtrController"/> 
				<entry key="/VtqForm.htm" value="vtQtrController"/>
				
			</map>
		</property>
	</bean>
	
	
	
	<bean id="vtQtrController" class="com.tlrg.clear.web.VerticalTransactionQtrController" >
		<!-- <property name="methodNameResolver" ref="urlResolver" /> --> 
		<property name="vtqDao" ref="tremorVtqDao" />
	</bean>
	
</beans>

VerticalTransactionQtrcontroller.java
--------------------------------------------

/**
 * 
 */
package com.tlrg.clear.web;


import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.ResourceBundle;

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

import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.portlet.ModelAndView;

import com.tlrg.clear.web.dao.VerticalTransactionQtrDAO;
import com.tlrg.clear.web.domain.Api;
import com.tlrg.clear.web.domain.TremorEntry;
import com.tlrg.clear.web.domain.VerticalTransaction;
import com.tlrg.clear.web.domain.VtQtrResultCarrier;

/**
 * @author Lakkaraju, Sep 8, 2011
 *
 */
public class VerticalTransactionQtrController{
	
	private VerticalTransactionQtrDAO vtqDAO;
	// Sun Sep 11 05:00:00 CDT 2011
	private final SimpleDateFormat formatter = new SimpleDateFormat("EEE MMM d H:mm:ss z yyyy");
	//2008-09-30 4:00PM
	private final SimpleDateFormat finalFormatter = new SimpleDateFormat("yyyy-MM-dd H:mm");
	
	private static final ResourceBundle rs = ResourceBundle.getBundle("tremor");
	
	/**
	 * 
	 * @param vtqDAO
	 */
	public void setVtqDao(VerticalTransactionQtrDAO vtqDAO){
		this.vtqDAO = vtqDAO;
	}
	
	@RequestMapping(method = RequestMethod.GET)
	public ModelAndView vtqInitialGetRequest(HttpServletRequest request, HttpServletResponse response) throws Exception{
		ModelAndView mav = new ModelAndView("VtqForm");
		mav.clear(); // to test if there is any impact or not (ofcourse, not)
		return mav;
	}
	
	/**
	 * Validates the request and delegates to the proper page
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(method = RequestMethod.POST)
	public ModelAndView validateAndDelegateRequest(HttpServletRequest request, HttpServletResponse responses) throws Exception{
		TremorEntry tEntry = new TremorEntry();
		tEntry.setApplication(request.getParameter("application"));
		tEntry.setStartDate(request.getParameter("startDate"));
		tEntry.setEndDate(request.getParameter("endDate"));
		tEntry.setMiddleTier(request.getParameter("middleTier"));
		tEntry.setNovus(request.getParameter("novus"));
		tEntry.setTimeRange(request.getParameter("timeRange"));
		tEntry.setView(request.getParameter("view"));
		Long api_id = null;
		if(tEntry.getApplication() != null && !tEntry.getApplication().equals("")){
			String fullApiName = rs.getString(tEntry.getApplication());
			Api api = vtqDAO.getApiByName(fullApiName);
			api_id = api.getApi_id();
		}
		return list(api_id, tEntry);
	}
	
	/**
	 * 
	 * @param request
	 * @param response
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	public ModelAndView list(Long api_id, TremorEntry tEntry) throws Exception{
		ModelMap modelMap = new ModelMap();
		processStartEndDates(tEntry);
		List vtqList = vtqDAO.generateVtqReportFifteenMnsInterval(api_id, tEntry.getStartDate(), tEntry.getEndDate());
		modelMap.addAttribute("vtqList", vtqList);
		VtQtrResultCarrier resultCarrier = getXYparamsForGraph(vtqList);
		modelMap.addAttribute("timeInterval", resultCarrier.getGeneratedTimes());
		modelMap.addAttribute("numOccurrences", resultCarrier.getNumOfOccurrences());
		modelMap.addAttribute("totalOccurrences", resultCarrier.getNumOfOccurrences() != null ? resultCarrier.getNumOfOccurrences().length : 0);
		modelMap.addAttribute("hsOccurNum", (resultCarrier.getHighestScaleOccNum()));
		modelMap.addAttribute("vtq", new VerticalTransaction());
		return new ModelAndView("VtqForm.htm", modelMap);
		
	}
	
	/**
	 * @param tEntry
	 */
	private void processStartEndDates(TremorEntry tEntry) {
		if(tEntry.getStartDate() != null && tEntry.getEndDate() != null){
			Calendar cal = Calendar.getInstance();
			String startDate = tEntry.getStartDate();
			String endDate = tEntry.getEndDate();
			startDate = startDate+" 01:00";
			endDate = endDate+" "+cal.get(Calendar.HOUR_OF_DAY)+":"+cal.get(Calendar.MINUTE);
			tEntry.setStartDate(startDate);
			tEntry.setEndDate(endDate);
		}
	}

	/**
	 * 
	 * @param qtrLst
	 * @return
	 * @throws Exception
	 */
	@SuppressWarnings("unchecked")
	private VtQtrResultCarrier getXYparamsForGraph(List qtrLst) throws Exception{
		VtQtrResultCarrier results = new VtQtrResultCarrier();
		if(qtrLst != null && qtrLst.size() > 0){
			int[] numOccurrences = new int[qtrLst.size()];
			int hsOccurNum = 0;
			String[] timeQtr = new String[qtrLst.size()];
			Object[] objArr =  null;
			String formattedDate = null;
			String dateStr = null;
			Date currDate, fmtDate = null;
			for(int i = 0; i < qtrLst.size(); i++){
				objArr = (Object[])qtrLst.get(i);
				numOccurrences[i] = ((Long)objArr[0]).intValue();
				if(numOccurrences[i] > hsOccurNum){
					hsOccurNum = numOccurrences[i];
				}
				dateStr = new Date(((Timestamp)objArr[1]).getTime()).toString();
				currDate = formatter.parse(dateStr);
				formattedDate = formatter.format(currDate);
				fmtDate =formatter.parse(formattedDate);
				timeQtr[i] = finalFormatter.format(fmtDate);
			}
			results.setGeneratedTimes(timeQtr);
			results.setNumOfOccurrences(numOccurrences);
			results.setHighestScaleOccNum(hsOccurNum);
		}
		return results;
	}
}

Open in new window

Murali.
0
lakkarajumurali
Asked:
lakkarajumurali
  • 3
  • 2
1 Solution
 
chaitu chaituCommented:
return new ModelAndView(new RedirectView(getSuccessView()));
or
return new ModelAndView(new RedirectView("success.htm");

check this.

http://stackoverflow.com/questions/1642784/return-same-view-controller-using-modelandview-of-spring-web-mvc
0
 
chaitu chaituCommented:
http://almaer.com/blog/redirect-in-spring-mvc


Use the new redirect: syntax in my action-servlet.xml

<property name=”successView”><value>redirect:/listAuctions.html</value></property>

Set the redirectContextRelative attribute to true in my Velocty View Resolved (this is true by default)

<bean id=”viewResolver”
class=”org.springframework.web.servlet.view.velocity.VelocityViewResolver”>
<property name=”exposeSpringMacroHelpers”><value>true</value></property>
<property name=”requestContextAttribute”><value>rc</value></property>
<property name=”redirectContextRelative”><value>true</value></property>
<property name=”cache”><value>true</value></property>
<property name=”prefix”><value>/WEB-INF/velocity/</value></property>
<property name=”suffix”><value>.vm</value></property>
</bean>

0
 
lakkarajumuraliAuthor Commented:
Thank you for the reply.  When i redirect the page, it is basically performing GET call which i dont want it.  

I fixed this problem this morning by changing the imports in the VerticalTransactionQtrController class.  I dont know the difference between the web.portlet.ModelAndView and 'web.servlet.ModelAndView', there were two ModelAndView classes in my project classpath and when i switced to servlet.ModelAndView, i could see the results on the same page.

Murali.
0
 
lakkarajumuraliAuthor Commented:
multiple ModelAndView classes available in the project classpath, one from Portlet and other from Servlet.
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

  • 3
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now