Ok I'm stumped. I am writing a Spring based app that queries a web service for information to load a SELECT object based on the user's id. I've set up the web.xml and servlet xml files, design the initial page and have a redirect from an index.jsp file (the final system will reside under a Tomcat / IIS config) with a hard coded value for the username for the time being.
Every time I try to run it I get a 404 error and nothing in the Tomcat logs. I am relatively new to JSP / Spring so this is driving me nuts as I can't seem to find the problem.
I have tried removing the reference to the web service calls and still the pages to not load.
What am I missing?
Below is the code minus stylesheets and images:
UserDatabaseProject.java
/**
*
*/
package enterprisesearch.domain;
/**
* #author bob
*
*/
public class UserDatabaseProject
{
private String _msUserName = "";
private String _msDatabaseName = "";
private String _msDatabaseDescription = "";
private String _msProjectName = "";
private String _msProjectDescription = "";
public UserDatabaseProject()
{
}
public UserDatabaseProject(String psUserName, String psDatabaseName, String psDatabaseDescription, String psProjectName, String psProjectDescription)
{
this._msUserName = psUserName;
this._msDatabaseName = psDatabaseName;
this._msDatabaseDescription = psDatabaseDescription;
this.setProjectName(psProjectName);
this.setProjectDescription(psProjectDescription);
}
/**
* #return the _msProjectName
*/
public final String getProjectName()
{
return this._msProjectName;
}
/**
* #param _msProjectName the _msProjectName to set
*/
public final void setProjectName(String psProjectName)
{
this._msProjectName = psProjectName;
}
/**
* #return the _msProjectDescription
*/
public final String getProjectDescription()
{
return this._msProjectDescription;
}
/**
* #param _msProjectDescription the _msProjectDescription to set
*/
public final void setProjectDescription(String psProjectDescription)
{
this._msProjectDescription = psProjectDescription;
}
/**
* #return the _msUserName
*/
public final String getUserName()
{
return this._msUserName;
}
/**
* #param _msUserName the _msUserName to set
*/
public final void setUserName(String psUserName)
{
this._msUserName = psUserName;
}
/**
* #return the _msDatabaseName
*/
public final String getDatabaseName()
{
return this._msDatabaseName;
}
/**
* #param _msDatabaseName the _msDatabaseName to set
*/
public final void setDatabaseName(String psDatabaseName)
{
this._msDatabaseName = psDatabaseName;
}
/**
* #return the _msDatabaseDescription
*/
public final String getDatabaseDescription()
{
return this._msDatabaseDescription;
}
/**
* #param _msDatabaseDescription the _msDatabaseDescription to set
*/
public final void setDatabaseDescription(String psDatabaseDescription)
{
this._msDatabaseDescription = psDatabaseDescription;
}
}
DouglasService.java
/**
*
*/
package enterprisesearch.domain.service;
import java.io.StringReader;
import java.util.Collection;
import java.util.HashMap;
import java.util.Map;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;
import org.apache.cxf.jaxws.JaxWsProxyFactoryBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.w3c.dom.Element;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import gov.sec.com.IDouglas;
import enterprisesearch.domain.UserDatabaseProject;
/**
* #author bob
*
*/
public class DouglasService
{
private IDouglas _mtDouglas;
private static Map<Integer, UserDatabaseProject> _muspUserDatabaseProjects = new HashMap<Integer, UserDatabaseProject>();
public DouglasService(String psDouglasUrl)
{
//String endPointAddress = "http://localhost:8080/Douglas/services/Douglas?wsdl";
//ApplicationContext acContext = new ClassPathXmlApplicationContext("context.xml");
JaxWsProxyFactoryBean factory = new JaxWsProxyFactoryBean();
factory.setServiceClass(IDouglas.class);
factory.setAddress(psDouglasUrl);
this._mtDouglas = (IDouglas) factory.create();
}
public String getSecurityToken(String psUserId)
{
String sReturn = "";
this._mtDouglas.getSecurityToken(psUserId);
return sReturn;
}
public String getProjectOptions(String psProjectName)
{
String sReturn = "";
this._mtDouglas.getProjectOptions(psProjectName);
return sReturn;
}
public String getDatabaseFilters(String psDatabaseName)
{
String sReturn = "";
this._mtDouglas.getDatabaseFilters(psDatabaseName);
return sReturn;
}
public Collection<UserDatabaseProject> getUserDatabaseProjects(String psUserName)
{
String sReturn = "";
String sResult = this._mtDouglas.getUserDatabaseProjects(psUserName);
XPathFactory xfactory = XPathFactory.newInstance();
XPath xPath = xfactory.newXPath();
StringReader sr = new StringReader(sResult);
NodeList databases = null;
try
{
databases = (NodeList) xPath.evaluate("/douglasresponse/responsedata/databases", new InputSource(new StringReader(sResult)), XPathConstants.NODESET);
for (int i = 0; i < databases.getLength(); i++)
{
Element elDatabase = (Element) databases.item(i);
String sUserName = xPath.evaluate("database/username", elDatabase);
String sDatabaseName = xPath.evaluate("database/databasename", elDatabase);
String sDatabaseDescription = xPath.evaluate("database/databasedescription", elDatabase);
String sProjectName = xPath.evaluate("database/projectname", elDatabase);
String sProjectDescription = xPath.evaluate("database/projectdescription", elDatabase);
this._muspUserDatabaseProjects.put(new Integer(i), new UserDatabaseProject(sUserName, sDatabaseName, sDatabaseDescription, sProjectName, sProjectDescription));
}
}
catch(XPathExpressionException ex)
{
System.out.print(ex.getMessage());
}
return _muspUserDatabaseProjects.values();
}
public String executeTextQuery(String psSecurityToken, String psProjectName, String psDatabase, String psQueryText, String psOptions, String psFilters)
{
String sReturn = "";
this._mtDouglas.executeTextQuery(psSecurityToken, psProjectName, psDatabase, psQueryText, psOptions, psFilters);
return sReturn;
}
public String executeGetContent(String psSecurityToken, String psProjects, String psDatabases, String psOptions)
{
String sReturn = "";
this._mtDouglas.executeGetContent(psSecurityToken, psProjects, psDatabases, psOptions);
return sReturn;
}
public String executeGetSimilar(String psSecurityToken, String psProjects, String psDatabases, String psOptions)
{
String sReturn = "";
this._mtDouglas.executeGetSimilar(psSecurityToken, psProjects, psDatabases, psOptions);
return sReturn;
}
}
SearchController.java
package enterprisesearch.web;
import enterprisesearch.domain.UserDatabaseProject;
import enterprisesearch.domain.service.DouglasService;
import java.util.Collection;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
#Controller
public class SearchController
{
//protected final Log logger = LogFactory.getLog(getClass());
private DouglasService dgWebService = new DouglasService("http://localhost:8080/Douglas/services/Douglas");
#RequestMapping("/search.html")
#ModelAttribute("userprojects")
public Collection<UserDatabaseProject> getUserProjects(#RequestParam(value="username", required=true) String psUsername)
{
return this.dgWebService.getUserDatabaseProjects(psUsername);
}
//#RequestMapping("/search.html")
//#ModelAttribute("testmessage")
//public String setMessage()
//{
// return "This is a test!";
//}
}
/WEB-INF/jsp/index.jsp
<jsp:forward page="search.html">
<jsp:param value="lymana" name="username"/>
</jsp:forward>
/WEB-INF/jsp/search.jsp
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="x" uri="http://java.sun.com/jsp/jstl/xml" %>
<%# taglib prefix="spring" uri="http://www.springframework.org/tags" %>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>Enterprise Search</title>
<link href="assets/style_sheets/main.css" rel="stylesheet" type="text/css" />
<script type="text/javascript" language="javascript" src="assets/scripts/controls.js"></script>
</head>
<body>
<form:form method="post" action="" modelAttribute="search">
<table width="100%" border="0" style="border-collapse:collapse; border-spacing: 0px;" cellspacing="0">
<tr id="pageHeader">
<td id="pageHeaderLeft"><img src="assets/images/OCIE_left-1.jpg" style="float:left;" /></td>
<td id="pageHeaderRight"><img src="assets/images/OCIE_right.jpg" /></td>
</tr>
<tr>
<td valign="top" width="50%">
<div id="leftContainer">
<div class="blockHeader">
Text Search
</div>
<div id="TextBlock" class="blockControl">
<label for="taSearchText">Search Text:</label><br />
<textarea id="taSearchText" cols="60" rows="7" style="margin-bottom: .5em;"></textarea>
<br />
<table border="0" style="border-collapse:collapse; border-spacing: 0px;" cellspacing="0">
<tr>
<td width="30%" style="padding: 0em 0em .5em .5em; text-align:right; vertical-align:middle;">
<label for="sltResultsPerPage">Results per page:</label>
</td>
<td width="30%" style="padding: 0em .5em .5em 0em; text-align:left; vertical-align:middle;">
<select id="sltResultsPerPage">
<option value="10">10 per page</option>
<option value="20">20 per page</option>
<option value="50">50 per page</option>
<option value="100">100 per page</option>
</select>
</td>
<td width="40%" rowspan="3" valign="middle" align="center">
<input id="btnSearch" type="button" value="Search" />
</td>
</tr>
<tr>
<td style="padding: 0em 0em .5em .5em; text-align:right; vertical-align:middle;">
<label for="sltSort">Sort results by:</label>
</td>
<td style="padding: 0em .5em .5em 0em; text-align:left; vertical-align:middle;">
<select id="sltSort">
<option value="relevance">Relevance</option>
<option value="dateAsc">Date (Ascending)</option>
<option value="dateDesc">Date (Descending)</option>
</select>
</td>
</tr>
<tr>
<td style="padding: 0em 0em .5em .5em; text-align:right; vertical-align:middle;">
<label for="sltRelevance">Relevance:</label>
</td>
<td style="padding: 0em .5em .5em 0em; text-align:left; vertical-align:middle;">
<select id="sltRelevance">
<option value="90">90% relevant</option>
<option value="80">80% relevant</option>
<option value="70">70% relevant</option>
<option value="60">60% relevant</option>
<option value="50">50% relevant</option>
</select>
</td>
</tr>
</table>
</div><!-- end of textblock -->
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('BooleanBlock');" />
Boolean
</div>
<div id="BooleanBlock" class="blockControl" style="visibility:hidden; display:none;">Boolean Search controls here<br /><br /><br /><br />
</div>
<div class="blockHeader">
<img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('ParametricBlock');" />
Parametric
</div>
<div id="ParametricBlock" class="blockControl" style="visibility:hidden; display:none;">Parametric Search controls here<br /><br /><br /><br />
</div>
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('ClusterBlock');" />
Cluster
</div>
<div id="ClusterBlock" class="blockControl" style="visibility:hidden; display:none;">Cluster results here<br /><br /><br /><br />
</div>
</div>
</td>
<td valign="top" width="50%">
<div id="rightContainer">
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('ProjectsBlock');"/>
Projects
</div>
<div id="ProjectsBlock" class="blockControl">
<label for="sltProjects">Projects:</label><br />
<select id="sltProjects" size="10" onclick="">
<option value="all">All available projects</option>
<c:forEach items="${userprojects}" var="UserDatabaseProject">
<form:option value="${UserDatabaseProject._msProjectName}">${UserDatabaseProject._msProjectDescription}</form:option>
</c:forEach>
</select>
</div>
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('DatabasesBlock');"/>
Databases
</div>
<div id="DatabasesBlock" class="blockControl">
<label for="sltDatabases">Databases:</label><br />
<select id="sltDatabases" size="10" onclick="">
<option value="all">All available databases</option>
<option value="dbTCR20">TCR20 Database Primary</option>
<option value="dbTCR20-1">TCR20 Database Secondary</option>
<option value="dbECC">ECC Emails</option>
</select>
</div>
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('FiltersBlock');"/>
Filters
</div>
<div id="FiltersBlock" class="blockControl">
<label for="sltFilters">Filters:</label><br />
<select id="sltFilters" size="10" onclick="createInput();" multiple="multiple" >
<option value="Comment">TCR20 - Comment</option>
<option value="TCR Subject">TCR20 - Subject</option>
<option value="From Address">ECC - From Address</option>
<option value="ECC Subject">ECC - Subject</option>
<option value="Message Text">ECC - Message Text</option>
</select>
</div>
<div class="blockHeader"><img src="assets/images/RightArrowClosed16x16.jpg" onclick="setAdvancedVisible('SelectedBlock');"/>
<span>Selected Filters</span>
</div>
<div id="SelectedBlock" class="blockControl">
</div>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<hr />
<div>
<div class="resultsHeader">
Search Results
</div>
<div class="resultsControl" style="margin-bottom: 15px;">
</div>
</div>
</td>
</tr>
<tr>
<td id="footer" colspan="2"><hr />Some footer stuff goes here!</td>
</tr>
</table>
</form:form>
</body>
</html>
web.xml
<?xml version="1.0" encoding="ISO-8859-1"?>
<web-app version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<!-- Register a servlet that despatches requests to registered controllers -->
<servlet>
<servlet-name>es</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<!-- Send all .html files to the Spring dispatcher servlet -->
<servlet-mapping>
<servlet-name>es</servlet-name>
<url-pattern>*.html</url-pattern>
</servlet-mapping>
<!-- Define the web application entry point -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
es.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"
xmlns:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-2.5.xsd">
<!-- Auto-detect controllers in this package -->
<context:component-scan base-package="enterprisesearch.web"/>
<!-- Prepend /WEB-INF/jsp/ and append .jsp to the view name -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
</beans>
Your controller is bound to <contextname>/search.html, not index.html - <contextname> referring to the context that Tomcat maps your application to, which usually is the name of the WAR file but can be anything if you have configured Tomcat specially.
Turn up Spring's logging and you will see it logging warnings when you request a URL that it has no mapping for.
your controller was worng, you must return a ModalAndView or NameOfView not Collection<UserDatabaseProject>
please try this :
#RequestMapping("/search.html")
#ModelAttribute("userprojects")
public ModelAndMap getUserProjects(#RequestParam(value="username", required=true) String psUsername){
ModelMap modelMap = new ModelMap();
modelMap.put("userprojects", this.dgWebService.getUserDatabaseProjects(psUsername));
return new ModelAndView("index", modelMap);
}
Follow any good tutorial on spring mvc.
your return type should be either ModelAndView or its related type (since you are using InternalResourceViewResolved) or the String name of view.
In case of Rest Based approach or ajax you can return the data as collection (which get converted into json). For this approach you need to mark your controller as #RestController on class level or #ResponseBody on method level. This approach is mostly used in Ajax calls in which you need to iterate through the json response received and set the data on that page.
In Spring mvc based approach you need to add all the objects in the ModelAndView and set the view name as below. Then you can access the objects on that view using el.
#RequestMapping("/search.html")
#ModelAttribute("userprojects")
public ModelAndView getUserProjects(#RequestParam(value="username", required=true) String psUsername){
ModelAndView modelAndView = new ModelAndView();
// add all the required data which you need on next view page
modelAndView.addObject("userprojects", this.dgWebService.getUserDatabaseProjects(psUsername));
// set the view name which needs to be displayed
modelAndView.setViewName("search");
return modelAndView
}
In Jsp access the userprojects as:
${userprojects._msProjectName}
Related
I am trying to build a simple select and Option list in thymeleaf, but i keep getting the error
Neither BindingResult nor plain target object for bean name 'BOLForm' available as request attribute
I am pretty sure there is something wrong with my bol.html. But not able to figure out the missing mappings.
Below is my Controller:
#Controller
public class BillOfLadingController {
#Autowired
private DepotList depotList;
#GetMapping("/BillOfLading")
public String getBOLForm(){
return "bol";
}
#PostMapping("/BillOfLading")
public String Login(#ModelAttribute(name="BOLForm") BOLForm bolForm,Model model) {
model.addAttribute("BOLForm", bolForm);
List<DepotDetailEntity> depotDropDown = depotList.getDepots().getDepotDetail();
if(depotDropDown.size() == 0) {
return "login";
}
model.addAttribute("depots", depotDropDown);
return "bol";
}
}
The Form Class
#Component
public class BOLForm {
private String BOL;
private String depotId;
public String getBOL() {
return BOL;
}
public void setBOL(String bOL) {
BOL = bOL;
}
public String getDepotId() {
return depotId;
}
public void setDepotId(String depotId) {
this.depotId = depotId;
}
}
the bol.html
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head>
<meta charset="ISO-8859-1">
<title>BillOfLading Request Page</title>
</head>
<body>
<h1>BillOfLading Report</h1>
<form th:action="#{/BillOfLading}" th:object="${BOLForm}" method="post">
<label for="bol">BOL No.</label>
<input type="text" id="bol" name="bol">
<br/>
<table>
<tr>
<td>Select DC:</td>
<td>
<select th:field="*{depotId}">
<option value=""> -- </option>
<option th:each="depot : ${depots}"
th:value="${depot.depotId}"
th:utext="${depot.depotName}"/>
</select>
</td>
</tr>
<tr>
<td><input name="submit" type="submit" value="submit" /></td>
</tr>
</table>
</form>
</body>
</html>
When I replace my bol.html as below, it works:
<form th:action="#{/BillOfLading}" th:object="${BOLForm}" method="post">
<label for="bol">BOL No.</label>
<input type="text" id="bol" name="bol">
<br/>
<label for="depotId">DepotID </label>
<input type="text" id="depotId" name="depotId">
<br/>
In the controller, you need to add the BOLForm object as an attribute of the model:
#GetMapping("/BillOfLading")
public String getBOLForm(Model model){
model.addAttribute("BOLForm", new BOLForm());
return "bol";
}
I've got problem with my project. (It is my first Spring project, sorry for messy code). I want to insert values from form to DB, (for that moment they are working inputs called "nameHosp", "namePat", "surnamePat","peselPat"). And the problem is passing value from select options form. Result of submiting is "null" in column called "nameHosp"
Form
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
`<%# taglib prefix="sf" uri="http://www.springframework.org/tags/form"%>
`
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<sf:form action="${pageContext.request.contextPath}/create"
method="post" modelAttribute="combinedCommand" >
<table style="margin-right: auto; margin-left: auto;" width="100%">
<tr><sf:form modelAttribute="combinedCommand">
<td colspan="5"><strong>Szpital zamawiający</strong><br /> <br />
<sf:select path="${getHospitals}">
<sf:option value="NONE"> --Wybierz Szpital--</sf:option>
<sf:options items="${hospitals}" itemValue="nameHosp" itemLabel="nameHosp"></sf:options>
</sf:select></sf:form>
</tr>
<tr>
<th>Dane pacjenta</th>
<th colspan="4">Zamówienie</th>
</tr>
<tr>
<td>Imię:<br /> <sf:input path="${namePat}" name="namePat"
type="text" />
</td>
<td>KKCz</td>
<td><input name="iloscKKCz" size="1" type="text" /> jednostek.
</td>
<td><input name="ED5" type="checkbox" value="86" />
Ubogoleukocytarny</td>
<td><input name="EC2" type="checkbox" value="26" />
Napromieniowany</td>
</tr>
<tr>
<td>Nazwisko:<br /> <sf:input path="${surnamePat}"
name="surnamePat" type="text" />
</td>
<td>PLT</td>
<td><input name="iloscPLT" size="1" type="text" /> jednostek.
</td>
<td><input name="ED5" type="checkbox" value="86" />
Ubogoleukocytarny</td>
<td><input name="EC2" type="checkbox" value="26" />
Napromieniowany</td>
</tr>
<tr>
<td>PESEL:<br /> <sf:input path="${peselPat}" name="peselPat"
type="text" />
</table>
</sf:form>
Controller
#Controller
public class Controlling {
#Autowired
private Servicu servicu;
#Autowired
public void setServicu(Servicu servicu) {
this.servicu = servicu;
}
#RequestMapping("/")
public String showHome(Model model) {
return "home";
}
#RequestMapping("/orderForm")
public String showForm(Model model){
List<Hospitals> hospital = servicu.getCurrent();
model.addAttribute("combinedCommand", new CombinedCommand());
model.addAttribute("hospitals", hospital);
model.addAttribute("ordersPatient", new OrdersPatient());
return "orderForm";
}
#RequestMapping(value="/create", method=RequestMethod.POST)
public String doCreate( Hospitals hospitals,
Model model,
OrdersPatient ordersPatient,
Orders orders,
BindingResult result) {
if(result.hasErrors()) {
return "error";
}else{
model.addAttribute("nameHosp",hospitals);
// model.addAttribute("combinedCommand", new CombinedCommand());
model.addAttribute("ordersPatient", new OrdersPatient());
servicu.create(ordersPatient);
// servicu.create(orders);
return "success";
}
DAO
#Component("offersDAO")
public class OffersDAO {
private NamedParameterJdbcTemplate jdbc;
#Autowired
public void setDataSource(DataSource jdbc) {
this.jdbc = new NamedParameterJdbcTemplate(jdbc);
}
public List<Hospitals> getHosps() {
return jdbc.query("select nameHosp from hospitals", new RowMapper<Hospitals>() {
public Hospitals mapRow(ResultSet rs, int rowNum) throws SQLException {
Hospitals hospital = new Hospitals("nameHosp");
hospital.setNameHosp(rs.getString("nameHosp"));
return hospital;
}
});
}
public boolean createPatient(OrdersPatient ordersPatient){
BeanPropertySqlParameterSource param = new BeanPropertySqlParameterSource(ordersPatient);
return jdbc.update("insert into patient (idOrd,nameHosp,namePat,surnamePat,peselPat) values (:idOrd,:nameHosp,:namePat,:surnamePat,:peselPat)", param)==1;
}
Try to add name="nameHosp" to the select. Like this.
<sf:select path="${getHospitals}" name="nameHosp">
<sf:option value="NONE"> --Wybierz Szpital--</sf:option>
<sf:options items="${hospitals}" itemValue="nameHosp" itemLabel="nameHosp"></sf:options>
</sf:select></sf:form>
I am developing an application with AngularJS and Spring MVC. Everything is working fine but my object is going as null to the Spring Controller so it's returning null. I just don`t know how to make the AngularJS populates the object.
I will post the code here.
AngularJS
<%#taglib prefix='c' uri='http://java.sun.com/jsp/jstl/core'%>
<%#taglib prefix="spring" uri="http://www.springframework.org/tags"%>
<%#taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!doctype html>
<html>
<head>
<title>Settings</title>
<link rel="stylesheet" href="css/main.css">
<link rel="stylesheet" href="css/workflow.css">
<link rel="stylesheet" href="css/upload.css">
<link rel="stylesheet" href="http://netdna.bootstrapcdn.com/bootstrap/3.0.3/css/bootstrap.min.css">
<link rel="shortcut icon" href="images/logo-small.png" />
</head>
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.3.14/angular.min.js"></script>
<script type="text/javascript">
var app = angular.module('formSubmit', []);
app.controller('FormSubmitController', function($scope, $http) {
$scope.formData = {};
$scope.headerText = 'AngularJS Post Form Spring MVC example: Submit below form';
$scope.submit = function() {
var formData = {
"name1" : "nome 1",
"name2" : "nome 2",
"name3" : "nome 3",
};
var response = $http.post('http://localhost:8080/fire-fatca-web/SubmitMock.html', formData); //passing mockForm
response.success(function(data, status, headers, config) {
/* alert('Success!' + JSON.stringify({
data: $scope.formData //used formData model here
}) ); */
$scope.mockForm = data;
$scope.formData.push(data);
});
response.error(function(data, status, headers, config) {
alert("Exception details: " + JSON.stringify({
data: $scope.formData //used formData model here
}));
})
};
});
</script>
<style>
input.ng-invalid {
border: 2px red solid;
}
</style>
<body data-ng-app="formSubmit">
<div class="container">
<div class="col-sm-8 col-sm-offset-2">
<form data-ng-submit="submit()" name="myForm" data-ng-controller="FormSubmitController">
<!-- novalidate prevents HTML5 validation since we will be validating ourselves -->
<table border="1">
<tr>
<td colspan="2">
<label>Name Line 1:</label>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-group">
<input type="text" name="name1" class="form-control" data-ng-model="formData.name1" required ng-Maxlength="40">
<p ng-show="myForm.name1.$error.required" class="help-block">Name is required.</p>
<p ng-show="myForm.name1.$error.maxlength" class="help-block">Maximum 40 characters</p>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<label>Name Line 2:</label>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-group">
<input type="text" name="name2" class="form-control" data-ng-model="formData.name2" ng-Maxlength="40">
<p ng-show="myForm.name2.$error.maxlength" class="help-block">Maximum 40 characters</p>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<label>Name Line 3:</label>
</td>
</tr>
<tr>
<td colspan="2">
<div class="form-group">
<input type="text" name="name3" class="form-control" data-ng-model="formData.name3" ng-Maxlength="40">
<p ng-show="myForm.name3.$error.maxlength" class="help-block">Maximum 40 characters</p>
</div>
</td>
</tr>
<tr>
<td colspan="2">
<h4>You submitted below data through post:</h4>
<pre>Form data ={{formData}}</pre>
</td>
</tr>
<tr>
<td colspan="2">
<p>Response: {{mockForm}}</p>
</td>
</tr>
<tr>
<td colspan="2">
<!-- SUBMIT BUTTON -->
<button type="submit" class="btn btn-primary" ng-disabled="myForm.$invalid">Submit</button>
</td>
</tr>
</table>
</form>
</div>
</div>
</body>
</html>
Spring Controller
#Controller
public class MockController {
private Logger log = LoggerFactory.getLogger(MockController.class);
#RequestMapping("/mock")
public String getSettingsPage(){
return "mock";
}
#RequestMapping(value = "/SubmitMock", method = RequestMethod.POST)
public #ResponseBody String getMock(#RequestBody MockForm mockForm){
StringBuilder reponseData = new StringBuilder();
reponseData.append("Name1: "+ mockForm.getName1()+" ");
reponseData.append("Name2: "+ mockForm.getName2()+" ");
reponseData.append("Name3: "+ mockForm.getName3());
log.debug(reponseData.toString());
return reponseData.toString();
}
The return is aways: Name1: null, Name2: null and Name3: null
I know that I need to populate my mockForm with my formData. It was suggested me to do this:
var response = $http.post('http://localhost:8080/fire-fatca-web/SubmitMock.html', {mockform: formData});
But when I use that piece of code above my Controller Stops responding, I don't know why, maybe Sintaxe Error, I have no idea. Any help?
EDIT:
MockForm.java
package com.opessoftware.beans;
public class MockForm {
private String name1;
private String name2;
private String name3;
public String getName1() {
return name1;
}
public void setName1(String name1) {
this.name1 = name1;
}
public String getName2() {
return name2;
}
public void setName2(String name2) {
this.name2 = name2;
}
public String getName3() {
return name3;
}
public void setName3(String name3) {
this.name3 = name3;
}
}
EDIT 2:
Finally I solve the problem. my ng-data-model was formData.name1, formData.name2 and formData.name3. I changed for name1, name2 and name3. Problem solved. Thank you all!
My problem:
In my method save, i receive a inscriptionsForm but it contains is null; inscriptionsForm.getInscriptions() == null, Why?
I have tried multiple ways such as:
<div th:each="inscription, stat : *{inscriptions}">
<div th:each="inscription, stat : *{inscriptionsForm.inscriptions}">
<div th:each="inscription : *{inscriptionsForm.inscriptions}">
but is always null.
My code:
/** The Class TrainingTypeListController. */
#Controller
public class InscriptionListController {
/** The Constant TRAINING_VIEW_NAME. */
private static final String TRAINING_VIEW_NAME = "training/inscriptions";
/** The TrainingTypeService. */
#Autowired
private TrainingService trainingService;
/** The trainingTypes. */
public static List<Inscription> inscriptions;
/** The trainingTypes. */
private Training training;
/**
* Instantiates a new training Controller.
*/
public InscriptionListController() {
// Default empty constructor.
}
/**
* Show TrainingType List.
*
* #param model
* the model
* #return the string the view
*/
#RequestMapping(value = "trainingList/inscriptions/{trainingId}")
public String trainings(#PathVariable Long trainingId, Model model) {
//List of inscriptions
inscriptions = trainingService.getInscriptionsByTrainingId(trainingId);
model.addAttribute("inscriptions", inscriptions);
training = trainingService.findById(trainingId);
model.addAttribute("training", training);
InscriptionsForm inscriptionsForm = new InscriptionsForm();
inscriptionsForm.setInscriptions(inscriptions);
model.addAttribute(inscriptionsForm);
//System.out.println("-> " + inscriptionsForm);
//System.out.println("-> " + inscriptionsForm.getInscriptions());
return TRAINING_VIEW_NAME;
}
/**
* List of inscriptions.
*
* #return List<Inscription>
*/
#ModelAttribute("inscriptions")
public List<Inscription> inscriptions() {
return inscriptions;
}
/**
* List of inscriptions.
*
* #return Inscription
*/
#ModelAttribute("training")
public Training training() {
return training;
}
#RequestMapping(value = "trainingList/inscriptions/save", method = RequestMethod.POST)
public String save(#Valid #ModelAttribute InscriptionsForm inscriptionsForm) {
System.out.println("formulario: " + inscriptionsForm);
System.out.println("inscriptionsForm: " + inscriptionsForm.getInscriptions());
List<Inscription> inscriptions = inscriptionsForm.getInscriptions();
System.out.println("****\n " + InscriptionListController.inscriptions);
System.out.println("name: " + InscriptionListController.inscriptions.get(0).getAccount().getName());
System.out.println("note: " + InscriptionListController.inscriptions.get(0).getNote());
if(null != inscriptions && inscriptions.size() > 0) {
InscriptionListController.inscriptions = inscriptions;
for (Inscription inscription : inscriptions) {
System.out.printf("%s \t %s \n", inscription.getAccount().getName());
}
}
System.out.println("---------------------------------------------- ");
return "redirect:/trainingList";
}
}
FORM
/** The InscriptionsForm. */
public class InscriptionsForm {
/** The Inscription List. */
private List<Inscription> inscriptions;
/** The getInscriptions. */
public List<Inscription> getInscriptions() {
return inscriptions;
}
/** The setInscriptions. */
public void setInscriptions(List<Inscription> inscriptions) {
this.inscriptions = inscriptions;
}
}
HTML
<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org"
xmlns:tiles="http://www.thymeleaf.org"
xmlns:sec="http://www.thymeleaf.org/thymeleaf-extras-springsecurity3">
<head>
<title th:text="#{inscriptions.title}"></title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link href="../../../resources/css/bootstrap.min.css" rel="stylesheet"
media="screen" th:href="#{/resources/css/bootstrap.min.css}" />
<link href="../../../resources/css/core.css" rel="stylesheet"
media="screen" th:href="#{/resources/css/core.css}" />
<script src="http://code.jquery.com/jquery-latest.js"></script>
<script src="../../../resources/js/bootstrap.min.js"
th:src="#{/resources/js/bootstrap.min.js}"></script>
</head>
<body>
<!-- Generic Header -->
<div th:replace="fragments/header :: header(active='training')"> </div>
<fieldset>
<!-- Verify if exits Inscriptions -->
<div th:unless="${#lists.isEmpty(inscriptionsForm.inscriptions)}">
<h2 class="text-center"
th:text="#{inscription.inscriptionlist}+${training.name}">List
of Training Types</h2>
<!-- Table List of Inscriptions -->
<form method="post" th:action="#{/trainingList/inscriptions/save}"
th:object="${inscriptionsForm}">
<table class="table table-striped table-hover form-narrow ">
<thead>
<tr>
<th th:text="#{name}">Name</th>
<th th:text="#{inscription.attend}">Attend</th>
<th th:text="#{inscription.note}">Note</th>
<th th:text="#{inscription.pass}">Pass</th>
<th th:text="#{inscription.unsubscribe}">Baja</th>
</tr>
</thead>
<tbody>
<!-- Table Inscriptions -->
<tr th:each="inscription : ${inscriptionsForm.inscriptions}">
<td th:text="${inscription.account.name}">name</td>
<td><input type="checkbox"
th:checked="${inscription.attend}"
th:title="#{inscription.infoAttend}" /></td>
<td><textarea id="note" th:text="${inscription.note}"
th:placeholder="#{note}" rows="3" cols="40"> Note </textarea></td>
<td><input type="checkbox" th:checked="${inscription.pass}"
th:title="#{inscription.infoPass}" /></td>
<td><input type="checkbox"
th:checked="${inscription.unsubscribe}"
th:title="#{inscription.infoUnsubscribe}" /></td>
</tr>
</tbody>
</table>
<!-- Button Modify, visible if a checkbox enable is pressed -->
<div class="text-center">
<button type="submit" class="btn btn-success btn-lg"
th:text="#{inscription.confirm}">Confirm</button>
</div>
</form>
</div>
</fieldset>
</body>
</html>
My error was in entity inscription because of the default contructor is not public, it was protected.
th:field catch the value of field in a table and create a new inscription a set attribute with value you put in a table:
th:field="*{inscriptions[__${stat.index}__].attend}"
My html:
<!-- Table List of Inscriptions -->
<form method="post" th:action="#{/trainingList/inscriptionList/save}"
th:object="${inscriptionsForm}">
<table class="table table-striped table-hover form-narrow ">
<thead>
<tr>
<th th:text="#{name}">Name</th>
<th th:text="#{inscription.attend}">Attend</th>
<th th:text="#{inscription.note}">Note</th>
<th th:text="#{inscription.pass}">Pass</th>
<th th:text="#{inscription.unsubscribe}">Baja</th>
</tr>
</thead>
<tbody th:each="inscription, stat : *{inscriptions}">
<tr>
<td th:text="${inscription.account.name}">name</td>
<td class="text-center"><input
th:field="*{inscriptions[__${stat.index}__].attend}"
th:value="${inscription.attend}" type="checkbox"
th:checked="${inscription.attend}"
th:title="#{inscription.infoAttend}" /></td>
<td><textarea class="form-control"
th:field="*{inscriptions[__${stat.index}__].note}" id="note"
th:text="${inscription.note}" th:placeholder="#{note}" rows="3"
cols="40"> Note </textarea></td>
<td class="text-center"><input
th:field="*{inscriptions[__${stat.index}__].pass}"
type="checkbox" th:checked="${inscription.pass}"
th:title="#{inscription.infoPass}" /></td>
<td class="text-center"><input
th:field="*{inscriptions[__${stat.index}__].unsubscribe}"
type="checkbox" th:checked="${inscription.unsubscribe}"
th:title="#{inscription.infoUnsubscribe}" /></td>
</tr>
</tbody>
</table>
<!-- Button Confirm, confirm the list of inscription -->
<div class="text-center">
<button type="submit" class="btn btn-success btn-lg" th:name="save"
th:text="#{inscription.confirm}"
th:title="#{inscription.infoConfirm}">Confirm</button>
</div>
</form>
</div>
I have 2 pages, the first where the user insert the data, and the second where the user confirm the data (or can go back to the edit page).
The problem is that when validation fails, all the values in fields are erased. Somebody suggested to use prepare(), but It's a lot of work to copy all the fields, does it exist a faster way to repopulate all the fields?
the first page (formDatiUtente.jsp):
<%# page language="java" contentType="text/html;"
import="java.util.*,it.alm.bean.*,it.alm.delegate.*;"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href="${pageContext.request.contextPath}/css/stile1.css" rel="stylesheet" type="text/css" />
<title>Registrazione account</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/scriptFormUtente.js"></script>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/scriptDWR.js"></script>
<script type='text/javascript' src='/gestUtenzeLDAP/dwr/engine.js'></script>
<script type='text/javascript' src='/gestUtenzeLDAP/dwr/util.js'></script>
<script type='text/javascript' src='/gestUtenzeLDAP/dwr/interface/DwrAjaxServiceImplEnti.js'></script>
<script type='text/javascript' src='/gestUtenzeLDAP/dwr/interface/DwrAjaxServiceImplTipoUfficio.js'></script>
<script type='text/javascript' src='/gestUtenzeLDAP/dwr/interface/DwrAjaxServiceImplUfficio.js'></script>
<script type='text/javascript' src='/gestUtenzeLDAP/dwr/interface/ComboBean.js'></script>
</head>
<body>
<jsp:include page="header.jsp"/>
<s:actionerror />
<s:form name="formDatiUtente" action="inviaRichiesta.action" method="post" theme="simple" validate="true">
<%
String pathContest=request.getContextPath();
//Collection clRichAna = (ArrayList)request.getAttribute("clRichAna");
//String totRich=(clRichAna!=null?""+clRichAna.size():"0");
//Collection comuni = (ArrayList)request.getAttribute("comuni");
List <Comune> comuni = CreazioneUtenzaDelegate.getInstance().getComuni();
%>
<center>
<s:fielderror></s:fielderror>
<table width="48%" class="LISTA" border="0" cellPadding="3" cellSpacing="5" align="center">
<tr>
<td width="35%">
<p class="testodx">
<s:text name="label.cognome" />
</p>
</td>
<td align="right">
<p class="testosx">
<s:textfield name="cognome" id="idCognome"
size="30" value="%{anagraficaVDR.cognome}" />
</p>
</td>
</tr>
<tr>
<td align="right">
<p class="testodx"><s:text name="label.nome" /></p>
</td>
<td align="left">
<s:textfield name="nome" id="idNome" size="30" value="%{anagraficaVDR.nome}" />
<td>
</tr>
<tr>
<td>
<p class="testodx"><s:text name="label.dataNascita" /></p>
</td>
<td>
<s:date name="%{anagraficaVDR.dataNascita}" format="dd/MM/yyyy" var="dataFormattata" />
<s:textfield name="dataNascita" size="12"
value="%{#dataFormattata}" />
<br>
<p class="testosuggerimento">
<s:text name="label.ddmmyyyy" />
</p>
</td>
</tr>
<tr>
<td>
<p class="testodx"><s:text name="label.qualifica" /></p>
</td>
<td>
<s:select
style=" width : 207px;"
list="listaQualifiche"
listKey="idQualifica"
listValue="descrizione"
name="qualificaSelezionata"
value="%{anagraficaVDR.qualifica.idQualifica}"
/>
</td>
</tr>
<tr>
<td>
<p class="testodx"> Comune: </p>
</td>
<td>
<s:select
headerKey="-1" headerValue="Seleziona..."
style=" width : 207px;"
id="idListaComuni"
list="listaComuni"
listKey="codComune"
listValue="descrizione"
onChange="setReloadEnti()"
name="comuneSelezionato"
value="%{anagraficaVDR.ufficio.comune.codComune}"
/>
</td>
<tr>
<td>
<p class="testodx">Ente:</p>
</td>
<td>
<s:select
list="listaEnte"
listKey="idValue"
listValue="value"
name="ente"
onChange="setReloadTipoUfficio()"
id="identi"
value="%{anagraficaVDR.ufficio.tipoufficio.ente.idEnte}"
style=" width : 207px;"
/>
</td>
</tr>
<tr>
<td>
<p class="testodx">Tipo Ufficio:</p>
</td>
<td>
<s:select
list="listaTipoUffici"
listKey="idValue"
listValue="value"
name="tipoufficio"
onChange="setReloadUfficio()"
id="idtipouff"
value="%{anagraficaVDR.ufficio.tipoufficio.idTipoUfficio}"
style=" width : 207px;"/>
</td>
</tr>
<tr>
<td>
<p class="testodx">Ufficio:</p>
</td>
<td>
<s:select
list="listaUffici"
listKey="idValue"
listValue="value"
name="ufficio"
id="iduff"
value="%{anagraficaVDR.ufficio.idufficio}"
style=" width : 207px;"/>
</td>
</tr>
<tr>
<td>
<p class="testodx"><s:text name="label.telefono_Ufficio_reparto" /></p>
</td>
<td>
<s:textfield name="telefono" id="idTelefono_Ufficio_reparto" size="30" value="%{anagraficaVDR.telefono}"/>
</td>
</tr>
<tr>
<td>
<p class="testodx"><s:text name="label.email" /></p>
</td>
<td>
<s:textfield name="email" id="idEmail" size="30" value="%{emailVDR}"/>
<s:text name="label.#" />
<s:select
headerKey="-1" headerValue="Seleziona..."
list="dominiMail"
listKey="descrizione"
listValue="descrizione"
name="ilTuodominio_Email"
value="ilTuodominio_EmailVDR" />
</td>
</tr>
<tr>
<td>
<p class="testodx"><s:text name="label.confermaEmail" /></p>
</td>
<td>
<s:textfield name="confermaEmail" id="idConfermaEmail" size="30" value="%{emailVDR}" onfocus="disabilitaIncolla()"/>
<s:text name="label.#" />
<s:select
headerKey="-1" headerValue="Seleziona..."
list="dominiMail"
listKey="descrizione"
listValue="descrizione"
name="ilTuodominio_EmailConferma"
value="ilTuodominio_EmailVDR" />
</td>
</tr>
<tr>
<td>
<p class="testodx"><s:text name="label.ip" /></p>
</td>
<td>
<s:textfield name="ip" id="idIp" size="30" value="%{anagraficaVDR.ip}"/>
<br>
<p class="testosuggerimento"> <s:text name="label.testoip" /></p>
</td>
</tr>
<tr>
<td class="right">
<s:text name="label.checkbox" />
</td>
<td class="left">
<s:checkboxlist list="listaApplicazioni"
listKey="idApplicazione"
listValue="descrizione"
name="applicazioniSelezionate"
value="applicazioniSelezionateDefault"
cssStyle="vertical"/>
</td>
</tr>
</table>
<br>
<s:if test="!gestioneAmministratore">
<s:submit method="execute" cssClass="bottone" key="label.invia" align="center" />
</s:if>
</center>
</s:form>
</body>
</html>
That after the submit go here (visualizzaDatiRichiesta.jsp), I use hidden value to copy the data when the user go back to the previous page (it's not the best way I suppose, but I inherit part of the code from a co-worker):
<%# page language="java" contentType="text/html;"
import="java.util.*,it.alm.bean.*,it.alm.delegate.*;"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<link href="${pageContext.request.contextPath}/css/stile2.css" rel="stylesheet" type="text/css" />
<title>Riepilogo dati richiesta</title>
<script type="text/javascript" src="${pageContext.request.contextPath}/js/scriptFormUtente.js"></script>
</head>
<% String pathContest=request.getContextPath();
%>
<body>
<jsp:include page="headerGenerico.jsp"/> <br><br><br>
<s:actionerror />
<s:form action="registrazione.action" method="post" theme="simple">
<s:hidden name="anagraficaVDR.cognome" value="%{cognome}" />
<s:hidden name="anagraficaVDR.nome" value="%{nome}" />
<s:hidden name="anagraficaVDR.dataNascita" value="%{dataNascita}" />
<s:hidden name="anagraficaVDR.qualifica.idQualifica" value="%{qualificaSelezionata}" />
<s:hidden name="anagraficaVDR.telefono" value="%{telefono}" />
<s:hidden name="anagraficaVDR.email" value="%{email}" />
<s:hidden name="anagraficaVDR.ip" value="%{ip}" />
<s:hidden name="comuneSelezionatoVDR" value="%{comuneSelezionato}" />
<s:hidden name="enteSelezionatoVDR" value="%{ente}" />
<s:hidden name="tipoUfficioSelezionatoVDR" value="%{tipoufficio}" />
<s:hidden name="ufficioSelezionatoVDR" value="%{ufficio}" />
<s:hidden name="anagraficaVDR.ufficio.comune.codComune" value="%{comuneSelezionato}" />
<s:hidden name="anagraficaVDR.ufficio.tipoufficio.ente.idEnte" value="%{ente}" />
<s:hidden name="anagraficaVDR.ufficio.tipoufficio.idTipoUfficio" value="%{tipoufficio}" />
<s:hidden name="anagraficaVDR.ufficio.idufficio" value="%{ufficio}" />
<s:hidden name="qualificaSelezionataDescrizioneVDR" value="%{qualificaSelezionataDescrizione}" />
<s:hidden name="descrizioneTipoUfficioEUfficioVDR" value="%{descrizioneTipoUfficioEUfficio}" />
<s:hidden name="ilTuodominio_EmailVDR" value="%{ilTuodominio_Email}" />
<s:hidden name="applicazioniSelezionateVDR" value="%{applicazioniSelezionate}" />
<s:hidden name="applicazioniSelezionateDescVDR" value="%{applicazioniSelezionateDesc}" />
<center>
<div class= "divCornicePrimoBlocco">
<table width="900" class="PRIMORIQUADRO1" border="0" cellspacing="5" cellpadding="0">
<tr>
<th align="center" colspan="2">
<h3>Riepilogo dati richiesta</h3>
</th>
</tr>
<tr >
<td>
<s:text name="label.cognome2"/><p class="testoColorato"><s:property value="cognome"/></p>
<p> .............................................................................................................................</p>
</td>
</tr>
<tr>
<td>
<s:text name="label.nome2" /><p class="testoColorato"><s:property value="nome"/></p>
<p> ..................................................................................................................................</p>
</td>
</tr>
<tr>
<td>
<s:text name="label.dataNascita2" ></s:text><p class="testoColorato1"><s:date format="dd/MM/yyyy" name="dataNascita"/></p>
<p> .....................................................................................................................</p>
</td>
</tr>
<tr>
<td>
<s:text name="label.qualifica2"></s:text><p class="testoColorato"><s:property value="qualificaSelezionataDescrizione"/></p>
<p> ..............................................................................................................................</p>
</td>
</tr>
<tr>
<td>
<s:text name="label.ufficio_Reparto_di_appartenenza2" /><p class="testoColorato2"><s:property value="descrizioneTipoUfficioEUfficio"/></p>
<p> .......................................................................................</p>
</td>
</tr>
<tr>
<td>
<s:text name="label.telefono_Ufficio_reparto2" /><p class="testoColorato2"><s:property value="telefono"/></p>
<p > .........................................................................................................</p>
</td>
</tr>
<tr>
<td >
<s:text name="label.email2" /><p class="testoColorato"><s:property value="email"/>#<s:property value="ilTuodominio_EmailDesc"/></p>
<p > .................................................................................................................................</p>
</td>
</tr>
<tr>
<td>
<s:text name="label.ip2" /><p class="testoColorato3"><s:property value="ip"/></p>
<p> ................................................................................</p>
</td>
</tr>
<tr>
<td>
<s:label>Applicativo richiesto</s:label><p class="testoColorato2"><s:property value="applicazioniSelezionateDesc"/></p>
<p > .............................................................................................................</p>
</td>
</tr>
</table>
</div><br>
<div align="right">
<s:submit value="Crea documento" class="bottoneConferma" action="stampaRichiestaPdf" onClick="javascript:creaDocumentoPdf();"/>
<s:submit id="idBottoneConferma" value="Conferma" class="bottoneConferma" action="inserisciRichiestaInDB" disabled="true"/>
<s:submit value="Modifica dati richiesta" class="bottoneModifica" action="inserimentoDati" />
</div>
</center>
</s:form>
</body>
</html>
So, let's pass to the action, this is relative to the first jsp (this extend another action):
public class InserimentoDatiAction extends RegisterAction implements Preparable {
private static final long serialVersionUID = 1L;
public InserimentoDatiAction()
{
}
public String execute()
{
refreshDWR();
return "success";
}
public void refreshDWR()
{
String idComune = null;
try
{
idComune = getAnagraficaVDR().getUfficio().getComune().getCodComune();
}
catch (NullPointerException e)
{
//qualche campo � incompleto, le combobox non vengono caricate
}
if ( idComune != null)
{
DwrAjaxServiceImplEnti dwrEnte = new DwrAjaxServiceImplEnti();
this.setListaEnte( dwrEnte.get_Ente( idComune ) );
String idEnte = getAnagraficaVDR().getUfficio().getTipoufficio().getEnte().getIdEnte();
if ( idEnte != null)
{
DwrAjaxServiceImplTipoUfficio dwrTipoUff = new DwrAjaxServiceImplTipoUfficio();
this.setListaTipoUffici( dwrTipoUff.get_TipoUfficio(idComune, idEnte) );
String idTipoUff = getAnagraficaVDR().getUfficio().getTipoufficio().getIdTipoUfficio();
if ( idTipoUff != null)
{
DwrAjaxServiceImplUfficio dwrUff = new DwrAjaxServiceImplUfficio();
this.setListaUffici( dwrUff.get_Ufficio(idComune, idEnte, idTipoUff));
}
}
}
}
#Override
public void prepare() throws Exception
{
this.setDominiMail( CreazioneUtenzaDelegate.getInstance().getEmails() );
this.setListaComuni( CreazioneUtenzaDelegate.getInstance().getComuni() );
this.setListaApplicazioni( CreazioneUtenzaDelegate.getInstance().getApplicazioni() );
this.setListaQualifiche( CreazioneUtenzaDelegate.getInstance().getQualifiche() );
this.getSession().put("listaApplicazioni", this.getListaApplicazioni());
this.getSession().put("listaQualifiche", this.getListaQualifiche());
}
public boolean isGestioneAmministratore()
{
return false;
}
}
This is relative to the second jsp (the confirmation page):
public class InviaRichiestaAction extends ActionSupport implements Preparable, SessionAware
{
private static final long serialVersionUID = 1L;
private String cognome;
private String nome;
private Date dataNascita;
private List<Qualifica> listaQualifiche;
private String qualificaSelezionata;
private String qualificaSelezionataDescrizione;
private String comuneSelezionato;
private String ente;
private String tipoufficio;
private String ufficio;
private String telefono;
private String email;
private String confermaEmail;
private String ilTuodominio_Email;
private String ilTuodominio_EmailConferma;
private String ip;
private String applicazioniSelezionate;
private String applicazioniSelezionateDesc;
private String identi;
private static List<ComboBean> listaTipoUfficio = new ArrayList<ComboBean>();
private static List<ComboBean> listaUfficio = new ArrayList<ComboBean>();
//questo blocco di variabili anche se non è usato sta qui
//per non generare errori di validazione:
private List<Comune> listaComuni = new ArrayList<Comune>();
private List<ComboBean> listaEnte = new ArrayList<ComboBean>();
private List<Email> dominiMail = new ArrayList<Email>();
private List<ComboBean> listaTipoUffici = new ArrayList<ComboBean>();
private List<ComboBean> listaUffici = new ArrayList<ComboBean>();
private List<Applicazione> listaApplicazioni;
private Map<String, Object> session;
public String execute()
{
qualificaSelezionataDescrizione = BeanCopyUtil.getDescriptionFromBeanList(listaQualifiche, qualificaSelezionata, "getIdQualifica", "getDescrizione");
setApplicazioniSelezionateDesc(BeanCopyUtil.getDescriptionFromBeanList(listaApplicazioni, applicazioniSelezionate, "getIdApplicazione", "getDescrizione"));
return "success";
}
#Override
public void prepare() throws Exception
{
listaQualifiche = (List<Qualifica>) this.getSession().get("listaQualifiche");
listaApplicazioni = (List<Applicazione>) session.get("listaApplicazioni");
}
public String getDescrizioneTipoUfficioEUfficio()
{
String descrizioneTipoUfficioEUfficio = "";
if (listaTipoUfficio!=null && !listaTipoUfficio.isEmpty())
{
Iterator<ComboBean> it1 = listaTipoUfficio.iterator();
while (it1.hasNext())
{
ComboBean elem = it1.next();
if (elem.getIdValue().equals(tipoufficio))
{
descrizioneTipoUfficioEUfficio += elem.getValue();
break;
}
}
if (!listaUfficio.isEmpty())
{
it1 = listaUfficio.iterator();
while (it1.hasNext())
{
ComboBean elem = it1.next();
if (!elem.getValue().trim().isEmpty() && elem.getIdValue().equals(ufficio))
{
descrizioneTipoUfficioEUfficio += " - " + elem.getValue();
break;
}
}
}
}
return descrizioneTipoUfficioEUfficio;
}
[...a lot of boring getter and setter...]
}
The superclass of InserimentoDatiAction:
public class RegisterAction extends ActionSupport implements SessionAware {
private static final long serialVersionUID = 1L;
private Anagrafica anagraficaVDR = new Anagrafica();
private String comuneSelezionatoVDR;
private String ilTuodominio_EmailVDR;
private String applicazioniSelezionateVDR;
private List<Email> dominiMail;
private List<Comune> listaComuni;
private List<Applicazione> listaApplicazioni;
private List<Qualifica> listaQualifiche;
private List<ComboBean> listaEnte = new ArrayList<ComboBean>();
private String enteSelezionatoVDR;
private List<ComboBean> listaTipoUffici = new ArrayList<ComboBean>();
private String tipoUfficioSelezionatoVDR;
private List<ComboBean> listaUffici = new ArrayList<ComboBean>();
private String ufficioSelezionatoVDR;
private String qualificaSelezionataDescrizioneVDR;
private String descrizioneTipoUfficioEUfficioVDR;
private String applicazioniSelezionateDescVDR;
private Map<String, Object> session;
[...other less important stuff...]
}
part of struts.xml, formDatiUtente is the first jsp, visualizzaDatiRichiesta is the second (confirmation jsp):
<action name="inserimentoDati"
class="it.alm.action.InserimentoDatiAction">
<result name="success">/jsp/creazioneUtenza/formDatiUtente.jsp</result>
</action>
<action name="inviaRichiesta"
class="it.alm.action.InviaRichiestaAction">
<result name="success">/jsp/creazioneUtenza/visualizzaDatiRichiesta.jsp</result>
<result name="input">/jsp/creazioneUtenza/formDatiUtente.jsp</result>
<result name="backToMenuAdmin">/jsp/pannelloDiGestione/menu.jsp</result>
</action>
Action1 extends the one containing the AnagraficaVDR used to set the value;
Action2 extends simply ActionSupport, it doesn't know anything about an object called AnagraficaVDR.
When you post the form to Action2, and it fails validation, INPUT result returns the first JSP, without the first Action backing its data.
You have to rethink the mechanism a bit:
if you want to repopulate the first JSP with the ORIGINAL values from AnagraficaVDR, you have to provide AnagraficaVDR to Action2 too (maybe by declaring two actions in struts.xml pointing to two methods of the same action containing AnagraficaVDR...)
But this is generally avoided, because if I've changed 10 fields from their original values, and one of them is failing the validation, I want it to return my 10 ALTERED values, to be able to change only the failing one. With the solution provided above, it will reset all to AnagraficaVDR values, not the just entered values.
Then you should find another way, simpler and effective, like
populating your Action1 properties from AnagraficaVDR in the first Action execute (or
prepare) method,
remove all value="%{AnagraficaVDR.something" from your tags in JSP1.*
*NOTE: this is based on your previous question code, where the tag had name="properties" and value="%{AnagraficaVDR.properties}"
This way the first action will populate the values from AnagraficaVDR only the first time, then keeping the entered values in case of SUCCESS or INPUT.