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.
Related
So I have 3 jsp-forms. The first one with general information. On completetion of the first form it should based on the value of a dropdown return eather form 2 or form 3. So far so good, the object is correctly written to the db, the check is performed and the correct jsp-form is shown, but when the user fills in the second form, nothing happens, read the postmethod of the secondform isn't called.
Any tips on how to fix this problem would be greatly appreciated.
I've bin breaking my head and searching the internet for days but can't find a straight answer.
The GeneralController:
#Controller
public class GeneralController {
#Autowired
private GeneralRepo repo;
#GetMapping("new")
public String getNew(Map<String, Object> model) {
WrapperClass wrapper = new WrapperClass();
model.put("wrapperForm", wrapper);
return "newRecord";
}
#PostMapping("new")
public String handlePost(#ModelAttribute("wrapperForm") WrapperClass wrapper)
{
Address address = new Address(wrapper.getNameOrg(), wrapper.getStreet(), wrapper.getNumber(), wrapper.getZip(),
wrapper.getCity(), wrapper.getTelephone(), wrapper.getEmail());
General general = new General(wrapper.getLanguage(), wrapper.getApplication(), wrapper.getNameKbo(), wrapper.getKboNumber(),
address, wrapper.getApplicationType(), wrapper.getNotes(), null, null, null, null);
String url;
if (general.getApplicationType().equalsIgnoreCase("voortzetting")) {
url = "invoices";
} else {
url = "employee";
}
repo.save(general);
return "redirect:/" + url;
}
}
The Generalform:
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Record Toevoegen</title>
<link rel="stylesheet" href="${pageContext.request.contextPath}/css/general.css">
<link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
<link href="${pageContext.request.contextPath}/css/modern-business.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="${pageContext.request.contextPath}/css/customUtilities.css" rel="stylesheet">
<link href="${pageContext.request.contextPath}/css/general.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
<link rel="icon" href="${pageContext.request.contextPath}/images/vigilis.jpg" type="image/x-icon">
</head>
<body>
<%#include file="navigation.jsp" %>
<%--#elvariable id="wrapperForm" type=""--%>
<form:form method="post" commandName="wrapperForm">
<table align="center" id="forms">
<tr>
<td>
<label>Taal:</label>
</td>
<td>
<form:select path="language" id="language" name="language">
<form:option value="Nederlands"/>
<form:option value="Français"/>
<form:option value="Deutsch"/>
<form:option value="English"/>
</form:select>
</td>
<td>
<label>Type Aanvraag: </label>
</td>
<td>
<form:select path="applicationType" id="type" name="type">
<form:option value="Nieuwe aanvraag"/>
<form:option value="Voortzetting"/>
<form:option value="Vrijwillige ontbinding"/>
<form:option value="Faillisement"/>
</form:select>
</td>
</tr>
<tr>
<td>
<label for="nameKbo">KBO-Benaming</label>
</td>
<td colspan="3">
<form:input path="nameKbo" id="nameKbo" type="text" name="nameKbo" required="required" size="100%"/>
</td>
<tr>
<td>
<label for="kboNumber">KBO-Nummer:</label>
</td>
<td>
<form:input path="kboNumber" id="kboNumber" type="text" name="kboNumber"/>
</td>
</tr>
<tr>
<td>
<label for="nameOrg">HandelsBenaming:</label>
</td>
<td colspan="3">
<form:input path="nameOrg" id="nameOrg" type="text" name="nameOrg" size="100%"/>
</td>
</tr>
<tr>
<td>
<label>Adres:</label>
</td>
<td colspan="2">
<form:input path="street" id="street" name="street" type="text" placeholder="Straatnaam" size="100%"/>
</td>
<td>
<form:input path="number" id="number" name="number" type="text" size="5"/>
</td>
</tr>
<tr>
<td></td>
<td>
<form:input path="zip" id="zip" name="zip" type="text" placeholder="Zip" size="5"/>
</td>
<td >
<form:input path="city" id="city" name="city" type="text" placeholder="Stad" size="80%"/>
</td>
</tr>
<tr>
<td>
<label>Contactgegevens:</label>
</td>
<td>
<form:input path="telephone" id="telephone" name="telephone" type="text" placeholder="Telefoonnummer"/>
</td>
<td colspan="2">
<form:input path="email" id="email" name="email" type="e-mail" placeholder="E-mailadres" size="100%"/>
</td>
</tr>
<tr>
<td>
<label for="notes" style="vertical-align: middle">Opmerkingen:</label>
</td>
<td colspan="3">
<form:textarea path="notes" id="notes" name="notes" style="width: 100%"/>
</td>
</tr>
<tr></tr>
<tr></tr>
<tr>
<td></td>
<td colspan="2" style="align-content: center;"><input type ="submit" value="Opslaan" class="button"/></td>
</tr>
</table>
</form:form>
<%#include file="footer.jsp" %>
</body>
</html>
The InvoiceController:
#Controller
public class InvoiceController {
#Autowired
private GeneralRepo repo;
#GetMapping("invoices")
public String handleGetInvoice(Map<String, Object> model) {
Invoices invoiced = new Invoices();
model.put("invoiceForm", invoiced);
return "invoices";
}
#PostMapping("invoices")
public String handlePost(#ModelAttribute("invoiceForm") Invoices invoiced, Map<String, Object> model) {
General general = repo.findLast();
general.setInvoice(invoiced);
repo.save(general);
System.out.println("invoice saved");
return "redirect:/employee";
}
}
The Invoiceform:
<%# page contentType="text/html;charset=UTF-8" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<meta name="description" content="">
<meta name="author" content="">
<title>Facturen</title>
<link href="${pageContext.request.contextPath}/css/bootstrap.min.css" rel="stylesheet">
<link href="${pageContext.request.contextPath}/css/modern-business.css" rel="stylesheet">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<link href="${pageContext.request.contextPath}/css/customUtilities.css" rel="stylesheet">
<link href="${pageContext.request.contextPath}/css/general.css" rel="stylesheet">
<link href="https://fonts.googleapis.com/css?family=Pacifico" rel="stylesheet">
<link rel="icon" href="${pageContext.request.contextPath}/images/vigilis.jpg" type="image/x-icon">
</head>
<body>
<!-- Navigation -->
<%#include file="navigation.jsp" %>
<%--#elvariable id="invoiceForm" type=""--%>
<form:form action="invoices" method="post" commandName="invoiceForm">
<table align="center" id="forms">
<tr>
<td>
<label>Ontvangen:</label>
</td>
<td>
<form:select path="received" id="received" name="received">
<form:option value="Ok"/>
<form:option value="Niet Ok"/>
<form:option value="Niet Aanwezig"/>
<form:option value="Aanwezig"/>
</form:select>
</td>
<td>
<label>Status: </label>
</td>
<td>
<form:select path="state" id="state" name="state">
<form:option value="In Behandeling"/>
<form:option value="Goedgekeurd"/>
<form:option value="Geweigerd"/>
<form:option value="Ingetrokken"/>
<form:option value="Moraliteitsonderzoek"/>
</form:select>
</td>
</tr>
<tr>
<td>
<label>Aantal Vorig jaar:</label>
</td>
<td>
<form:input path="last" id="last" type="text" name="last" required="required"/>
</td>
<td>
<label>Aantal Andere jaren:</label>
</td>
<td>
<form:input path="early" id="early" type="text" name="early" required="required"/>
</td>
</tr>
<tr>
<td>
</td>
<td><label>BevestigingsDatum:</label></td>
<td><form:input path="confirmationDate" id="confirmationDate" type="date" name="confirmationDate"
required="required"/></td>
</tr>
<tr>
<td></td>
<td colspan="2" style="align-content: center;"><input type="submit" value="Opslaan" class="button"/>
</td>
</tr>
</table>
</form:form>
<!-- Footer -->
<%#include file="footer.jsp" %>
<!-- Bootstrap core JavaScript -->
<script src="${pageContext.request.contextPath}/js/jquery.min.js"></script>
<script src="${pageContext.request.contextPath}/js/popper.min.js"></script>
<script src="${pageContext.request.contextPath}/js/bootstrap.min.js"></script>
</body>
</html>
pass the complete URL inside return for example
return "http://localhost:8080/projectname/"+url;
I have a problem transferring data between two jsp
There are two controllers in which the first one accepts the input data, second generate lines with using this params
First controllers group receives two params
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String ProjectSizePost(
#RequestParam("countSprints") Integer countSprints,
#RequestParam("countWorkers") Integer countWorkers) {
BigInteger a = BigInteger.valueOf(countSprints);
return "project/project_size";
}
#RequestMapping(value = "/create", method = RequestMethod.GET)
public String projectSizeGet() {
return "project/project_size";
}
And his jsp
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Size</title>
</head>
<body>
<%--<c:forEach var="inputLine" begin="1" end="4">
<td><input type="text" name="projectManagerId" size="70" value={count} ></td><br>
</c:forEach>--%>
<form action="/project/show_size" method="post" name="/project/show_size"
commandName="projectSizeForm">
<tr>
<td>Count of sprints:</td>
<td><input type="text" name="countSprints" size="70" value = ${countSprints} ></td>
</tr> <br>
<tr>
<td>Count of workers:</td>
<td><input type="text" name="countWorkers" size="70" value = ${countWorkers} ></td>
</tr>
<tr>
<input type="submit" value="Next page"/></td>
</tr>
</form>
</body>
</html>
Second controller and jsp must take params from first jsp
#RequestMapping(value = "/create", method = RequestMethod.POST)
public String createProject(
#RequestParam("projectId") Integer id,
#RequestParam("name") String name,
#RequestParam("startDate") String startDate,
#RequestParam("endDate") String endDate,
#RequestParam("projectStatus") OCStatus projectStatus,
#RequestParam("projectManagerId") Integer projectManagerId) {
MapperDateConverter mdc = new MapperDateConverter();
*//*Project project = new Project.ProjectBuilder()
.projectId(BigInteger.valueOf(id))
.name(name)
.startDate(mdc.convertStringToDate(startDate))
.endDate(mdc.convertStringToDate(endDate))
.build();
project.setProjectStatus(projectStatus);
project.setProjectManagerId(BigInteger.valueOf(projectManagerId));*//*
//projectDao.createProject(project);
return "project/create";
}
And second jsp:
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
</head>
<body>
<div align="center">
<form action="/project/create" method="post" name="/project/create"
commandName="projectForm">
<table border="0">
<tr>
<h2>CreateProject</h2></td>
</tr>
<tr>
<td>Project Id:</td>
<td><input type="text" name="projectId" size="70" value = ${projectId} ></td>
</tr>
<tr>
<td>Project Name:</td>
<td><input type="text" name="name" size="70" value = ${projectName} ></td>
</tr>
<tr>
<td>StartDate (mm/dd/yyyy):</td>
<td><input type="text" name="startDate" size="70" value = ${startDate} ></td>
</tr>
<tr>
<td>EndDate (mm/dd/yyyy):</td>
<td><input type="text" name="endDate" size="70" value = ${endDate} ></td>
</tr>
<tr>
<td>Status:</td>
<td><input type="text" name="projectStatus" size="70" value = ${status} ></td>
</tr>
<tr>
<td>Project Manager:</td>
<td><input type="text" name="projectManagerId" size="70" value = ${pmId} ></td>
</tr>
<tr>
<td>Count of sprints</td>
<td><input type="text" name="countSprints" size="70" value = ${countSprints} ></td>
</tr>
<tr>
<td>Count of sprints</td>
<td><input type="text" name="countWorkers" size="70" value = ${countWorkers} ></td>
</tr>
<tr>
<input type="submit" value="Create"/></td>
</tr>
</table>
</form>
</div>
</body>
</html>
Params countSprints and countWorkers
I'm trying to output some information from table users on my JSP page, but there is no output there.
Here is my controller method:
#Autowired
private UsersService usersService;
#RequestMapping(value="/user**")
public String getUserProfile( ) {
ModelAndView mav = new ModelAndView("userInfo");
List<Users> userInfo = usersService.userInfo("Oleg");
mav.addObject("userInfo", userInfo);
return "user";
}
Here is my DAO method
#SuppressWarnings("unchecked")
#Override
public List<Users> userInfo(String username) {
Transaction tx = sessionFactory.getCurrentSession().beginTransaction();
Session session = this.sessionFactory.getCurrentSession();
String query = "select users.username, users.name, users.surname, users.email, users.gender, users.age, users.weight, users.height, users.sport, users.place from users where users.username LIKE '%s'";
List<Users> userInfo = session.createSQLQuery(String.format(query,username)).list();
tx.commit();
return userInfo;
}
Here is my Service layer method
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<html>
<head>
<title>User Profile Page</title>
</head>
<body>
<br />
<br />
<br />
<h1>User profile page !!!</h1>
<c:url var="logoutUrl" value="j_spring_security_logout" />
<form action="${logoutUrl}" method="post">
<input type="submit" value="Log out" /> <input type="hidden"
name="${_csrf.parameterName}" value="${_csrf.token}" />
</form>
<c:forEach var="users" items="${userInfo}">
<table>
<tr>
<td>Username</td>
<td>${users.username}</td>
</tr>
<tr>
<td>First Name</td>
<td>${users.name}</td>
</tr>
<tr>
<td>Last Name</td>
<td>${users.surname}</td>
</tr>
<tr>
<td>Email</td>
<td>${users.email}</td>
</tr>
<tr>
<td>Gender</td>
<td>${users.gender}</td>
</tr>
<tr>
<td>Age</td>
<td>${users.gender}</td>
</tr>
<tr>
<td>Weight</td>
<td>${users.weight}</td>
</tr>
<tr>
<td>Height</td>
<td>${users.height}</td>
</tr>
<tr>
<td>Sport</td>
<td>${users.sport}</td>
</tr>
<tr>
<td>Place</td>
<td>${users.place}</td>
</tr>
</table>
</c:forEach>
</body>
</html>
When i'm starting my project and opening my JSP, i have no output from my DB. Help pls!
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 a JSP called create-account.jsp which collects a customer's details and sends the data to a Servlet. The Servlet inserts the customer's data into the database, queries the database add sets the results as request scoped attributes and the dispatches to create-account.jsp(same jsp). Now the inserted details must appear in a hidden html table in the jsp. How do I do it? Can any one help?
create-account.jsp
<!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=UTF-8">
<title>Create New Account</title>
<style>
a {
text-decoration: none;
}
body {
border-color: azure;
}
</style>
</head>
<body>
<p align="right">Hi, ${sessionScope.user.userName} logout</p>
<h2 align="center">Create New Account</h2>
<form action="${pageContext.request.contextPath}/create.do" method="post">
<table border="1" align="center">
<tr>
<td>Name:</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>DOB:(yyyy-mm-dd)</td>
<td><input type="text" name="dob"></td>
</tr>
<tr>
<td>Balance:</td>
<td><input type="text" name="balance"></td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="submit" value="Create" name="create">
</td>
</tr>
</table>
</form>
<p align="center" style="display: none">${requestScope.result} has been successfully inserted into the table</p>
<table id="hiddenTable" style="display: none" border="1">
<tr>
<td>
</td>
</tr>
</table>
</body>
</html>
Use
style="visibility: hidden;"
or
style="display:none;"
to hide the table.
for more info have a look at below links
CSS Display and Visibility
Show/Hide div javascript
How to show the result in table?
sample code:
Servlet:
public class Model{
private String name;
private String dob;
private double balance;
// getter and setter
}
...
List<Model> list = new ArrayList<Model>();
//add the data in list
request.setAttribute("list",list);
JSP:
<c:if test="${not empty list}">
<c:forEach var="ob" items="${list}">
<tr>
<td><c:out value="${ob.name}"/></td>
<td><c:out value="${ob.dob}"/></td>
<td><c:out value="${ob.balance}"/></td>
</tr>
</c:forEach>
</c:if>
For complete code have a look at jsp iterate over list