I can't get value from select option to MySQL (Spring MVC) - java

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>

Related

ThymeLeaf: Neither BindingResult nor plain target object for bean name available as request attribute

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";
}

No output info on .JSP from MySQL DB, Spring MVC, Hibernate, JAVA

I'm trying to output some information from table users on my JSP page, but there is no output there.
Here is my controller method:
#Autowired
private UsersService usersService;
#RequestMapping(value="/user**")
public String getUserProfile( ) {
ModelAndView mav = new ModelAndView("userInfo");
List<Users> userInfo = usersService.userInfo("Oleg");
mav.addObject("userInfo", userInfo);
return "user";
}
Here is my DAO method
#SuppressWarnings("unchecked")
#Override
public List<Users> userInfo(String username) {
Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
Session session = this.sessionFactory.getCurrentSession();
String query = "select users.username, users.name, users.surname, users.email, users.gender, users.age, users.weight, users.height, users.sport, users.place from users where users.username LIKE '%s'";
List<Users> userInfo = session.createSQLQuery(String.format(query,username)).list();
tx.commit();
return userInfo;
}
Here is my Service layer method
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>User Profile Page</title>
</head>
<body>
<br />
<br />
<br />
<h1>User profile page !!!</h1>
<c:url var="logoutUrl" value="j_spring_security_logout" />
<form action="${logoutUrl}" method="post">
<input type="submit" value="Log out" /> <input type="hidden"
name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
<c:forEach var="users" items="${userInfo}">
<table>
<tr>
<td>Username</td>
<td>${users.username}</td>
</tr>
<tr>
<td>First Name</td>
<td>${users.name}</td>
</tr>
<tr>
<td>Last Name</td>
<td>${users.surname}</td>
</tr>
<tr>
<td>Email</td>
<td>${users.email}</td>
</tr>
<tr>
<td>Gender</td>
<td>${users.gender}</td>
</tr>
<tr>
<td>Age</td>
<td>${users.gender}</td>
</tr>
<tr>
<td>Weight</td>
<td>${users.weight}</td>
</tr>
<tr>
<td>Height</td>
<td>${users.height}</td>
</tr>
<tr>
<td>Sport</td>
<td>${users.sport}</td>
</tr>
<tr>
<td>Place</td>
<td>${users.place}</td>
</tr>
</table>
</c:forEach>
</body>
</html>
When i'm starting my project and opening my JSP, i have no output from my DB. Help pls!

Passing Java Object to AngularJS using Spring MVC Controller

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!

Struts2 validation, repopulate all the fields when validation fails

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.

JavaBean not being remembered throughout the session

I'm currently learning JSP/Servelets. The following is code containing 2 JSP pages and a servlet, which works as follows:
JSP #1 requests user info, & passes it into a servlet.
The servlet Instantiates a JavaBean class, and passes it to the 2nd JSP, using the Session Object.
The 2nd JSP then displays the info that th user entered in the 1st JSP; the user can then hit the Return button to return to the 1st JSP.
My Question is: I've read in various Tutorials (notably Murach's JSP, which this code is based on) that if the Javabean attributes are passed to the session object rather than the request object, the JavaBean's values should be maintained throughout the session. However when I return to the first page, the JB fields are empty. Am i doing anything wrong? I would appreciate any help!
The following is the code:
1st JSP:
<%# 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">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email Application</title>
</head>
<body>
<h1>Join our Email list</h1>
<p>To join our email list, enter your name and email address below.<br>
Then, click on the Submit button</p>
<form action="addToEmailList" method="post">
<jsp:useBean id="user" scope="session" class="business.User"/>
<table cellspacing="5" border="0">
<tr>
<td align="right">First name:</td>
<td>
<input type="text" name="firstName"
value = "<jsp:getProperty name="user" property="firstName"/>">
</td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><input type="text" name="lastName"
value = "<jsp:getProperty name="user" property="lastName"/>">
</td>
</tr>
<tr>
<td align="right">Email address:</td>
<td><input type="text" name="emailAddress"
value = "<jsp:getProperty name="user" property="emailAddress"/>">
</td>
</tr>
<tr>
<td>I'm interested in these types of music:</td>
<td><select name="music" multiple>
<option value="rock">Rock</option>
<option value="country">Country</option>
<option value="bluegrass">Bluegrass</option>
<option value="folkMusic">Folk Music</option>
</select>
</td>
</tr>
<tr>
<td ></td>
<td><input type="submit" name="Submit"></td>
</tr>
</table>
</form>
</body>
Servlet:
public class AddToEmailListServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
private HttpServletRequest request;
private HttpServletResponse response;
private String firstName;
private String lastName;
private String emailAddress;
private String[] musicTypes;
private Music music;
private User user;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
this.request = request;
this.response = response;
setInstanceVariables();
writeDataToFile();
forwardResponseToJSPpage();
System.err.println("Hello!");
}
private void setInstanceVariables()
{
this.firstName = getFirstName();
this.lastName = getLastName();
this.emailAddress = getEmailAddress();
this.musicTypes = request.getParameterValues("music"); //getMusic();
this.user = new User(firstName,lastName,emailAddress);
}
private String getFirstName()
{
return request.getParameter("firstName");
}
private String getLastName()
{
return request.getParameter("lastName");
}
private String getEmailAddress()
{
return request.getParameter("emailAddress");
}
private void writeDataToFile() throws IOException
{
String path = getRelativeFileName();
UserIO.add(user,path);
}
private String getRelativeFileName()
{
ServletContext sc = getServletContext();
String path = sc.getRealPath("/WEB-INF/EmailList.txt");
return path;
}
private void forwardResponseToJSPpage() throws ServletException, IOException
{
if(this.emailAddress.isEmpty()||this.firstName.isEmpty()||this.lastName.isEmpty())
{
String url = "/validation_error.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
else
{
music = new Music(musicTypes);
HttpSession session = this.request.getSession();
session.setAttribute("music", music);
session.setAttribute("user", user);
String url = "/display_email_entry.jsp";
RequestDispatcher dispatcher =
getServletContext().getRequestDispatcher(url);
dispatcher.forward(request,response);
}
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException
{
doPost(request,response);
}
}
2nd JSP:
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# include file="/header.html" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Email Application</title>
</head>
<body>
<h1>Thanks for joining our email list</h1>
<p>Here is the information that you entered:</p>
<jsp:useBean id="user" scope="session" class="business.User"/>
<table cellspacing="5" cellpadding="5" border="1">
<tr>
<td align="right">First name:</td>
<td><jsp:getProperty name="user" property="firstName"/></td>
</tr>
<tr>
<td align="right">Last name:</td>
<td><jsp:getProperty name="user" property="lastName"/></td>
</tr>
<tr>
<td align="right">Email Address:</td>
<td><jsp:getProperty name="user" property="emailAddress"/></td>
</tr>
</table>
<p>We'll use the Email to otify you whenever we have new releases of the following types of music:</p>
<c:forEach items="${music.musicTypes}" var="i">
<c:out value="${i}"></c:out><br/>
</c:forEach>
<p>To enter another email address, click on the Back <br>
button in your browser or the Return button shown <br>
below.</p>
<form action="join_email_list.jsp" method="post">
<input type="submit" value="Return">
</form>
</body>
<%# include file="/footer.html" %>
</html>

Categories