Spring annotation for a global scope of function variables? - java

I am working on a springboot+thymeleaf project. I have a page(form) which accepts user data (startdate and enddate),and a button(Check). On click of the button, backend does some validation. If there are errors, I print the errors on the textarea within the same page (below the check button). If there are no errors, then I activate another button below the textarea, to signify that the entries between the mentioned dates are ready to be stored in the database.
<!DOCTYPE html>
<html xmlns:th="https://www.thymeleaf.org"
xmlns:sec="https://www.thymeleaf.org/thymeleaf-extras-springsecurity5">
<body>
<div th:fragment="contentinput">
<div class="container-md">
<a>Import Worklogs</a>
<div class="row justify-content-md-end">
<form modelAttribute = "userData">
<div class="row">
<div class="col-2">
<input type="text" class="form-control" id="txtFrom"
placeholder="start date(yyyy-mm-dd)" name="dateFrom">
</div>
<div class="col-2">
<input type="text" class="form-control" id="txtTo"
placeholder="end date(yyyy-mm-dd)" name="dateTo">
</div>
</div>
<div>
<br>
</div>
<div class="row">
<div class="row-2">
<input type="submit" class="btn btn-primary btn-sml"
value="check">
</div>
</div>
</form>
</div>
</div>
</div>
<div th:fragment="contentresult">
<div class="container-md">
<div class="row">
<div class="row">
<label style="color: black; font-weight: bold;">Issues: </label>
</div>
<br>
<div class="row">
<label for="Feedback"
th:text="'checking entries between '+ ${dateFrom}+' and '+ ${dateTo}"></label>
</div>
<div>
<textarea id="feedbackSection" name="story" cols="100" rows="10"
th:text="${styledErrors}">
</textarea>
</div>
</div>
<div>
<label th:if="${containsErrors}" style="color: green;"> There are
no issues. The entries can be imported</label>
<label
th:unless="${containsErrors}" style="color: red;"> There are
issues! Read the above for details</label>
</div>
<br>
<div class="row">
<div class="row-2">
<a th:if="${containsErrors}" type="button" th:attr="href='/importToDb'"
class="btn btn-primary btn-sml">Import</a>
<input th:unless="${containsErrors}" type="button" disabled="disabled"
value="Import">
</div>
</div>
</div>
</div>
<div th:fragment="contentmessage">
<div class="container-md">
<div class="row">
<label style="color: green; font-weight: bold;"
th:text="'Entries between '+ ${dateFrom}+' and '+ ${dateTo}+' are stored on the database'"></label>
</div>
</div>
</div>
</body>
</html>
I have run into a problem in my controller application for the import button. When I click on the import, I want to utilise the features that were used while clicking the button (check)
#GetMapping("/showform")
public String showForm(#RequestParam(value = "dateFrom", required = false) String dateFrom,
#RequestParam(value = "dateTo", required = false) String dateTo, Model model)
throws IOException, JSONException, InterruptedException, ExecutionException,
NumberFormatException, SQLException {
if (dateFrom != null && dateTo != null && !dateFrom.isBlank() && !dateTo.isBlank()) {
logger.info("inside the datefrom dateto");
CheckManager wm = prepareConfiguration(dateFrom, dateTo);
model.addAttribute("containsErrors", wm.getErrors().isEmpty());
model.addAttribute("styledErros", wm.getFormattedErrors(wm.getErrors()));
model.addAttribute("dateFrom", dateFrom);
model.addAttribute("dateTo", dateTo);
return "showform-errors"; //shows the fragment with contentinput and contentResult
} else {
logger.info("inside the validationform");
return "showform"; //only contentinput( having 2 textboxes for dates and a button)
}
}
private CheckManager prepareConfiguration(String dateFrom, String dateTo)
throws IOException, JSONException, InterruptedException, ExecutionException,
NumberFormatException, SQLException {
LocalDate from = LocalDate.parse(dateFrom, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
LocalDate to = LocalDate.parse(dateTo, DateTimeFormatter.ofPattern("yyyy-MM-dd"));
Request req = new Request("username", "password");
List<Entry> entrylist = req.getEntryList(from,to);
// I want this info entrylist to be used globally
return new CheckManager(entryList,from,to);
}
#GetMapping("/placeinDB")
public String placeInDb(Model model) {
logger.info("Inside the db import");
//HERE I WOULD LIKE TO USE THE DATES AND THE LIST I HAD IN THE ABOVE RETURN STATEMENT
}
Problem: When I hit the endpoint(/placeinDB) I do not have the resources like entryList, datefrom, dateTo to perform some modifications.
I am hoping there is some spring annotation that could help me here. Please let me know.

Related

Required request part 'photo' is not present

I encountered this issue on uploading image file. It say's that there is something part is missing and I have no idea. I have searched so many things already but still I couldn't find a solution. I'm trying to insert it in database and store the file in my project directory. It's seems I have missed something.
here is my html:
<form autocomplete="off" th:action="#{/AddCriminal}"
enctype="multipart/form-data" method="post" class="m-t" role="form"
th:object="${criminalRec}" data-toggle="validator">
<h1 class="text-white">Add Criminal</h1>
<div th:if="${info}" class="alert alert-success" role="alert"
th:text=${info}></div>
<div th:if="${infoError}" class="alert alert-danger" role="alert"
th:text="${infoError}"></div>
<div class="row text-center">
<div class="col-md-5">
<div th:if="${#fields.hasErrors('name')}" th:errors="*{name}"
class="validation-message alert alert-danger" role="alert"></div>
<div th:if="${#fields.hasErrors('seq_number')}"
th:errors="*{seq_number}"
class="validation-message alert alert-danger" role="alert"></div>
<div th:if="${#fields.hasErrors('comments')}"
th:errors="*{comments}"
class="validation-message alert alert-danger" role="alert"></div>
<div class="form-group">
<label class="text-white">Full Name: </label> <input type="text"
th:field="*{name}" placeholder="Wanted Full name"
class="form-control" required /> <small id="firstnameHelp"
class="form-text text-muted text-white">Full name of the
person</small>
</div>
<div class="form-group">
<label class="text-white">Sequence Number: </label> <input
type="text" th:field="*{seq_number}"
placeholder="Sequence Number" class="form-control" required /> <small
id="firstnameHelp" class="form-text text-muted text-white">Sequence
of the records the Ascending order</small>
</div>
<div class="form-group">
<label class="text-white">Photo: </label> <!-- <input type="file"
th:field="*{photo}" placeholder="Add Photo" class="form-control"
accept="image/*" required /> -->
<input type="file" name="photo" accept="image/*" class="form-control" />
<small id="firstnameHelp" class="form-text text-muted text-white">Upload
Photo</small>
</div>
</div>
<div class="col-md-12">
<div class="form-group">
<textarea class="form-control" th:field="*{comments}"
placeholder="Facts" rows="3" required></textarea>
<small id="firstnameHelp" class="form-text text-muted text-white">Facts
about this criminal</small>
</div>
</div>
<div class="col-md-5">
<button type="submit" class="btn btn-primary block full-width m-b">Add
Criminal</button>
</div>
</div>
</form>
my controller:
#RequestMapping(value = "/AddCriminal", method = RequestMethod.POST, consumes = "multipart/form-data")
public ModelAndView processCriminal(ModelAndView modelAndView,
#Valid #ModelAttribute("criminalRec") Criminals criminalRec, #RequestParam("photo") MultipartFile file,
BindingResult bindingResult, HttpServletRequest request)
throws SerialException, SQLException, IOException {
if (bindingResult.hasErrors()) {
modelAndView.setViewName("/admin/addwantedperson");
} else {
storageService.store(file);
System.out.println("FILENAME: " + storageService.getFName());
byte [] byteArr=file.getBytes();
Blob blob = new SerialBlob(byteArr);
criminalRec.setPhoto(blob);
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
LocalDate localDate = LocalDate.now();
criminalRec.setDate_added(formatter.format(localDate));
criminalService.saveCriminal(criminalRec);
modelAndView.addObject("info", "Criminal Record Successfully Added!");
modelAndView.addObject("criminalRec", new Criminals());
modelAndView.setViewName("/admin/addwantedperson");
}
return modelAndView;
}
In your Application Properties add spring.http.multipart.enabled=true

Spring Web Mvc jQuery AJAX call with post not bidinding from with #ModelAttribute

I am trying to send an AJAX call with jquery to a spring web mvc application. I have a modal which contains a form:
<div id="editTileModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myLargeModalLabel" aria-hidden="true" style="display: none;">
<div class="modal-dialog modal-lg">
<form id="frmEditTileModal" modelAttribute="editTile" class="floating-labels " action="/DESSOApplicationPortalAdmin/rest/tile/002" method="POST">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal" aria-hidden="true">×</button>
<h4 class="modal-title" id="myLargeModalLabel">Edit Tile</h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-6" >
<div class="form-group m-b-40 margin-top-20">
<input type="text" class="form-control" id="editTileId" name="id" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileId">Id</label>
</div>
<div class="form-group m-b-40">
<input type="text" class="form-control" id="editTileDescription" name="description" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileDescription">Description</label>
</div>
<div class="form-group m-b-40">
<input type="text" class="form-control" id="editTileRole" name="role" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileRole">Role</label>
</div>
</div>
<div class="col-md-6" >
<div class="form-group m-b-40 margin-top-20">
<input type="text" class="form-control" id="editTileTarget" name="target" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileTarget">Target</label>
</div>
<div class="form-group m-b-40">
<input type="text" class="form-control" id="editTileIndex" name="index" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileIndex">Index</label>
</div>
<div class="form-group m-b-40">
<input type="text" class="form-control" id="editTileTileimagename" name="tileImageName" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileTileimagename">Tile Image Name</label>
</div>
</div>
<div class="col-md-12">
<div class="form-group m-b-40">
<input type="text" class="form-control" id="editTileUrl" name="url" required><span class="highlight"></span> <span class="bar"></span>
<label for="editTileUrl">Url</label>
</div>
</div>
<div class="col-md-12">
<div class="form-group m-b-40 form-check">
<label class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input">
<span class="custom-control-indicator"></span>
<span class="custom-control-description">Disable Tile</span>
</label>
</div>
</div>
<div class="row>">
<div class="col-sm-6 col-md-6 col-xs-12">
<div class="white-box">
<h3 class="box-title">Tile Image Normal</h3>
<label for="img-tile-normal">You can add a default value</label>
<input type="file" id="img-tile-normal" class="dropify" data-default-file="resources/vendor/plugins/bower_components/dropify/src/images/test-image-1.jpg" />
</div>
</div>
<div class="col-sm-6 col-md-6 col-xs-12">
<div class="white-box">
<h3 class="box-title">Tile Image on Hover</h3>
<label for="img-tile-on-hover">You can add a default value</label>
<input type="file" id="img-tile-on-hover" class="dropify" data-default-file="resources/vendor/plugins/bower_components/dropify/src/images/test-image-1.jpg" />
</div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default waves-effect" data-dismiss="modal">Close</button>
<button id="btnSaveEditTile" type="submit" class="btn btn-danger waves-effect waves-light">Save changes</button>
</div>
</div>
</form>
<!-- /.modal-content -->
</div>
<!-- /.modal-dialog -->
This is the jQuery
$('#frmEditTileModal').submit(function (e) {
e.preventDefault();
alert("save edit start!");
var editSuccesFunc = function () {
alert('Success Edit!');
};
var editErrorFunc = function () {
alert('Error Edit!');
};
var tileId = $('#editTileId').val();
alert("data to send: " + $('#editTileId').val());
var formData = new FormData();
formData.append("id", $('#editTileId').val());
formData.append("description", $('#editTileDescription').val());
formData.append("role", $('#editTileRole').val());
$.ajax({
type: "POST",
url: "/DESSOApplicationPortalAdmin/rest/tile/" + tileId,
data: $('#frmEditTileModal').serialize(),
contentType: "application/json",
dataType: "json",
success: editSuccesFunc,
error: editErrorFunc
});
});
and this is the java controller:
#RestController
#RequestMapping(value = "rest/tile")
public class TileRestController {
#Autowired
TileService tileService;
#RequestMapping(value = "/{tileId}", method = RequestMethod.GET)
public Tile getProductById(#PathVariable(value = "tileId") String tileId) {
System.out.println("------------->" + this.getClass().getSimpleName() + ": getProductById called. Searching for Tile Id " + tileId);
return tileService.getTileById(tileId);
}
#RequestMapping(value = "/{tileId}", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseBody
public Tile update( #ModelAttribute("editTile") Tile tile, #PathVariable(value = "tileId") String tileId) {
Tile updatedTile = new Tile();
//updatedTile.setId("099");
//updatedTile.setDescription("ExampleTile");
System.out.println("------------->" + this.getClass().getSimpleName() + " update method: print object fields: "+tile.toString());
return updatedTile;
//return tileService.updateTile(tile);
}
}
When I try a doing a normal submit (no ajax or jquery) the controller correctly reads the field to the object.
However when, I try doing the same as an ajax call, it correctly sends the data but the controllers does not map it to an object via modelAttribute("editTile"). Here is a print of the class:
------------->TileRestController update method: print object fields: Tile{ tileImageName=null, description=null, role=null, url=null, target=null, index=0, id=null, disabled=false}
Am I missing something?
EDIT:
I tried a suggestion made in the answers, but it did not seem to work. Here is what I did:
I change the code of the update method in order to use the #RequestBody annotation
#RequestMapping(value = "/{tileId}", method = RequestMethod.POST, produces = { MediaType.APPLICATION_JSON_VALUE })
#ResponseBody
public Tile update( #RequestBody Tile tile, #PathVariable(value = "tileId") String tileId) {
Tile updatedTile = new Tile();
//updatedTile.setId("099");
//updatedTile.setDescription("ExampleTile");
System.out.println("------------->" + this.getClass().getSimpleName() + " update method: print object fields: "+tile.toString());
return updatedTile;
//return tileService.updateTile(tile);
}
plus, I changed my content type as well for the ajax call:
$.ajax({
type: "POST",
url: "/DESSOApplicationPortalAdmin/rest/tile/" + tileId,
data: $('#frmEditTileModal').serialize(),
contentType: "application/www-form-url-encoded",
dataType: "json",
success: editSuccesFunc,
error: editErrorFunc
});
however, now I get an ajax error, it it does not even make the call:
You seem to be Posting a JSON (content-type: application/json) from ajax.
Try using #RequestBody instead of #ModelAttribute for the Tile.
A FORM post normally gets post'ed as content-type: application/www-form-url-encoded.

Redirect to same tab on page upon Form submission - Spring MVC

I am using Spring MVC. I have a jsp page with multiple tabs. Each tab has a form. All these tabs are in a single jsp page called admin.jsp
I want to redirect the tab to itself upon POST to show errors or success message of transaction(Validation of input). What view should I return from the controller for each tab.
Controller:
#RequestMapping(value="/register", method = RequestMethod.POST)
public String registerDevice(#ModelAttribute("deviceMaster") #Validated DeviceMaster deviceMaster, BindingResult result, Model model, Locale locale) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
#RequestMapping(value="/lock", method = RequestMethod.POST)
public #ResponseBody Status lockDevice(#ModelAttribute("adminTransaction") #Validated AdminTransaction adminTransaction, BindingResult result, Model model, Locale locale,Map<String, Object> map, HttpServletRequest request, #RequestParam #DateTimeFormat(pattern="yyyy-MM-dd") Date dueDate) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
#RequestMapping(value="/unlock", method = RequestMethod.POST)
public #ResponseBody Status unlockDevice(#ModelAttribute("adminTransaction") #Validated AdminTransaction adminTransaction, BindingResult result, Model model, Locale locale,Map<String, Object> map, HttpServletRequest request) {
try {
if(result.hasErrors()){
return "admin";
}
/*CODE*/
}
admin.jsp
<div class="tabs" align="center">
<div class="list-center">
<ul class="tab-links">
<li class="active">Register</li>
<li>Lock</li>
<li>Unlock</li>
</ul>
</div>
<div class="tab-content">
<div id="tab1" class="tab active">
<div class="devices">
<form:form method="post" id="registerForm" modelAttribute="deviceMaster" action="/DeviceManager/admin/register">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" type="text" size="29"/></div>
</div>
<div>
<div class="plLabelSearch">Home Whse:</div>
<div class="plselect">
<form:select path="warehouseHome">
<form:option value="NONE" label="------- Select One -------"/>
<form:option value="TR" label="TRAINING"/>
<form:options items="${homeWhseList}" itemValue="warehouseCode" itemLabel="warehouseCode"/>
</form:select>
</div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnRegister" class="abutton">Register</a></div>
<div class="plinput"><a id="btnCancel1" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
<div id="tab2" class="tab">
<div class="devices" >
<form:form method="post" id="lockForm" modelAttribute="adminTransaction" action="/DeviceManager/admin/lock">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" size="29"/></div>
</div>
<div>
<div class="plLabelSearch">Reason Code:</div>
<div class="plselect">
<form:select path="reasonCodeForeignKey">
<form:option value="NONE" label="------- Select One -------" />
<form:options items="${reasonList}" itemValue="reasonCode" itemLabel="reasonDesc"/>
</form:select>
</div>
</div>
<div class="hidden" >
<div>
<div class="plLabelSearch">Away Whse:</div>
<div class="plselect">
<form:select path="awayWarehouse">
<form:option value="NONE" label="------- Select One -------" />
<form:options items="${homeWhseList}" itemValue="warehouseCode" itemLabel="warehouseCode"/>
</form:select>
</div>
</div>
<div>
<div class="plLabelSearch">Due Date:</div>
<div class="plinput"><form:input id="datepicker" path="dueDate" placeholder="yyyy-mm-dd"/></div>
</div>
<div>
<div class="plLabelSearch">IT Ticket:</div>
<div class="plinput"><form:input path="itTicket" value="" size="29"/></div>
</div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnLock" class="abutton">Lock</a></div>
<div class="plinput"><a id="btnCancel2" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
<div id="tab3" class="tab">
<div class="devices" >
<form:form method="post" id="unlockForm" modelAttribute="adminTransaction" action="/DeviceManager/admin/unlock">
<form:errors path="*" cssClass="plErroMessage" element="div" />
<br>
<c:if test="${not empty serverError}">
<div id="serverError" class="plErroMessage">${serverError}</div>
</c:if>
<div>
<div class="plLabelSearch">Device Id:</div>
<div class="plinput"><form:input path="deviceId" size="29"/></div>
</div>
<br>
<br>
<div>
<div class="plLabelSearch"> </div>
<div class="plinput"><a id="btnUnlock" class="abutton">Unlock</a></div>
<div class="plinput"><a id="btnCancel3" class="abutton">Cancel</a></div>
</div>
</form:form>
</div>
</div>
Handled it using jQuery and kept selected tab active on refresh with Bootstrap 3
$(document).ready(function() {
var activeTab = localStorage.getItem('activeTab');
if(activeTab){
$('.tab-links a[href="' + activeTab + '"]').tab('show');
}
$('.tabs .tab-links a').on('click', function(e) {
var currentAttrValue = jQuery(this).attr('href');
localStorage.setItem('activeTab', currentAttrValue);
jQuery('.tabs ' + currentAttrValue).siblings().slideUp(400);
jQuery('.tabs ' + currentAttrValue).delay(400).slideDown(400);
jQuery(this).parent('li').addClass('active').siblings().removeClass('active');
e.preventDefault();
});
});

Edit action returns null

I'm new to Struts2 framework and I found a problem when I try to edit an object.
The code of my modification action:
#Action(value = "modifyServer", results = {
#Result(name = "success", location = Location.MAIN_PAGE),
#Result(name = "error", location = Location.LOGIN_PAGE) })
public String modifyServer() {
em = DbConnexion.getEntityManager().createEntityManager();
String id=request.getParameter(sssid);
logger.info("id serveur = "+request.getParameter("id"));
try {
em.getTransaction().begin();
Simserver server = em.find(Simserver.class, id);
server.setSssServer(request.getParameter("sssServer"));
server.setSssIp(request.getParameter("sssIp"));
server.setSssPort(request.getParameter("sssPort"));
em.getTransaction().commit();
System.out.println("modification done !!!");
em.close();
return SUCCESS;
} catch (Exception e) {
return ERROR;
}
}
The JSP:
<form class="form-horizontal" action="modifyServer" role="form"
name="form_message" method="get">
<div id="elmsg"></div>
<div class="panel panel-info">
<div class="panel-heading expand" id="second-level">
<h6 class="panel-title">Modification du Serveur</h6>
</div>
<div class="panel-body">
<div class="form-group">
<label class="col-sm-2 control-label"> Id du Serveur : <span
class="mandatory">*</span></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sssId"
disabled="disabled" id="sssId"
value="<s:property value="#request.curentserver.sssId" />">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> Nom du Serveur : <span
class="mandatory">*</span></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sssServer"
id="sssServer"
value="<s:property value="#request.curentserver.sssServer" />">
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> Adresse IP : <span
class="mandatory">*</span></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sssIp" id="sssIp"
value="<s:property value="#request.curentserver.sssIp" />" />
</div>
</div>
<div class="form-group">
<label class="col-sm-2 control-label"> Port : <span
class="mandatory">*</span></label>
<div class="col-sm-10">
<input type="text" class="form-control" name="sssPort" id="sssPort"
value="<s:property value="#request.curentserver.sssPort" />" />
</div>
</div>
<div class="form-actions text-right">
<button type="submit" value="Envoyer" class="btn btn-success"
>Modifier le serveur</button>
<a role="button" href="gestionServeurList" class="btn btn-danger">Retour
à la list des serveurs</a>
</div>
When I execute my action the request.getParameter returns null.
I think the issue is in the parameter!
There are issues with code:
In Java code you are trying to print a request parameter with name as "id" instead of "sssId".
Also you are trying to use a variable called "sssid" that is no where defined in your question.
String id=request.getParameter(sssid);
logger.info("id serveur = "+request.getParameter("id"));
In JSP the sssId element is disabled, when you submit a form the disabled elements are ignored.
<input type="text" class="form-control"
name="sssId" disabled="disabled" id="sssId"
value="<s:property value="#request.curentserver.sssId" />">
So to get its value, create a hidden element in your jsp and on form submission update the hidden element with the required value using JavaScript.
<input type="hidden" name="sssId" value=""/>
In Javascript it will be like:
document.getElementById("sssId").value = 123; // Give value here
document.getElementById("myForm").submit(); // Give an Id to your form, say "myForm"
Finally the Action code looks like this :
public class MyAction extends ActionSupport implements ServletRequestAware {
#Action(value = "modifyServer", results = {
#Result(name = "success", location = Location.MAIN_PAGE),
#Result(name = "error", location = Location.LOGIN_PAGE) })
public String modifyServer() {
String id = request.getParameter("sssId");
System.out.println("id serveur = " + id);
return null;
}
private HttpServletRequest request;
#Override
public void setServletRequest(HttpServletRequest request) {
this.request = request;
}
}
If the input element has disabled="disabled" attribute it won't include as parameter when your form is submitted. Also rename the input element name that correspond to a parameter name. Struts2 getter/setter can be used to populate the action bean.
public void setSssId(String id){
this.id = id;
}
I'd suggest checking value of sssId being passed to the action through javascript.
<button onclick='javascript:submitMyForm();' type="button" value="Envoyer" class="btn btn-success"
>Modifier le serveur</button>
write the following javascript
function submitMyForm(){
var sssIdElement = document.getElementById("sssId");
document.form_message.action = "modifyServer.action?sssId="+sssIdElement;
document.form_message.submit();
}

getParamter() returns NULL

Why is request.getParameter("termin"); returning NULL
.The Connection and the Statement for my Databse are correct.It works fine in an more simple Version.
This is JSp/JAva Code:
int result = 0;
if(request.getParameter("submit") != null) {
String name = new String();
if(request.getParameter("termin") != null) {
name = request.getParameter("termin");
}else {
out.println("termin is null");
}
Termin t1 = new Termin();
result = t1.setTermin(name);
Here is the HTML Code :
<form action="index.jsp" method="POST" name="test">
<div class="modal fade" id="bModal" tabindex="-1" role="dialog" aria-labelledby="beispielModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Schließen</span></button>
<h4 class="modal-title" id="beispielModalLabel">Neuer Termin</h4>
</div>
<div class="modal-body">
<!-- <form role="form" action="index.jsp" method="POST"> -->
<div class="form-group">
<label for="empfaenger-name" class="control-label">Name</label>
<input type="text" class="form-control" id="empfaenger-name" name="termin" value="">
</div>
<div class="form-group">
<label for="nachricht-text" class="control-label">Zusätzlich:</label>
<textarea class="form-control" id="nachricht-text"></textarea>
</div>
<!-- </form> -->
</div>
<div class="modal-footer">
<button type="button" class="btn btn-danger" id="del" data-dismiss="modal" >Löschen</button>
<input type="submit" name="submit" class="btn btn-primary" id="eintrag" data-dismiss="modal" value="Speichern" >
</div>
</div>
</div>
</div>
</form>
I'm not a Bootstrap expert yet I can see a few potential causes to this issue:
data-dismiss="modal"- looking at:
http://getbootstrap.com/javascript/#modals-related-target it seems that data-dismiss="modal" is used only with "close" buttons - never with "submit"!
the class class="btn btn-primary" is supposed to be used with elements of type button and you're using it with input
using the id attribute might create a conflict with bootstrap autogenerated html-elements, but I'm just guessing here based on your comment above.

Categories