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 ${~~}
Related
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 have a restaurant edit page located "/restaurant/edit/{id}". From that page I can (among other things) add tables to the restaurant by pressing an "Add tables" button. That button takes me to another page located "/restaurant/edit/{id}/table". The question is, after I have added the table - how do I get back to the previous page by pressing a button? Right now my contoller is returning "editRestaurant.jsp" which is the right value, but I don't know how to pass that same restaurant id as well. I hope you understand what I mean.
My RestaurantTableController.java:
#Controller
public class RestaurantTableController {
#Autowired
private RestaurantService restaurantService;
#Autowired
private RestaurantTableService restaurantTableService;
#RequestMapping(value="restaurant/{id}/table", method = RequestMethod.GET)
public String addRestaurantTable(Model model, #PathVariable Long id) {
model.addAttribute("table", new RestaurantTable());
return "newTable";
}
#RequestMapping(value = "restaurant/{id}/table", method = RequestMethod.POST)
public String addRestaurantTableAction(#PathVariable Long id, #ModelAttribute ("table") RestaurantTable table, BindingResult result) {
RestaurantTableFormValidator restaurantTableFormValidator = new RestaurantTableFormValidator();
restaurantTableFormValidator.validate(table, result);
if (result.hasErrors()) {
return "newTable";
}
restaurantService.mergeRestaurant(id, table);
return "editRestaurant";
}
}
My "newTable.jsp":
<body>
<jsp:include page="../fragments/menu.jsp"/>
<div id="body">
<section class="content-wrapper main-content clear-fix">
<h2>Add New Table</h2>
<form:form method="POST" modelAttribute="table">
<table>
<tr>
<td>Table size:</td>
<td><form:input path="tableSize" /></td>
<td><form:errors path="tableSize" cssClass="error"/></td>
</tr>
<tr>
<td>Table number:</td>
<td><form:input path="tableNumber" /></td>
<td><form:errors path="tableNumber" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" onclick="goback()"/>
</td>
</tr>
</table>
</form:form>
</section>
</div>
<jsp:include page="../fragments/footer.jsp"/>
</body>
Relevant methods in RestaurantController.java:
#RequestMapping(value = "restaurant/edit/{id}", method = RequestMethod.GET)
public String editRestaurant(#PathVariable Long id, Model model) {
Restaurant restaurant = restaurantService.getRestaurant(id);
model.addAttribute("restaurant", restaurant);
return "editRestaurant";
}
#RequestMapping(value = "restaurant/edit/{id}", method = RequestMethod.POST, params="submit")
public String editRestaurant(#ModelAttribute ("restaurant") Restaurant restaurant, BindingResult result) {
RestaurantFormValidator restaurantFormValidator = new RestaurantFormValidator();
restaurantFormValidator.validate(restaurant, result);
if (result.hasErrors()) {
return "editRestaurant";
}
restaurantService.updateRestaurant(restaurant);
return "redirect:/bookings";
}
"editRestaurant.jsp":
<div id="body">
<section class="content-wrapper main-content clear-fix">
<h2>Edit</h2>
<form:form method="POST" modelAttribute="restaurant" >
<table>
<tr>
<td>Restaurant:</td>
<td><form:input path="restaurantName" /></td>
<td><form:errors path="restaurantName" cssClass="error"/></td>
</tr>
<tr>
<td>Address:</td>
<td><form:input path="address" /></td>
<td><form:errors path="address" cssClass="error"/></td>
</tr>
<tr>
<td colspan="3"><input type="submit" value="Submit" name="submit"/>
</td>
</tr>
<tr>
<c:forEach items="${restaurant.table}" var="item">
<td>${item.toString()}</td>
</c:forEach>
</tr>
<tr>
<td>Add Table</td>
</tr>
</table>
</form:form>
<div>
Back to List
</div>
</section>
</div>
After successful POST you should do a redirect.
Something like this:
return "redirect:/restaurant/edit/" + restaurant.getId();
or
return new RedirectView("/restaurant/edit/" + restaurant.getId(), false);
There is a different method you can use to return the model that will include the parameter. I believe this may solve your problem.
#RequestMapping(value = "restaurant/edit/{id}", method = RequestMethod.GET)
public String editRestaurant(#PathVariable Long id, Model model) {
Restaurant restaurant = restaurantService.getRestaurant(id);
return new ModelAndView("editRestaurant", "restaurant", restaurant);
}
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 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.
Form:Options working pretty well, but if I submit wrong data in Form, form:options in newContact.jsp shows the first element of departmentList as selected.
ContactController:
#RequestMapping(value="/saveContact", method=RequestMethod.GET)
public ModelAndView newuserForm(){
ModelAndView mav = new ModelAndView("newContact");
// Contact contact = new Contact();
// Department department = new Department();
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
mav.addObject("username", name);
mav.addObject("newContact", new Contact());
// mav.addObject("department", department);
mav.addObject("departmentList", departmentService.listDepartment());
//mav.getModelMap().put("newContact", contact);
return mav;
}
#RequestMapping(value="/saveContact", method=RequestMethod.POST)
public String create(#ModelAttribute("newContact")Contact contact, BindingResult result, SessionStatus status,Map<String, Object> map)
{
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
map.put("departmentList", departmentService.listDepartment());
map.put("username", name);
contactFormvalidator.validate(contact, result);
if (result.hasErrors())
{
return "newContact";
}
contactService.addContact(contact);
status.setComplete();
//return "redirect:/showContacts.do";
return "newContactSuccess";
}
newContact.jsp:
<%#include file="header.jsp"%>
<div id="menu">
<div id="subMenu"></div>
</div>
<div id="main">
<h2>Contact Manager</h2>
<form:form method="post" action="saveContact.do" commandName="newContact" >
<table>
<tr>
<td><form:label path="firstname">
<spring:message code="label.firstname" />
</form:label></td>
<td><form:input path="firstname" /></td>
<td><form:errors path="firstname" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="lastname">
<spring:message code="label.lastname" />
</form:label></td>
<td><form:input path="lastname" /></td>
<td><form:errors path="lastname" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="email">
<spring:message code="label.email" />
</form:label></td>
<td><form:input path="email" /></td>
<td><form:errors path="email" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="telephone">
<spring:message code="label.telephone" />
</form:label></td>
<td><form:input path="telephone" /></td>
<td><form:errors path="telephone" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td><form:label path="department">
<spring:message code="label.department" />
</form:label></td>
<td><form:select path="department" >
<form:option label="**SELECT**" value="0"></form:option>
<form:options items="${departmentList}" itemValue="id" itemLabel="name"></form:options>
</form:select> </td>
<td><form:errors path="department" cssStyle="color:red"></form:errors> </td>
</tr>
<tr>
<td colspan="2"><input type="submit"
value="<spring:message code="label.addcontact"/>" /></td>
</tr>
</table>
</form:form>
</div>
<%# include file="footer.jsp"%>
ContactFormValidator:
package pl.ivmx.contact.validator;
import java.util.regex.*;
import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;
import pl.ivmx.contact.form.Contact;;
//#Component("contactFormValidator")
public class ContactFormValidator implements Validator{
#Override
public boolean supports(Class clazz) {
return Contact.class.isAssignableFrom(clazz);
}
#SuppressWarnings("unchecked")
#Override
public void validate(Object obj, Errors errors) {
Contact contact = (Contact) obj;
Pattern p = Pattern.compile("[a-zA-Z]*[0-9]*#[a-zA-Z]*.[a-zA-Z]*");
Matcher m = p.matcher(contact.getEmail());
boolean b = m.matches();
if (b != true) {
errors.rejectValue("email", "error.is.not.valid",
"Email does not Valid ");
}
if (contact.getFirstname() == null || contact.getFirstname().length() < 3) {
errors.rejectValue("firstname", "error.empty.field",
"Please Enter First Name");
}
if (contact.getLastname() == null || contact.getLastname().length() < 4) {
errors.rejectValue("lastname", "error.empty.field",
"Please Enter Last Name");
}
if (contact.getTelephone() == 0 || String.valueOf(contact.getTelephone()).trim().length() < 2 ||
String.valueOf(contact.getTelephone()).trim().length() > 9) {
errors.rejectValue("telephone", "error.empty.field",
"Please Enter Telephone");
}
if (contact.getDepartment() == null) {
errors.rejectValue("department", "error.empty.field",
"Please select department");
}
}
}
Instead of returning String in your submit method return ModelAndView ...
#RequestMapping(value="/saveContact", method=RequestMethod.POST)
public ModelAndView create(#ModelAttribute("newContact")Contact contact, BindingResult result, SessionStatus status,ModelMap map)
{
User user = (User)SecurityContextHolder.getContext().getAuthentication().getPrincipal();
String name = user.getUsername();
map.addAttribute("departmentList", departmentService.listDepartment());
map.addAttribute("username", name);
contactFormvalidator.validate(contact, result);
if (result.hasErrors())
{
return new ModelAndView("newContact",map);
}
contactService.addContact(contact);
status.setComplete();
//return new ModelAndView("redirect:/showContacts.do");
return new ModelAndView("newContactSuccess");
}