How to display a JasperReports pdf file in an iframe? - javascript

in currently I run my pdf report using JasperReports when clicking on report button the pdf report run with another browser tab but now I want to run the report on my JSP page using iframe tag. please help me to view / embedded jasper report on my web page.................................
everybody can give me an example.
Html code is
<div class="col-md-12">
<!-- begin panel -->
<div class="panel panel-inverse" data-sortable-id="form-stuff-2">
<div class="panel-heading">
<div class="panel-heading-btn">
<i class="fa fa-expand"></i>
</div>
<h4 class="panel-title">Ship Service Report Page </h4>
</div>
<div class="panel-body">
<form class="form-horizontal">
<div class="form-group">
<label class="col-md-2 control-label">Ship Name</label>
<div class="col-md-4">
<select name="" class="form-control" id="shipNam" name="shipNam">
<option value="" selected="selected">Select Ship name</option>
<s:iterator value="reportInfos" status="rowstatus">
<option value="<s:property value='shipNo' />"><s:property value='shipName' /></option>
</s:iterator>
</select>
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">From Date</label>
<div class="col-md-3">
<input type="text" class="form-control" name="fromDate" id="fromDate" placeholder="Select Date" value="" />
</div>
</div>
<div class="form-group">
<label class="col-md-2 control-label">To Date</label>
<div class="col-md-3">
<input type="text" class="form-control" name="toDate" id="toDate" placeholder="Select Date" value="" />
</div>
</div>
<div class="form-group col-md-6">
<label class="col-md-4 control-label">Report Format</label>
<div class="col-md-8">
<label class="radio-inline">
<input type="radio" name="optionsRadios" id="option1" value="pdf" checked />
PDF
</label>
<label class="radio-inline">
<input type="radio" name="optionsRadios" id="option2" value="xls" />
Excel
</label>
</div>
</div>
<div class="form-group">
<div class="col-md-6">
<button type="button" class="btn btn-sm btn-success" onclick="getShipServiceReport('shipNam','toDate' , 'fromDate')">View</button>
</div>
</div>
</form>
</div>
</div>
<!-- end panel -->
</div>
my js function/report calling function
function getShipServiceReport(ship_no,to_date, fromDate){
var shipNos=document.getElementById(ship_no).value;
var toDate=document.getElementById(to_date).value;
var fromDate=document.getElementById(fromDate).value;
var fileType=$('input[name="optionsRadios"]:checked').val();
var ajaxURL = "getShipServiceReportRT.do?ship_no="+shipNos+"&to_date="+toDate+"&fileType="+fileType+"&fromDatee="+fromDate;
window.open(ajaxURL,'_blank');
//$("#documentArea.html('<iframe src='"+ajaxURL+"' frameBorder='0' style='height:1200px;width:100%;'></iframe>')");
}
Java Action class
public void getShipServiceReport()throws JRException, ServletException, IOException{
Map<String, Object> parameters = new HashMap<String, Object>();
parameters.put("shipNo", ship_no);
parameters.put("fromDate", fromDatee);
parameters.put("toDate", to_date);
System.out.println("Parameter"+ship_no);
String filename="shipServiceInformation.jasper";
String reportType=fileType;
showReport("",parameters,filename,reportType);
}
public static void showReport(String key, Map<String, Object> parameters, String filename, String reportType)
throws JRException, ServletException, IOException {
Connection connection = null;
HttpServletResponse response = ServletActionContext.getResponse();
String outputFileName = "report_" + key;
connection = DBC.openCon();
ServletContext context = ServletActionContext.getServletContext();
String path = context.getRealPath("/");
JasperPrint jasperPrint = JasperFillManager.fillReport(path + "jasper" + "/" + filename, parameters,
connection);
OutputStream ouputStream = response.getOutputStream();
JRExporter exporter = null;
if ("pdf".equalsIgnoreCase(reportType)) {
response.setContentType("application/pdf");
response.setHeader("Content-disposition", "inline;filename=" + outputFileName + "." + reportType);
exporter = new JRPdfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
System.out.println("Report Created");
} else if ("rtf".equalsIgnoreCase(reportType)) {
response.setContentType("application/rtf");
response.setHeader("Content-disposition", "inline;filename=" + outputFileName + "." + reportType);
exporter = new JRRtfExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
} else if ("html".equalsIgnoreCase(reportType)) {
exporter = new JRHtmlExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
} else if ("xls".equalsIgnoreCase(reportType)) {
response.setContentType("application/xls");
response.setHeader("Content-disposition", "inline;filename=" + outputFileName + "." + reportType);
exporter = new JRXlsExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
} else if ("csv".equalsIgnoreCase(reportType)) {
response.setContentType("application/xls");
response.setHeader("Content-disposition", "inline;filename=" + outputFileName + "." + reportType);
exporter = new JRCsvExporter();
exporter.setParameter(JRExporterParameter.JASPER_PRINT, jasperPrint);
exporter.setParameter(JRExporterParameter.OUTPUT_STREAM, ouputStream);
}
try {
// JasperViewer.viewReport(jasperPrint, true); // for direct print
exporter.exportReport();
} catch (JRException e) {
System.out.println(e);
} finally {
if (ouputStream != null) {
try {
ouputStream.close();
} catch (Exception ex) {
System.out.println(ex);
}
}
}
}

just add this line in js function instate of "window.open(ajaxURL,'_blank');" line
$('#documentArea').html("<iframe name='your_frame_name' src='"+ajaxURL+"' height=100% width=100% > </iframe>")

Related

Request Ajax failed getting http status 403

I am trying to save some store details and getting a response from the controller using Ajax but when I am trying to do so the request is not received by the Controller please see the code and help me what I am doing wrong here.
MasterAjaxClass: The class is used to send the request and receive a response
class MasterAjax{
constructor(){
this.requestType = null;
this.url = null;
this.timeout = 100000;
this.enctype = null;
this.data = null;
this.processData = null;
this.contentType = null;
this.responseData = null;
this.responseStatus = null;
this.responseStatusCode = null;
}
requestData(callBack){
var parameterError=false;
if(null == this.requestType){
parameterError=true;
console.log("Error: Request Type can't be null");
}
if(null === this.url || undefined === this.url || "undefined" === this.url){
parameterError=true;
console.log("Error: URL can't be null");
}
if(null == this.data || this.data.length <= 0){
//console.log("Warning: Data is null");
}
if(parameterError === false){
/*toggleSpinnerOn(); */
$.ajax({
type : this.requestType,
enctype : this.enctype,
processData : this.processData,
contentType : this.contentType,
// url : global_contextPath+"/"+this.url,
url : global_contextPath+"/"+this.url,
data: this.data,
timeout : this.timeout,
success : function(responseData,textStatus) {
/*toggleSpinnerOff();*/
callBack(responseData,textStatus);
},
error : function(responseData,textStatus) {
/*toggleSpinnerOff(); */
callBack(responseData,textStatus);
}
});
}
//return this.responseData;
}
}
Ajax Request method
function saveStore(){
let formData = new FormData();
//formData.append("key" , Value ) ;
formData.append("storeName", $("#storeName").val());
formData.append("country", $("#country").val());
formData.append("city", $("#city").val());
formData.append("street", $("#street").val());
formData.append("address", $("#address").val());
formData.append("zipCode", $("#zipCode").val());
formData.append("storeDescription", $("#storeDescription").val());
formData.append("storeOpenTime", $("#storeOpenTime").val());
formData.append("logoURL", $("#file-input-2").val());
console.log($("#storeName").val());
console.log($("#country").val());
console.log($("#city").val());
console.log($("#street").val());
console.log($("#address").val());
console.log($("#zipCode").val());
console.log($("#storeDescription").val());
console.log($("#storeOpenTime").val());
console.log($("#file-input-2").val());
var obj = new MasterAjax();
obj.requestType = "POST";
obj.url = "store/saveStore";
obj.data = formData;
obj.enctype ="multipart/form-data";
obj.contentType = false;
console.log("---------------------------")
for (var pair of formData.entries()) {
console.log(pair[0]+ ': ' + pair[1]);
}
console.log("---------------------------")
obj.requestData(function(responseData){
console.log(responseData);
if(responseData.status == "OK" || responseData.status == "ok"){
alert("success");
console.log(responseData)
}else{
alert(" failed");
console.log(responseData)
}
});
}
StoreForm.jsp
<form:form name="storeForms" modelAttribute="storeForm"
method="POST" enctype="multipart/form-data">
<%-- <c:if test="${not empty error}">
<div class="alert alert-danger" role="alert">
<h5 class="alert-heading">Failed to Save</h5>
<hr>
<p>${error}</p>
</div>
</c:if>
--%>
<!-- Hidden For Update employee -->
<form:input type="hidden" path="id" />
<!-- First row -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Name</label>
<form:input type="text" path="storeName" class="form-control"
id="storeName" placeholder="Store Name" required="required" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Country</label>
<form:input type="text" id="country" path="country" class="form-control" />
</div>
</div>
<!-- Second row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">City</label>
<form:input type="text" id="city" path="city" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Street</label>
<form:input type="text" id="street" path="street" class="form-control" />
</div>
</div>
<!-- Third row container -->
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Address</label>
<form:input type="text" id="address" path="address" class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Zip Code</label>
<form:input type="text" id="zipCode" path="zipCode" class="form-control" />
</div>
</div>
<div class="form-row row-eq-spacing-sm">
<div class="col-sm">
<label for="first-name" class="required">Store Description</label>
<form:input type="text" path="storeDescription" id="storeDescription"
class="form-control" />
</div>
<div class="col-sm">
<label for="last-name" class="required">Store Timings</label>
<form:input type="text" path="storeOpenTime" id="storeOpenTime" class="form-control" />
</div>
</div>
<div class="custom-file">
<form:input type="file" path="logoURL" id="file-input-2"
data-default-value="Size of logo should not Exeed 1mb" />
<label for="file-input-2">Choose logo</label>
</div>
<!-- Submit button container -->
<div class="text-right">
<!-- text-right = text-align: right -->
<input class="btn btn-primary" type="button" onclick="saveStore();" value="Add Store">
</div>
</form:form>
Controller Method
#Controller
#RequestMapping("/store")
public class StoreController {
#ResponseBody
#RequestMapping(value = "/saveStore" , method = {RequestMethod.POST},consumes = {"multipart/form-data"})
public APIResponseModal saveStore(#ModelAttribute("storeForm") StoresDTO store,#RequestPart("logoURL") MultipartFile file) {
logger.info("Store Save MEthod callled !!!!!!!!");
Stores storeModal = new Stores();
String logopath = "";
APIResponseModal apiResponse = new Utils().getDefaultApiResponse();
List<String> errorList = new ArrayList<String>();
try {
if(store !=null){
storeModal = new Stores(store);
if(!file.isEmpty()) {
if(file.getSize()>1000000) {//1000000 bytes == 1 mb
errorList.add("File size should be less than 1 MB");
}
logopath = Utils.storeLogoPath(file);
}
storeService.saveStore(storeModal, errorList,logopath);
if(errorList.isEmpty() && !Utils.isNotNull(errorList)) {
apiResponse.setStatus(HttpStatus.OK);
apiResponse.setData("--");
apiResponse.setMessage("Store Saved Successfully !!");
}else {
apiResponse.setMessage("Failed to save store !!");
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
}
}
} catch (Exception e) {
e.printStackTrace();
apiResponse.setStatus(HttpStatus.BAD_REQUEST);
apiResponse.setData("--");
apiResponse.setMessage("Error Occured at our end !!");
}
logger.info("API RESPONSE:: ::"+ apiResponse);
return apiResponse;
}
}
Error On browser Console
Status :403

RedirectToAction in Loop process [.Net Core 3.1]

I've been struggling to finish the app I'm developing,
here is the scenario:
I have a Razor page where the user will input customer number, Company Code, and Date. Users can input multiple customer numbers and the app will split them by comma.
once the user inputted the details a button with asp-action pointed to the action named GenerateSoa, it will run a foreach statement that will RedirectToAction for every customer that is inputted on the GUI
The problem starts here when the loop runs it only opens one tab even if there are 3 customers inputted.
It should open 3 tabs with their details for 3 different customers. below is my code
I did not however include the SoaLooper cshtml file.
SoaController.cs
public IActionResult GenerateSoa()
{
ClearAmounts();
#region Date management for SOA
// First day of Current Month
var FirstDateOfCurrentMonth = new DateTime(SD.DateToday.Year, SD.DateToday.Month, 1);
var PreviousMonthFirstDay = FirstDateOfCurrentMonth.AddMonths(-1);
var PreviousMonthLastDay = DateTime.DaysInMonth(SD.DateToday.Year, PreviousMonthFirstDay.Month);
****** Ommitted some code *****
// Get last day of Previews month
var PreviewsBalanceDate = PreviousMonthFirstDay.Month.ToString() + "/" +
PreviousMonthLastDay.ToString() + "/" + PreviousMonthFirstDay.Year.ToString();
#endregion Date management for SOA
//SD.GuiCustomerNum = customer.ToString();
var bsid_unpaid_payments = _context.BSIDs.Where(l =>
(l.UMSKZ == "" || l.UMSKZ != "C") && l.BLART == "DJ");
foreach (var payments in bsid_unpaid_payments)
{
SD.PAmount += Convert.ToDouble(payments.DMBTR);
}
SD.UPTotalAmount = SD.UPAmount - SD.PAmount;
return View();
}
public IActionResult SoaLooper(string customer, int company, DateTime asof)
{
string[] customerNum = customer.Split(',');
SD.GuiCompany = company.ToString();
SD.DateToday = asof;
foreach (var item in customerNum)
{
SD.GuiCustomerNumSelected = item.ToString();
RedirectToAction(nameof(GenerateSoa));
}
return View();
}
Index.cshtml
<div class="container h-100">
<div class="row h-100 justify-content-center align-items-center border">
<form method="post" class="col-12 text-center">
<div class="col-12 border-bottom">
<h2 class="text-primary">Statement of Account</h2>
</div>
<div class="col-8 pt-4">
<div class="form-group row">
<div class="col-4">
<label class="float-right">Customer</label>
</div>
<div class="col-8">
<input id="customer" name="customer" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label class="float-right">Company Code</label>
</div>
<div class="col-8">
<select id="company" name="company" class="form-control">
<option value="">Select a number</option>
<option value="2000">2000</option>
<option value="3000">3000</option>
</select>
</div>
</div>
<div class="form-group row">
<div class="col-4">
<label class="float-right">Statement as of</label>
</div>
<div class="col-8">
<input id="asof" name="asof" type="date" class="form-control" />
</div>
</div>
<div class="form-group row">
<div class="col-8 offset-4">
<div class="row">
<div class="col">
<button type="submit" formtarget="_blank" id="btnCheck"
class="btn btn-primary form-control" asp-action="SoaLooper">Generate</button>
</div>
</div>
</div>
</div>
</div>
</form>
</div>
</div>
RedirectToAction doesn't open a new tab, it just returns a status code of 302 to tell the client to redirect.
If you really want to open multiple new tabs, you should do something like return a list of urls and then use window.open when the page loads.
I haven't tested it but you could do something like this:
Add your url to a list:
SoaController.cs
var newTabUrls = new List<string>();
foreach (var item in customerNum)
{
SD.GuiCustomerNumSelected = item.ToString();
newTabUrls.Add(nameof(GenerateSoa));
}
return View(newTabUrls);
Index.cshtml
<script type="text/javascript">
#if(Model?.Any() ?? false)
{
#foreach(var url in Model)
{
#:window.open(url, "_blank");
}
}
</script>
Open a URL in a new tab (and not a new window)
how to open a page in new tab on button click in asp.net?

how to send email using asp.net and html page

I have a contact.html page where i have textboxex page for username,email,phone,subject, message and a submit button.
<form class="contact-page-form-1">
<div class="row clearfix">
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="text" name="username" placeholder="Your Name*" id="username" required>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="email" name="email" placeholder="Email Address*" id="email" required>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="text" name="phone" placeholder="Phone Num" id="phone" required>
</div>
<div class="col-md-6 col-sm-6 col-xs-12 form-group">
<input type="text" name="subject" placeholder="Subject" id="subject" required>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
<textarea name="message" placeholder="Your Message..." id="message"></textarea>
</div>
<div class="col-lg-12 col-md-12 col-sm-12 col-xs-12 form-group">
<button class="theme-btn btn-style-one" onclick="javascript:SendMail()" type="submit" name="submit-form">Send Message</button>
</div>
</div>
</form>
when we click on the button the javascript function is called where i Called a webmethod which is in VisionMail.aspx.
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
function SendMail() {
var uname = document.getElementById("username").value;
var email = document.getElementById("email").value;
var phone = document.getElementById("phone").value;
var subject = document.getElementById("subject").value;
var message = document.getElementById("message").value;
var URL = "VisionMail.aspx?uname=" + uname + "&email=" + email + "&ph=" + phone + "&sub=" + subject + "&msg=" + message + "&count=India";
window.open(URL);
}
</script>
My WebMethod used for sending mail is in VisionMail.aspx as following:-
protected void Page_Load(object sender, EventArgs e)
{
string uname = Request.QueryString["uname"].ToString();
string email = Request.QueryString["email"].ToString();
string phone = Request.QueryString["ph"].ToString();
string subject = Request.QueryString["sub"].ToString();
string message = Request.QueryString["msg"].ToString();
string country = Request.QueryString["count"].ToString();
string close = #"<script type='text/javascript'>
window.returnValue = true;
window.close();
</script>";
using (MailMessage mail = new MailMessage())
{
mail.From = new MailAddress("abc#gmail.com");
mail.To.Add("info#xyz.com");
mail.Subject = subject;
mail.Body = "Mr. " + uname + "<br/>" + "Email ID : " + email + " Phone No. " + phone + "<br/> <h4>He/She is Sending Message From Contact Page (" + country + "). <br/>" + message;
mail.IsBodyHtml = true;
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com", 587))
{
try
{
smtp.Credentials = new NetworkCredential("abc#gmail.com", "abc123");
smtp.EnableSsl = true;
smtp.Send(mail);
base.Response.Write(close);
}
catch (Exception ex)
{
base.Response.Write(close);
}
}
}
}
This code is well on local system and mail is going but when i publish it on server it does not work and when i click on button to send mail, the mail does not go and the page which the webmethod present is downloaded. Is there any solution for this.
Try with below code.
using (SmtpClient smtp = new SmtpClient("smtp.gmail.com"))
{
try
{
smtp.Credentials = new NetworkCredential("visioncomn#gmail.com", "visioncomptel123");
smtp.EnableSsl = smtp.Port == 587 || smtp.Port == 465;
smtp.Send(mail);
base.Response.Write(close);
}
catch (Exception ex)
{
base.Response.Write(close);
}
}

Spring MVC - Child entity id lost when submitting a form

I have two entities Environnment and ServeurApplicatif that have a oneToMany relationship. I have a dynamic form with a button to add a new form each time a user wants to associate a ServeurApplicatif to on Environnement entity.When submitting the expected result is the persistence of both the environnement Entity and the ServeurApplicatif entities associated with it.
However in my case i get a 400 http error : your request is synthatically incorrect, whenever i try to submit the form.
here is the javascript code that adds the child entity related form dynamically :
<script type="text/javascript">
$(document).ready(function() {
var index = ${fn:length(env.serveurApplicatifs)};
console.log("index value :"+index);
$("#addServ").off("click").on("click",function() {
$(this).before(function() {
var html = '<div id="serveurApplicatifs'+index+'.wrapper" style="display: none;">';
html += '<input type="hidden" id="serveurApplicatifs'+index+'.idserv" name="serveurApplicatifs['+index+'].idserv" ></input>';
html += '<p><strong>Serveur Applicatif 1 : </strong></p>';
html += '<div class="form-group"><label for="serveurApplicatifs'+index+'.port">Port :</label><input class ="form-control" type="text" id="serveurApplicatifs'+index+'.port" name="serveurApplicatifs['+index+'].port" ></input></div>';
html += '<div class="form-group"><label for="serveurApplicatifs'+index+'.compte">Compte :</label><input class ="form-control" type="text" id="serveurApplicatifs'+index+'.compte" name="serveurApplicatifs['+index+'].compte" ></input></div>';
html += '<div class="form-group"><label for="serveurApplicatifs'+index+'.pwd">Mot de passe :</label><input class ="form-control" type="text" id="serveurApplicatifs'+index+'.pwd" name="serveurApplicatifs['+index+'].pwd" ></input></div>';
html += '<div class="form-group"><label for="serveurApplicatifs'+index+'.adresse">Adresse :</label><input class ="form-control" type="text" id="serveurApplicatifs'+index+'.adresse" name="serveurApplicatifs['+index+'].adresse" ></input></div>';
html += 'Supprimer';
html += "</div>";
return html;
});
$("#serveurApplicatifs"+index+"\\.wrapper").show();
index++;
return false;
});
$("a.serveurApplicatifs.remove").off("click").on("click",function() {
var index2remove = $(this).data("index");
$("#serveurApplicatifs"+index2remove+"\\.wrapper").hide();
$("#serveurApplicatifs"+index2remove+"\\.remove").val("1");
return false;
})
the Spring form tags in the jsp :
<c:url value="/envs/save" var="saveUrl"/>
<form:form action="${ saveUrl }" method="POST" modelAttribute="env">
<div class="form-group">
<form:input type="hidden" class="form-control" id="idEnv" placeholder="id" path="idEnv"></form:input><span id="star">*</span>
</div>
<!-- ------------- -->
<div class="form-group">
<label for="nom">Nom</label>
<form:input type="text" class="form-control" id="nom" placeholder="Nom" path="nom"></form:input><span>*</span>
<form:errors path="nom" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="plateforme">Platforme</label>
<form:input type="text" class="form-control" id="plateform" placeholder="Plateforme" path="platforme"></form:input>
<form:errors path="platforme" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="typologie">Typologie</label>
<form:input type="text" class="form-control" id="typologie" placeholder="Typologie" path="typologie"></form:input>
<form:errors path="typologie" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="bd">Base de donnée</label>
<form:input type="text" class="form-control" id="bd" placeholder="Bdd" path="bd"></form:input>
<form:errors path="bd" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="version">Version</label>
<form:input type="text" class="form-control" id="version" placeholder="Version" path="version"></form:input>
<form:errors path="version" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="machine_bd">Serveur de base de données</label>
<form:input type="text" class="form-control" id="machine_bd" placeholder="Machine Bdd" path="machineBd"></form:input>
<form:errors path="machineBd" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="port_bd">Port Base de données</label>
<form:input type="text" class="form-control" id="port_bd" placeholder="Port bdd" path="portBd"></form:input>
<form:errors path="portBd" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="version_bd">Version de base de données</label>
<form:input type="text" class="form-control" id="version_bd" placeholder="Version bdd" path="versionBd"></form:input>
<form:errors path="versionBd" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="type_bd">Type de base de données</label>
<form:input type="text" class="form-control" id="type_bd" placeholder="Type bdd" path="typeBd"></form:input>
<form:errors path="typeBd" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="depart">Environnement de départ</label>
<form:radiobutton value ="1" id="depart" path="depart" label="Oui"></form:radiobutton>
<form:radiobutton value ="0" id="depart" path="depart" label="Non"></form:radiobutton>
<form:errors path="depart" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="repert">Repert</label>
<form:input type="text" class="form-control" id="repert" placeholder="Repert" path="repert"></form:input>
<form:errors path="repert" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="port_ftp">Port FTP</label>
<form:input type="text" class="form-control" id="port_ftp" placeholder="Port FTP" path="portFtp"></form:input>
<form:errors path="portFtp" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="exclu">Exclu</label>
<form:radiobutton value ="1" id="exclu" path="exclu" label="Oui"></form:radiobutton>
<form:radiobutton value ="0" id="exclu" path="exclu" label="Non"></form:radiobutton>
<form:errors path="exclu" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="envsPrec">Précedent</label>
<form:select class="form-control" id="envsPrec" path="environnements2" items="${ envsPrecSuiv }" itemLabel="nom" itemValue="idEnv"/>
<form:errors path="environnements2" cssClass="error"></form:errors>
</div>
<div class="form-group">
<label for="envsSuiv">Suivant</label>
<form:select class="form-control" id="envsSuiv" path="environnements1" items="${ envsPrecSuiv }" itemLabel="nom" itemValue="idEnv"/>
<form:errors path="environnements1" cssClass="error"></form:errors>
</div>
<c:forEach varStatus="loop" var="serveurApplicatifs" items="${ env.serveurApplicatifs }">
<c:choose>
<c:when test="${env.serveurApplicatifs[loop.index].remove eq 1 }">
<div id="serveurApplicatifs${loop.index }.wrapper" style="display: none;">
</c:when>
<c:otherwise>
<div id="serveurApplicatifs${ loop.index }.wrapper">
</c:otherwise>
</c:choose>
<div class="form-group">
<form:input type="hidden" class="form-control" id="idApp" path="env.serveurApplicatifs[${loop.index}].idserv"></form:input>
</div>
<div class="form-group">
<label for="portApp">Port serveur applicatif</label>
<form:input type="text" class="form-control" id="portApp" placeholder="Port" path="env.serveurApplicatifs[${loop.index}].port"></form:input>
</div>
<div class="form-group">
<label for="compteApp">Compte serveur applicatif</label>
<form:input type="text" class="form-control" id="compteApp" placeholder="Compte" path="env.serveurApplicatifs[${loop.index}].compte"></form:input>
</div>
<div class="form-group">
<label for="pwdApp">Mot de passe serveur applicatif</label>
<form:input type="text" class="form-control" id="pwdApp" placeholder="Mot de passe" path="env.serveurApplicatifs[${loop.index}].pwd"></form:input>
</div>
<div class="form-group">
<label for="adresseApp">Adresse serveur applicatif</label>
<form:input type="text" class="form-control" id="adresseApp" placeholder="Adresse" path="env.serveurApplicatifs[${loop.index}].adresse"></form:input>
</div>
<c:choose>
<c:when test="${serveurApplicatifs[loop.index].remove eq 1}"><c:set var="hiddenValue" value="1"></c:set></c:when>
<c:otherwise><c:set var="hiddenValue" value="0"></c:set> </c:otherwise>
</c:choose>
<form:hidden path="serveurApplicatifs[${loop.index}].remove" value="${hiddenValue}"/>
Supprimer
</div>
</c:forEach>
<button type="button" class="btn btn-default" id="addServ">Ajouter Un Serveur d'application</button>
<button type="submit" class="btn btn-default" value="Save">Submit</button>
</form:form>
The Environnement entity class :
#Entity
#NamedQuery(name="Environnement.findAll", query="SELECT e FROM Environnement e")
public class Environnement implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
#Column(name="id_env")
private int idEnv;
private String bd;
private int depart;
private int exclu;
#Column(name="machine_bd")
private String machineBd;
#Column(name="mdp_bdd")
private String mdpBdd;
private String nom;
private String platforme;
#Column(name="port_bd")
private int portBd;
#Column(name="port_ftp")
private int portFtp;
private String repert;
#Column(name="type_bd")
private String typeBd;
private String typologie;
#Column(name="utilisateur_bdd")
private String utilisateurBdd;
private String version;
#Column(name="version_bd")
private String versionBd;
//bi-directional many-to-many association to Composant
#ManyToMany
#JoinTable(
name="env_comp"
, joinColumns={
#JoinColumn(name="id_env")
}
, inverseJoinColumns={
#JoinColumn(name="id_comp")
}
)
private List<Composant> composants;
//bi-directional many-to-many association to Environnement
#LazyCollection(LazyCollectionOption.FALSE)
#ManyToMany
#JoinTable(
name="lien_environnement"
, joinColumns={
#JoinColumn(name="id_env_suiv")
}
, inverseJoinColumns={
#JoinColumn(name="id_env_prec")
}
)
private List<Environnement> environnements1;
//bi-directional many-to-many association to Environnement
#LazyCollection(LazyCollectionOption.FALSE)
#ManyToMany
#JoinTable(
name="lien_environnement"
, joinColumns={
#JoinColumn(name="id_env_prec")
}
, inverseJoinColumns={
#JoinColumn(name="id_env_suiv")
}
)
private List<Environnement> environnements2;
//bi-directional many-to-one association to ServeurApplicatif
#LazyCollection(LazyCollectionOption.FALSE)
#OneToMany(mappedBy="environnement")
private List<ServeurApplicatif> serveurApplicatifs;
the ServeurApplicatif entity class :
#Entity
#Table(name="serveur_applicatif")
#NamedQuery(name="ServeurApplicatif.findAll", query="SELECT s FROM ServeurApplicatif s")
public class ServeurApplicatif implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy=GenerationType.IDENTITY)
private int idserv;
private String adresse;
private String compte;
private int port;
private String pwd;
#Transient
private Integer remove;
//bi-directional many-to-one association to Environnement
#ManyToOne
#JoinColumn(name="id_env")
private Environnement environnement;
Controller Method used to persist the entities :
#RequestMapping(value="/envs/save",method=RequestMethod.POST)
public ModelAndView saveEnvironnement(#ModelAttribute(value="env")Environnement env) {
//Environnement envFinal = this.envService.validate(env);
this.envService.gererServeur(env);
/*for (ServeurApplicatif servApp : env.getServeurApplicatifs()) {
}*/
envService.saveOrUpdate(env);
for (ServeurApplicatif servApp : env.getServeurApplicatifs()) {
servAppService.saveOrUpdate(servApp);
}
return new ModelAndView("redirect:/envs");
}
gererServeur method in EnvironnementService classe :
#Override
public List<ServeurApplicatif> gererServeur(Environnement env) {
// TODO Auto-generated method stub
List<ServeurApplicatif> serveurRemoved = new ArrayList<ServeurApplicatif>();
if(env.getServeurApplicatifs() != null) {
for (Iterator<ServeurApplicatif> iterator = serveurRemoved.iterator(); iterator
.hasNext();) {
ServeurApplicatif serveurApplicatif = iterator.next();
if(serveurApplicatif.getRemove() == 1) {
serveurRemoved.add(serveurApplicatif);
iterator.remove();
}
else {
serveurApplicatif.setEnvironnement(env);
}
}
}
return serveurRemoved;
}
Note that i'm using the solution shown here to manage the dynamic form :
Spring 3 MVC: one-to-many within a dynamic form (add/remove on create/update)
Edit :
i tried declaring the line var index = ${fn:length(env.serveurApplicatifs)}; outside of the document ready function but it didn't help, the console.log returns 0 when loading the form but gets incremented each time i clic the button to add a new form for ServeurApplicatif,the form data sent to the server is as follows :
idEnv:0
nom:
platforme:
typologie:
bd:
version:
machineBd:
portBd:0
versionBd:
typeBd:
depart:0
repert:
portFtp:0
exclu:0
_environnements2:1
_environnements1:1
serveurApplicatifs[0].idserv:
serveurApplicatifs[0].port:14523
serveurApplicatifs[0].compte:test
serveurApplicatifs[0].pwd:test
serveurApplicatifs[0].adresse:test
serveurApplicatifs[1].idserv:
serveurApplicatifs[1].port:14523
serveurApplicatifs[1].compte:test
serveurApplicatifs[1].pwd:test
serveurApplicatifs[1].adresse:test
_csrf:2d856fad-16f3-4ae4-a254-47922a695c17
you will notice that the idserv doesn't get automatically populated unlike idenv. both of these IDs are auto-increment fields in the DB, the other blank fields are nullable so the problem isn't there.
Thanks in advance.
I found what was wrong.
Basically the idserv wasn't getting the default value of 0 so that
spring can handle the request to the server and hibernate can insert the ServeurApplicatif entity alongside the Environnment entity when saveOrUpdate is invoked, so i added a value="0" to the javascript code responsible for creating form inputs for ServeurApplicatifs on the fly and now it works as expected.

Username checking not working for form with multiple register models (mvc)

I have a page which allows an admin to add multiple users to the database at once, with usernames and passwords. I use remote username checking, so in my account models I have this:
public class RegisterModel
{
[Required]
[Display(Name = "User name")]
[System.Web.Mvc.Remote("doesUserNameExist", "Account", HttpMethod = "POST", ErrorMessage = "User name already exists. Please enter a different user name.")]
public string UserName { get; set; }
// ...etc
}
In my account controller I have this:
[HttpPost]
public JsonResult doesUserNameExist(string UserName)
{
var user = Membership.GetUser(UserName);
return Json(user == null);
}
Now this works nicely on a single form, with one user being created, using the mvc html helpers. The message saying that a username is in use shows up as I'm typing it into the field. But on this form which doesn't use the mvc helpers, instead pure html and javascript, it doesn't show up:
#model List<PicsWebApp.Models.UserRegisterModel>
#{
ViewBag.Title = "NewRep";
}
<div class="col-lg-12">
<h1>First-Time Setup</h1>
</div>
<legend></legend>
<div class="col-lg-12">
<h3>Add Representatives <small>You can add more representatives later</small></h3>
#using (Html.BeginForm("NewRep", "Admin", new { jobid = ViewData["jobid"] }, FormMethod.Post, new { #class = "form" }))
{
#Html.ValidationSummary(true)
<p>
Skip
<input type="submit" class="btn btn-primary" />
<button type="button" class="btn btn-default" id="add">Add Rep</button>
</p>
<div id="fieldform" class="col-lg-12">
<div id="container0" class="col-lg-4" style="background-color: #eee; border: 4px solid white;">
<h4 style="text-align: center">New Rep</h4>
<div class="form-group">
<label>Representative Name</label><input type="text" class="form-control" name="models[0].RepName" />
</div>
<div class="form-group">
<label>Contact Number</label><input type="text" class="form-control" name="models[0].ContactNumber" />
</div>
<div class="form-group">
<label>Rep Username</label><input type="text" class="form-control" name="models[0].UserName" />
<input class="text-box single-line" data-val="true" data-val-remote="User name already exists. Please enter a different user name." data-val-remote-additionalfields="*.UserName" data-val-remote-type="POST" data-val-remote-url="/Account/doesUserNameExist" data-val-required="The User name field is required." id="UserName" name="models[0].UserName" type="text">
<span class="field-validation-valid" data-valmsg-for="UserName" data-valmsg-replace="true"></span>
</div>
<div class="form-group">
<label>Location</label><select id="select-0" class="form-control" name="models[0].Location"></select>
</div>
<div class="form-group">
<label>Rep Password</label><input type="password" class="form-control" name="models[0].Password" />
</div>
<div class="form-group">
<label>Confirm Password</label><input type="password" class="form-control" name="models[0].ConfirmPassword" />
</div>
</div>
</div>
}
</div>
<script src="https://code.jquery.com/jquery.js"></script>
<script type="text/javascript">
var selectValues = {
"Johannesburg": "Johannesburg",
"Pretoria": "Pretoria",
"Cape Town": "Cape Town",
"Pretoria": "Pretoria",
"Durban": "Durban",
"Centurion": "Centurion"
};
$.each(selectValues, function (key, value) {
$('select')
.append($('<option>', { value: key })
.text(value))
.prop("selectedIndex", -1);
});
var i = 1;
$("#add").click(function () {
var inputfield = '<div class="col-lg-4" id="' + container + i + '" style="background-color: #eee; border: 4px solid white;"><h4 style="text-align: center">New Rep</h4><div class="form-group"><label>Representative Name</label><input type="text" class="form-control" name="models[' + i + '].RepName" /></div>' +
'<div class="form-group"><label>Contact Number</label><input type="text" class="form-control" name="models[' + i + '].ContactNumber" /></div>' +
'<div class="form-group"><label>Rep Username</label><input type="text" class="form-control" name="models[' + i + '].UserName" /></div>' +
'<div class="form-group"><label>Location</label><select id="select-' + i + '" class="form-control" name="models[' + i + '].Location"></select></div>' +
'<div class="form-group"><label>Rep Password</label><input type="password" class="form-control" name="models[' + i + '].Password" /></div>' +
'<div class="form-group"><label>Confirm Password</label><input type="password" class="form-control" name="models[' + i + '].ConfirmPassword"/></div></div>'
$('#fieldform').append(inputfield)
$.each(selectValues, function (key, value) {
$('#select-' + i)
.append($('<option>', { value: key })
.text(value))
.prop("selectedIndex", -1);
});
i++
});
</script>
I understand I would have to add validation attributes to the username input fields but I tried that and it still didn't work. Any ideas?
You could validate in your controller (when the ajax request is sent) using the Validator class. This class allows you to call Validator.TryValidateObject to validate your model's data annotations such as [Required].
Then once this has passed/failed return the constructed json data with success/error messages.
Here is the article that really helped me on this:
http://odetocode.com/blogs/scott/archive/2011/06/29/manual-validation-with-data-annotations.aspx

Categories