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>
Related
I am new to Java... I made this application, but the problem is that when I run the project I am getting the text which i have written in h tag's value attribute instead of the value from the bean. I have searched a lot but the problem is still there. The code and the screenshot tells the rest of the story. Here is my login.jsp:
</head>
<body>
<f:view>
<div class="login_container">
<h:messages errorClass="errorMsg"/>
<div class="login_box">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<div class="login_wrap">
<div class="login_logo">
<img src="images/login_logo.gif" width="116" height="141" />
</div>
<h:form id="login_form">
<div class="login_form">
<table width="100%" border="0" cellpadding="0" cellspacing="0">
<tr>
<td>
<div style="float: left;">
<h2 class="orange">
Please Login
</h2>
</div>
<div class="login_icon">
<img src="images/icn_lock.png" width="16" height="16" />
</div>
</td>
</tr>
<tr>
<td>
<label>
Username
</label>
</td>
</tr>
<tr>
<td><h:inputText id="username" value="#{loginBean.username}" /></td>
</tr>
<tr>
<td>
<label>
Password
</label>
</td>
</tr>
<tr>
<td><h:inputText id="password" value="#{loginBean.password}"/>
</td>
</tr>
<tr>
<td>
</td>
</tr>
<tr>
<td align="left" valign="middle">
<h:commandButton image="images/btn_login.gif" id="loginButton" action="#{loginBean.login}"
style="width:81px; height:29px" />
</td>
</tr>
</table>
</div>
</h:form>
</div>
</td>
</tr>
<tr>
<td>
<div class="login_box_bt">
</div>
</td>
</tr>
</table>
</div>
<div class="login_footer_box">
<div class="login_footer">
<div class="login_footer_text">
<p>
<span class="text_orange">Phone:</span> (+92-51) 5120684
<br />
<span class="text_orange">E-mail:</span> support#noeticworld.com
<br />
<span class="text_orange">Web:</span> http://www.noeticworld.com.pk
</p></div>
<div class="login_footer1_text">
<p>
<span class="text_orange">Leading VAS Solution Provider
</span>
<% /**<span class="text_orange">Fax:</span> (+92-51) 260 9263*/ %>
<br />
</p></div>
</div>
</div>
<div class="login_box_bt">
</div>
</f:view>
</body>
</html>
here is my backingbeans :
public class LoginBackingBean
{
private String username;
private String password;
private Boolean rememberMe;
public String getUsername()
{
return username;
}
public void setUsername(String username)
{
this.username = username;
}
public String getPassword()
{
return password;
}
public void setPassword(String password)
{
this.password = password;
}
public Boolean getRememberMe()
{
return rememberMe;
}
public void setRememberMe(Boolean rememberMe)
{
this.rememberMe = rememberMe;
}
public String login()
{
boolean isValidUser = true;
String message = "";
Employee employee = null;
try
{
employee = getCurrentEmployee();
if (employee == null)
{
isValidUser = false;
message = "Sorry, the username or password is incorrect. Please try again";
}
}
catch (SQLException e)
{
isValidUser = false;
message = e.getMessage();
e.printStackTrace();
}
if (!isValidUser)
{
FacesMessage facesMessage = new FacesMessage();
facesMessage.setSeverity(FacesMessage.SEVERITY_ERROR);
facesMessage.setSummary(message);
FacesContext.getCurrentInstance().addMessage("login_form", facesMessage);
return "failure";
}
EmployeeBackingBean employeeBackingBean = EmployeeBackingBean.getEmployeeBackingBean(employee);
List<Integer> recursiveSubordinatesIds;
try
{
recursiveSubordinatesIds = new EmployeeDAOImpl(DigiDeskDAO.getSqlMapper()).selectIdsOfRecursiveSubordinates(employeeBackingBean.getEmployeeId());
employeeBackingBean.setRecursiveSubordinatesIds(recursiveSubordinatesIds);
}
catch (SQLException e)
{
// TODO Auto-generated catch block
e.printStackTrace();
}
SessionManager.setEmployeeInSession(employeeBackingBean);
return "success";
}
/**
* This function finds the employee with the provided username and password
*
* #return - Employee object if validation succeeds, null if no matching user is found
* #throws SQLException
*/
private Employee getCurrentEmployee() throws SQLException
{
EmployeeDAOImpl employeeDAOImpl = new EmployeeDAOImpl(DigiDeskDAO.getSqlMapper());
EmployeeExample employeeExample = new EmployeeExample();
EmployeeExample.Criteria criteria = employeeExample.createCriteria();
criteria.andUsernameEqualTo(username);
criteria.andPasswordEqualTo(password);
List<Employee> employeesList = employeeDAOImpl.selectByExampleWithBLOBs(employeeExample);
if (employeesList.isEmpty())
{
return null;
}
Employee employee = employeesList.get(0);
return employee;
}
}
This is the problem, username and password shows the text:
Try to replace #{~~} with ${~~}
In my jsp page there have a table with nested list value, i want to send that table value to the container, The outer table value were sent but the inner table value not sent to the container, I am new here please let me know how to over come this situation,
My jsp
<script>
function rowAdded(rowElement) {
//clear the imput fields for the row
$(rowElement).find("input").val('');
//may want to reset <select> options etc
//in fact you may want to submit the form
saveNeeded();
}
function rowRemoved(rowElement) {
saveNeeded();
}
function saveNeeded() {
$('#submit').css('color','red');
$('#submit').css('font-weight','bold');
if( $('#submit').val().indexOf('!') != 0 ) {
$('#submit').val( '!' + $('#submit').val() );
}
}
function beforeSubmit() {
alert('script Working');
return true;
}
$(document).ready( function() {
var config = {
rowClass : 'rule',
addRowId : 'addRule',
removeRowClass : 'removeRule',
formId : 'ruleListForm',
rowContainerId : 'ruleListContainer',
indexedPropertyName : 'ruleList',
indexedPropertyMemberNames : 'id,ruleName,parameterName,overwriteValue',
rowAddedListener : rowAdded,
rowRemovedListener : rowRemoved,
beforeSubmit : beforeSubmit
};
new DynamicListHelper(config);
});
</script>
<html>
<form:form action="/update" method="post" id="ruleListForm" modelAttribute="ruleListContainer">
<table border="1">
<thead>
<h3 align="center">Selected Rule</h3>
<tr>
<th data-field="id" width="25">ID </th>
<th data-field="details" width="20">RuleName </th>
<th data-field="parameter" width="240">Parameter </th>
</tr>
</thead>
<tbody id="ruleListContainer">
<c:forEach items="${List2}" var="as">
<tr class="rule">
<td><input type="hidden" name="ruleList[].id" value="${as.rule.id}" /> ${as.rule.id}</td>
<td><input type="hidden" name="ruleList[].ruleName" value="${as.rule.ruleName}" /> ${as.rule.ruleName}</td>
<td> <input id="one" class="datepicker" type="text" name="ruleList[].startDate" size="11" height="0.10"></td>
<td> <input id="two" class="datepicker" type="text" name="ruleList[].endDate" size="11" height="0.10"></td>
<td>
<table border="1">
<c:forEach items="${as.ruleAssignmentParameter}" var="asss">
<tr>
<td><input type="hidden" name="ruleList[].parameterName"value="${asss.parameterName}" > ${asss.parameterName}</td>
<td><input type="hidden" name="ruleList[].overwriteValue" value="${asss.overwriteValue}" /> ${asss.overwriteValue}</td>
</tr>
</c:forEach>
</table>
</td>
</tr>
</c:forEach>
</tbody>
</table>
<br>
<input type="submit" value="Update">
</form:form>
</html>
Here is my model class
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import com.demo.app.model.RuleAssignmentParameter;
public class RuleAssUI {
private int id;
private String ruleName;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getRuleName() {
return ruleName;
}
public void setRuleName(String ruleName) {
this.ruleName = ruleName;
}
private List<RuleAssignmentParameter> ruleAssignmentParameter = new LinkedList<RuleAssignmentParameter>();
public List<RuleAssignmentParameter> getRuleAssignmentParameter() {
return ruleAssignmentParameter;
}
public void setRuleAssignmentParameter(List<RuleAssignmentParameter> ruleAssignmentParameter) {
this.ruleAssignmentParameter = ruleAssignmentParameter;
}
public RuleAssUI(){
}
public RuleAssUI(int id,String ruleName){
this.id=id;
this.ruleName=ruleName;
}
}
My container where i store the list value
import java.util.LinkedList;
import java.util.List;
public class RuleListContainer {
private List<RuleAssUI> ruleList = new LinkedList<RuleAssUI>();
public RuleListContainer() {
}
public RuleListContainer(List<RuleAssUI> ruleList) {
this.ruleList = ruleList;
}
public List<RuleAssUI> getRuleList() {
return ruleList;
}
public void setRuleList(List<RuleAssUI> ruleList) {
this.ruleList = ruleList;
}
Controller
#RequestMapping(value = "/update", method = RequestMethod.POST)
public String update(#ModelAttribute("SpringWeb") RuleListContainer ruleListContainer, HttpSession session, ModelMap model) {
ruleListContainer.getRuleList().size();
for (RuleAssUI rul1 : ruleListContainer.getRuleList()) {
System.out.println("Id: " + rul1.getId());
System.out.println("RuleName: " + rul1.getRuleName());
for (RuleAssignmentParameter rul2 : rul1.getRuleAssignmentParameter()) {
System.out.println("ParameterName: " + rul2.getParameterName());
System.out.println("ParameterValue: " + rul2.getOverwriteValue());
}
}
session.setAttribute("ruleListContainer", ruleListContainer);
return "hello";
}
I am trying so many time but unable to fixed the issue, And browse also but did't get any proper help, so please help to do items
I NEED HELP PLEASE SOME BODY HELP ME...!
Thank you in advance
I think the problem is in your jsp file.
You need to set the index of each list element.
<c:forEach items="${List2}" var="as" varStatus="vs">
<tr class="rule">
<td><input type="hidden" name="ruleList[${vs.index}].id" value="${as.rule.id}" /> ${as.rule.id}</td>
<td><input type="hidden" name="ruleList[${vs.index}].ruleName" value="${as.rule.ruleName}" /> ${as.rule.ruleName}</td>
<td> <input id="one" class="datepicker" type="text" name="ruleList[${vs.index}].startDate" size="11" height="0.10"></td>
<td> <input id="two" class="datepicker" type="text" name="ruleList[${vs.index}].endDate" size="11" height="0.10"></td>
<td>
<table border="1">
<c:forEach items="${as.ruleAssignmentParameter}" var="asss" varStatus="assignments">
<tr>
<td><input type="hidden" name="ruleList[${vs.index}].ruleAssignmentParameter[${assignments.index}].parameterName" value="${asss.parameterName}" > ${asss.parameterName}</td>
<td><input type="hidden" name="ruleList[${vs.index}].ruleAssignmentParameter[${assignments.index}].overwriteValue" value="${asss.overwriteValue}" /> ${asss.overwriteValue}</td>
</tr>
</c:forEach>
</table>
</td>
</tr>
</c:forEach>
Also in your controller (POST method) you are trying to get the object identified by "SpringWeb" but should be "ruleListContainer", same name you have in your form tag
The problem was you had a list into RuleAssUI and you was not accesing correctly, you need 2 loops and indexes, one for each list.
Here is the key:
ruleList[${vs.index}].ruleAssignmentParameter[${assignments.index}].parameterName
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!
I want to know what's wrong in this code.
I have a list of date and the second list contain others values.
I'm trying to put all date in the list "daStock" and others values (line,category,duration) in list "stockss". I have a table in my page jsp. I want every date display with his own values.
<%#page import="model.Stock"%>
<%#page import="model.Operateur"%>
<%#page import="model.Descriptionarret"%>
<%#page import="model.Categoriearret"%>
<%#page import="web.Operation"%>
<%#page import="web.UhtBeans"%>
<%#page import="model.Ligne"%>
<%#page import="java.text.DateFormat"%>
<%#page import="java.text.SimpleDateFormat"%>
<%#page import="java.util.Date"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Iterator"%>
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!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" />
<meta name="author" content="MWH Team 2" />
<script type="text/javascript" src="fichier/jquery-1.10.2.js"></script>
<script type="text/javascript" src="jquery-ui-1.11.0/jquery-ui.js"></script>
<script type="text/javascript" src="fichier/ajax_js.js"></script>
<script type="text/javascript" src="fichier/calendrier.js"></script>
<link rel="stylesheet" media="screen" type="text/css" title="Design" href="fichier/design.css" />
<link href="./fichier/bootstrap.min.css" rel="stylesheet">
<link href="./fichier/Site.css" rel="stylesheet">
<link rel="stylesheet" href="jquery-ui-1.11.0/jquery-ui.css">
<title>UHT</title>
<script language="javascript">
function showList() {
var select = document.getElementById('liste');
if(select.value == "l1") {
document.getElementById('l1').setAttribute('style','visibility:inline');
} else if(select.value == "l2") {
document.getElementById('l2').setAttribute('style','visibility:inline');
} else {
document.getElementById('l3').setAttribute('style','visibility:inline');
}
}
</script>
</head>
<body >
<script language="JavaScript" type="text/javascript">
function getsupport ( )
{
document.SupportForm.submit() ;
}
</script>
<%
Operateur p = new Operateur();
String info="";
String info1="";
String info2="";
if (session.getAttribute("oppp")==null){%>
<SCRIPT LANGUAGE='JavaScript'>
window.alert('Veuillez vous identifier');
window.location.href='Connexion.jsp';
</SCRIPT>
<% } else {
p = (Operateur) session.getAttribute("oppp");
if (p.getIsadmin().equals("false"))
{
info = p.getNomoperateur();
info2="Operateur";
info1="opera";
}
else
{
info = p.getNomoperateur();
info2="Administrateur";
info1="admin";
}
}
%>
<script language="JavaScript" type="text/javascript">
function getsupport ( )
{
document.SupportForm.submit() ;
}
</script>
<div style="padding-bottom:30px; margin-top:-10px; background-color: green; background-image: url('./fichier/occpp.png');
-webkit-background-size: cover;
-moz-background-size: cover;
-o-background-size: cover;
background-size: cover;
" >
<div> <label style="margin-left:1150px; margin-top:30px; margin-right: 2px; color:#ffffff; font-family: Calibri, sans-serif; "><%=info %><br/><%=info2 %></label></div>
<p style="color:#ffffff; font-size:36px; font-family: Coolvetica Rg;" align="center">Cute Process UHT</p>
</div>
<div class="row-offcanvas row-offcanvas-left">
<div id="sidebar" class="sidebar-offcanvas" style="margin-top:18px; ">
<form name="SupportForm" method="post" action="controle">
<input type="hidden" name="Adminpanel4" />
<ul class="nav nav-pills nav-stacked">
<li>Acceuil</li>
<li class="active">Saisie des Données</li>
<li class="active">Resultats</li>
<li id="Adminpanel" >Gestion des Lignes</li>
<li id="Adminpanel1">Gestion des Categories</li>
<li id="Adminpanel2">Gestion des Arrêts</li>
<li id="Adminpanel3">Gestion des Operateurs</li>
<li>Deconnexion</li>
</ul>
</form>
</div>
<button class="sidebar-trigger" data-toggle="offcanvas" style="margin-top:18px;"></button>
<div id="main">
<div class=" container-fluid body-content " style="margin-top:10px; ">
<%
UhtBeans uhtBs;
Operation opp = new Operation();
uhtBs = new UhtBeans();
uhtBs.setListeLi(opp.allLigne());
uhtBs.setListeCat(opp.allCategorie());
uhtBs.setListeArr(opp.allArret());
%>
<input type="hidden" name="isSent" id="InputisSent" />
<input type="hidden" id="oop" value="<%=info1 %>" /></td>
<br /><br />
<center>
<h2 align="center" class="button green center" data-toggle="collapse" data-target="#Gestion1" >List</h2>
<br><br>
<center id="Gestion1" class="collapse">
<div id="affichage" style="overflow:auto;">
<script type="text/javascript">
var tableToExcel = (function() {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
, base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }
return function(table, name) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
<div id="export" ><input type="button" onclick="tableToExcel('testTable2', 'W3C Example Table')" value=" Export to Excel ">
</div>
<p></p>
<center>
<table border="1" id="testTable2" border="1" width=100% class="table table-hover">
<thead>
<tr align="center" >
<th width="50%">Postes</th>
<th>Poste1 (22h-06h)</th>
<th>Poste2 (06h-14h)</th>
<th>Poste3 (14h-22h)</th>
<th>Total Journé</th>
</tr>
</thead>
<%
UhtBeans ub = new UhtBeans();
UhtBeans ub1 = new UhtBeans();
ub.setListDateSt(opp.allDateStock());
ub1.setListSt(opp.allStock());
request.setAttribute("DateStock", ub);
request.setAttribute("stock", ub1);
UhtBeans stockss;
UhtBeans daStock;
daStock = (UhtBeans) request.getAttribute("DateStock");
if(request.getAttribute("stock") != null){
stockss =(UhtBeans) request.getAttribute("stock");
}else {
Operation opers = new Operation();
stockss = new UhtBeans();
stockss.setListSt(opers.allStock());
}
%>
<%
Iterator<Stock> listDat = daStock.getListDateSt().iterator();
while(listDat.hasNext()){
Stock sd =listDat.next();
Iterator<Stock> lists = stockss.getListSt().iterator();
while(lists.hasNext()){
Stock s =lists.next();
%>
<tr>
<th bgcolor="green" class="Date"><%=s.getDate() %></th>
</tr>
<tr align="center" bgcolor="cyan">
<th>DIAGRAMME TEMPS</th>
<th>Durée(min)</th>
<th>Durée(min)</th>
<th>Durée(min)</th>
<th>Durée(min)</th>
</tr>
<tbody id="colonne">
<tr align="center">
<th bgcolor="yellow">Temps Calendrier</th>
<%int d=480; %>
<th id="d" class="Duree"><%=d %></th>
<th ></th>
<th></th>
<th></th>
</tr>
<tr align="right">
<th bgcolor="red">Temps non disponible</th>
<th class="Duree" id="d11"><%
System.out.println("ID DU CATEGORIE EST : "+s.getCategorie());
if (s.getCategorie().equals("0")){
%>
<%=s.getDuree() %>
<%} %>
</th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center">
<th bgcolor="yellow">Temps Disponible</th>
<%int d2;
d2=d; %>
<th><%=d2 %></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="right">
<th bgcolor="red">Temps disponible non utilisé</th>
<th class="Duree">
<%System.out.println("ID De TDNU EST : "+ s.getCategorie());
if(s.getCategorie().equals("1")){
%><%=s.getDuree()%>
<%} %>
</th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center">
<th bgcolor="yellow">Temps d'ouverture</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="right">
<th bgcolor="red">Préventif et révision équipement</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="right">
<th bgcolor="red">Autres arrêts planifiés non OP</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center">
<th bgcolor="yellow">Temps operationnel</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="right">
<th bgcolor="red">Nettoyage</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="right">
<th bgcolor="red">Autres arrêts OP planifiés</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center">
<th bgcolor="yellow">Temps de production</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="right">
<th bgcolor="red">Arrêts organisationnels</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="right">
<th bgcolor="red">Arrêts techniques</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="right">
<th bgcolor="red">Arrêts technologiques</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center">
<th bgcolor="yellow">Running time</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center">
<th bgcolor="yellow">Temps net de production</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<%
}}
%>
</tbody>
<tr><th colspan="5"><br></th></tr>
<tr align="center" bgcolor="cyan">
<th>INDICATEURS DU CUTE</th>
<th colspan="4">Valeur</th>
</tr>
<tr align="center" bgcolor="green">
<th>Efficacité de production (PE)</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center" bgcolor="green">
<th>Efficacité operationnelle (OE)</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center" bgcolor="green">
<th>Efficacité énèrgetique (EE)</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center" bgcolor="green">
<th>Maintenance planifiée (PM)</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center" bgcolor="green">
<th>Nettoyage planifié (CIP)</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center" bgcolor="green">
<th>Arrêts techniques (th)</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center" bgcolor="green">
<th>Arrêts technologiques (TOD)</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr align="center" bgcolor="green">
<th>Utilisation operationnelle (OU)</th>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
<tr>
</table>
</center>
</div>
</center>
<script>
$('#InputOperateurMail').on("click", function () {
// $('#CC').val($(this).val());
$('#CC').val($('#CC').val()+";"+$(this).val());
});
$( "#InputDate" ).datepicker({
changeMonth: true,
changeYear: true
});
//Le script Ajaaaaaaaaaaaaaaaaaax
$(document).ready(function() {
if ( $("#oop").val()!="admin")
{
$("#Adminpanel").hide();
$("#Adminpanel1").hide();
$("#Adminpanel2").hide();
$("#Adminpanel3").hide();
$("#export").hide();
}
var selectionCount = 1;
$('#Ajouter').on("click", function () {
$.ajax({
type: "GET",
url: "controle?action=Ajouter",
data: {
Date: $("#InputDate").val(),
NomCat: $("#InputNomCat").val(),
Arret: $("#InputArrets option:selected").val(),
Ligne: $("#InputLigne").val(),
Duree: $("#InputDuree").val(),
},
success: function (result) {
$("#affichage").html(result);
}
});
});
//Modifier
$('#Modifier').on("click", function () {
$.ajax({
type: "GET",
url: "controle?action=Modifier",
data: {
Date: $("#InputDate").val(),
NomCat: $("#InputNomCat").val(),
Arret: $("#InputArrets").val(),
Ligne: $("#InputLigne").val(),
Duree: $("#InputDuree").val(),
},
success: function (result) {
$("#affichage").html(result);
}
});
});
//Supprimer
$('#Supprimer').on("click", function () {
$.ajax({
type: "GET",
url: "controle?action=Supprimer",
data: {
Date: $("#InputDate").val(),
NomCat: $("#InputNomCat").val(),
Arret: $("#InputArrets").val(),
Ligne: $("#InputLigne").val(),
Duree: $("#InputDuree").val(),
},
success: function (result) {
$("#affichage").html(result);
}
});
});
//Recherche
$('#Rechercher').on("click", function () {
$("#Retourner").attr('type', 'submit');
$("#Rechercher").attr('type', 'hidden');
$.ajax({
type: "GET",
url: "controle?action=Rechercher",
data: {
Date: $("#InputDate").val(),
},
success: function (result) {
$("#affichage").html(result);
}
});
});
//retourner Affichage
$('#Retourner').on("click", function () {
$("#Retourner").attr('type', 'hidden');
$("#Rechercher").attr('type', 'submit');
$.ajax({
type: "GET",
url: "controle?action=Retourner",
success: function (result) {
$("#affichage").html(result);
}
});
});
//Vider les Inputs
$('#Vider').on("click", function () {
$("#InputDate").val("");
$("#InputNomCat").val("");
$("#InputArrets").val("");
$("#InputLigne").val("");
$("#InputDuree").val("");
});
//Affichage des valeurs dans les Inputs
$('#affichage').on("click", 'tbody tr', function () {
if ($(this).hasClass('selected')) {
selectionCount++;
selectionCount = 1;
}
if (selectionCount == 1) {
$(".selected").removeClass("selected");
$(this).addClass("selected");
var Date = $('.selected').find(".Date").text().trim();
var NomCat = $('.selected').find(".NomCat").text().trim();
var Arret = $('.selected').find(".Arret").text().trim();
var Ligne = $('.selected').find(".Ligne").text().trim();
var Duree = $('.selected').find(".Duree").text().trim();
//changement du couleur
$('#colonne tr').css('background','white');
$("#InputDate").val(Date) ;
$("#InputNomCat").val(NomCat);
$("#InputArrets").val(Arret);
$("#InputLigne").val(Ligne);
$("#InputDuree").val(Duree);
}
});
//Affichage des valeurs dans les Inputs
var i=1;
$( "#espacefournisseur" ).hide();
$( "#espaceF" ).click(function() {
if(i % 2 == 0)
{ $( "#espacefournisseur" ).hide( "slow");
i=i+1;
}else
{ $( "#espacefournisseur" ).show( "slow");
i=i+1;
}});
});
</script>
<!-- Date Pickeeeeeeeer! -->
<!-- Tableau obligatoire ! C'est lui qui contiendra le calendrier ! -->
<table class="ds_box" cellpadding="0" cellspacing="0" id="ds_conclass" style="display: none;">
<tr>
<td id="ds_calclass"></td>
</tr>
</table>
<script type="text/javascript" src="fichier/bootstrap.js"></script>
<script src="fichier/Site.js"></script>
</div>
</div>
</div>
</body>
</html>
Error
SEVERE: Servlet.service() for servlet [jsp] in context with path [/Stage-UHT1] threw exception [An exception occurred processing JSP page /Resultats.jsp at line 222
219: <%
220: Iterator<Stock> listDat = daStock.getListDateSt().iterator();
221: while(listDat.hasNext()){
222: Stock sd =listDat.next();
223: Iterator<Stock> lists = stockss.getListSt().iterator();
224: while(lists.hasNext()){
225: Stock s =lists.next();
Stacktrace:] with root cause
java.lang.ClassCastException: java.lang.String cannot be cast to model.Stock
at org.apache.jsp.Resultats_jsp._jspService(Resultats_jsp.java:310)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:432)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:390)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:334)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:170)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:98)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:313)
at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
at java.lang.Thread.run(Unknown Source)
UhtBeans CLass
package web;
import java.util.ArrayList;
import java.util.List;
import model.Categoriearret;
import model.Descriptionarret;
import model.Ligne;
import model.Operateur;
import model.Stock;
public class UhtBeans {
private Ligne ligne = new Ligne() ;
private Categoriearret categorie = new Categoriearret();
private Descriptionarret arret = new Descriptionarret();
private Stock stock = new Stock();
private Operateur operateur = new Operateur();
private boolean login;
private ArrayList<Ligne> listeLi = new ArrayList<Ligne>();
private ArrayList<Categoriearret> listeCat = new ArrayList<Categoriearret>();
private ArrayList<Descriptionarret> listeArr = new ArrayList<Descriptionarret>();
private ArrayList<Stock> listSt = new ArrayList<Stock>();
private ArrayList<Stock> listDateSt = new ArrayList<Stock>();
private ArrayList<Operateur> listOp = new ArrayList<Operateur>();
public ArrayList<Stock> getListDateSt() {
return listDateSt;
}
public void setListDateSt(List<Stock> listDateSt) {
this.listDateSt = (ArrayList<Stock>) listDateSt;
}
//Operateur
public Operateur getOperateur() {
return operateur;
}
public void setOperateur(Operateur operateur) {
this.operateur = operateur;
}
public ArrayList<Operateur> getListOp() {
return listOp;
}
public void setListOp(List<Operateur> listOp) {
this.listOp = (ArrayList<Operateur>) listOp;
}
//Stock
public Stock getStock() {
return stock;
}
public void setStock(Stock stock) {
this.stock = stock;
}
public ArrayList<Stock> getListSt() {
return listSt;
}
public void setListSt(List<Stock> list) {
this.listSt = (ArrayList<Stock>) list;
}
//Arrêt
public Descriptionarret getArret() {
return arret;
}
public void setArret(Descriptionarret arret) {
this.arret = arret;
}
public ArrayList<Descriptionarret> getListeArr() {
return listeArr;
}
public void setListeArr(List<Descriptionarret> listeArr) {
this.listeArr = (ArrayList<Descriptionarret>)listeArr;
}
//Categories
public Categoriearret getCategorie() {
return categorie;
}
public void setCategorie(Categoriearret categorie) {
this.categorie = categorie;
}
public ArrayList<Categoriearret> getListeCat() {
return listeCat;
}
public void setListeCat(List<Categoriearret> listCat) {
this.listeCat = (ArrayList<Categoriearret>)listCat;
}
//Lignes
public Ligne getLigne() {
return ligne;
}
public void setLigne(Ligne ligne) {
this.ligne = ligne;
}
public ArrayList<Ligne> getListeLi() {
return listeLi;
}
public void setListeLi(List<Ligne> listeLi) {
this.listeLi = (ArrayList<Ligne>)listeLi;
}
public boolean isLogin() {
return login;
}
public void setLogin(boolean login) {
this.login = login;
}
}
I think stockss.getListSt() returns a list of String. So casting an element of the list to a Stock cannot possibly work. And that's what you're trying to do in Stock s =lists.next();
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.