Spring MVC Form Not Submitting Value - java

Resolution
I've now managed to get this working.
It was my own oversight that was causing the null result, and thanks to #WillKeeling for pointing out that I was mapping the form to the wrong controller method.
Rather than creating a new Role object for the form to submit, I was (for an unknown reason) asking it to submit a User object.
My working JSP & Controller below:
<form:form method="POST" action="/users/${user.username}/addRole" modelAttribute="newRole">
<div class="input-group">
<span class="input-group-addon">Roles</span>
<form:select class="form-control" path="rolename" multiple="false">
<form:options items="${roles}" title="rolename" itemValue="rolename" itemLabel="rolename" />
</form:select>
<span class="input-group-addon"><input type="submit" value="Add Role" class="btn btn-xs btn-warning"/></span>
</div>
</form:form>
Controller Mapping
#RequestMapping(value = "/{username}/addRole", method = RequestMethod.POST)
public String addUserRoles(#ModelAttribute("newRole") Role newRole, #PathVariable("username") String username) {
System.out.println(newRole.getRolename());
return "redirect:/users/" + username;
}
Original Question
I may be missing something obvious here but I was hoping someone may be able to help.
I'm building an access management system for the team I work in. I've got a form on a jsp (code below) which should submit a new "role" object that can be handled into the repository in the back end.
At the moment however, when I click submit the logging reports that the value is "null". Can somebody please shed some light on why this is?
Form in JSP
<form:form method="POST" action="/users/${user.username}/addRole" modelAttribute="user">
<div class="input-group">
<span class="input-group-addon">Roles</span>
<form:select class="form-control" path="roles" multiple="false">
<form:options items="${roles}" title="roles" itemValue="rolename" itemLabel="rolename" />
</form:select>
<span class="input-group-addon"><input type="submit" value="Add Role" class="btn btn-xs btn-warning"/></span>
</div>
</form:form>
Controller
Original path is /users with the following controller.
#RequestMapping(value = "/{username}/addRole", method = RequestMethod.POST)
public String addUserRoles(#ModelAttribute("user") User user) {
System.out.println(user.getRoles());
return "redirect:/users/" + user.getUsername();
}
Result in Console
Role [rolename=null]

Related

Thymeleaf form send object with null fields to controller in weblogic server

I'm using thymeleaf for my web application. There is a problem about save and update functions. When I want to save a campaign from ui, the campaign object fields come null to rest controller class. This problem just occure in weblogic server(12.1.3). When I try it in tomcat server, do not occure any error.
my edit and create page as follow. There are a few fields for campaign, but I wrote some of them in here. Bytheway, I am sure that all fields ready in the html page. Some of them hidden, some of them visible.
<div class="row">
<form name="Form" class="col s8 offset-s2" id="upload-file-form"
enctype="multipart/form-data" th:object="${campaign}"
th:action="#{/admin/getCampaign}" onsubmit="return validateForm()"
method="post">
<div class="row">
<input type="hidden" th:field="*{id}"/>
<input type="hidden" th:field="*{version}"/>
</div>
<div class="row">
<div class="input-field">
<input id="brandname" type="text" class="validate" th:field="*{brandname}">
<label for="brandname">Brand Name</label>
</div>
</div>
</form>
</div>
#RequestMapping(value = "admin/getCampaign", method = RequestMethod.POST)
public String uploadingPost(#RequestParam("uploadingFiles") MultipartFile[] uploadingFiles,
#RequestParam("uploadingFiles1") MultipartFile[] uploadingFiles1,
#RequestParam("uploadingFiles2") MultipartFile[] uploadingFiles2,
#RequestParam("uploadingFiles3") MultipartFile[] uploadingFiles3,
Campaign campaign) throws IOException {
/** this is my controller method for save or update.
*/
}
in weblogic server campaign parameter fields come null (as a new object), but in tomcat server, everything is normal.
UPDATE:
I changed my ui fields to value like this post. But the problem continue.
<input type="hidden" th:value="*{id}"/>
Your form enctype is "multipart/form-data".
So you must add spring.http.encoding.enabled=false to application.properties.
It should be <input type="hidden" th:field="*{id}"/>not th:value

How to get inputs from my view to my controller - SPRING JAVA JPA THYMELEAF

I'm developing a webApp in java, maven, JPA and thymeleaf and I have this problem:
I have this method in my controller:
#RequestMapping(value = "/admin/searchResults", method = RequestMethod.GET)
public String listResults(#ModelAttribute Step step,Model model,#PathVariable("dateStart") Date dateStart,#PathVariable("dateEnd") Date dateEnd){
model.addAttribute("dateStart", dateStart);
model.addAttribute("dateStart", dateEnd);
return "thisAreTheDates";
}
And this is a fragment of the view that in theory has to send the 2 date parameters to my fancy controller:
<div class="container">
<form class="form-inline" data-th-action="#{/admin/searchResults}" method="get" >
<div class="input-group">
<div class="form-group">
<label>From:</label>
<input type="date" id="dateStart" class="form-control"/>
<label>To:</label>
<input type="date" id = "dateEnd" class="form-control"/>
</div>
</div>
<br/>
<button type="submit" class="button">Generate Report</button>
</form>
</div>
Everything goes so good, until I go to that view, fill the fields with 2 dates and when I press the button of generate report, this error appears:
Whitelabel Error Page
This application has no explicit mapping for /error, so you are seeing this as a fallback.
Sun May 28 10:54:07 BOT 2017
There was an unexpected error (type=Internal Server Error, status=500).
Missing URI template variable 'dateStart' for method parameter of type Date
In your HTML, you need to add name="dateStart" and name="dateEnd" to each of your dateStart and dateEnd input fields, respectively. This will allow your form connect to your model attribute.
Additionally, you will want to add a method to your controller annotated with #PostMapping to actually handle what you want to be done with your form input.
Finally, you will not want to use get on your HTML form but more likely, post.
So:
#GetMapping("/admin/searchResults") //use the shorthand
public String listResults(#ModelAttribute("step") Step step,
#PathVariable("dateStart") Date dateStart,
#PathVariable("dateEnd") Date dateEnd,
Model model) {
Step step = new Step(); //or however you are creating this
model.addAttribute("step", step);
model.addAttribute("dateStart", dateStart);
model.addAttribute("dateStart", dateEnd);
return "thisAreTheDates";
}
Your Post Mapping:
#PostMapping("/admin/searchResults") //use the shorthand
public String postResults(#ModelAttribute("step") Step step,
Errors result) {
//validate your step bean
someValidator.validate(step, result);
//persist it, do whatever
someService.save(step);
return "confirmationPage";
}
Updated HTML:
<div class="container">
<form class="form-inline" th:object="${step}" th:action="#{/admin/searchResults}" method="post" >
<div class="input-group">
<div class="form-group">
<label>From:</label>
<input type="date" name="dateStart" id="dateStart" class="form-control"/>
<label>To:</label>
<input type="date" name="dateEnd" id="dateEnd" class="form-control"/>
</div>
</div>
<br/>
<button type="submit" class="button">Generate Report</button>
</form>
</div>

Spring boot controller + thymeleaf page refresh

I am developing a dashboard page which will parse files and generate charts. So when I click submit button, I want that page should get reloaded or refreshed after successful post method. I have enabled security also, but disabled csrf().
Here is my controller,
#RequestMapping(value = "/analyze.go", method = RequestMethod.POST)
#ResponseBody
public String analyze(#RequestParam("logFile") MultipartFile file) {
//my code
return "{}";
//return "redirect:dashboard.html";
}
Here is my thymeleaf template named as dashboard.html,
<form role="form" enctype="multipart/form-data" th:action="#{/analyze.go}"
method="post">
<div class="form-group">
<label for="logFile">File input</label> <input type="file"
name="logFile" id="logFile"/>
<p class="help-block">Select only *.log or any text type of
files</p>
<input type="submit" class="btn btn-primary" value="Submit"/>
</form>
Currently it is redirecting to http://localhost:9090/analyze.go page. Any idea how to overcome this issue. I tried with returning "redirect:redirect_page" but it is not working.

Send POST request from Spring controller

I have a question to you. Let me explain the situation. We have a jsp page, there is a post form here with some inputs. When user enter some data and submit the form, my spring controller handles this request, transforms income data and then I should send it's trasformed data with post request to another site with the client redirection. In other words I want to know is it some oppotunity to use response.sendRedirect("some other website url") with post request in my controller? Or how I can do it another way?
For example simple form:
<form action="myServerSideUrl" method="post>
<input type="text" name="Input1"/>
<input type="text" name="Input1"/>
<input type="submit" value="submit"/>
</form>
When user submit it, it comes to server, then for example I sum Input1 and Input2 (Input3), and then I want to redirect user to another site with Input3 POST request.
You may use Spring's own RestTemplate or a simple java.net.URLConnection (but you have to write a bit more code) to make a POST request in your controller.
So upon receiving the request in your #Controller you can just forward it wherever you want.
<html:form action="changePassword" method="POST"
commandName="changePasswordForm">
<label> <html:password path="password" id="oldPassword"
maxlength="128" class="input" required="required"
placeholder="Current Password" />
</label>
<label> <html:password path="newPassword" id="password"
maxlength="15" required="required" class="input"
placeholder="New Password" />
</label>
<label> <html:password path="confirmPassword"
id="confirmNewPassword" maxlength="15" required="required"
class="input" placeholder="Confirm Password" />
</label>
<label> <html:input path="" type="submit" value="SAVE"
/>
</label>
</html:form>
Spring Controller is below :
#RequestMapping(value = "changePassword", method = RequestMethod.POST)
public String changePassword( #ModelAttribute(value = "searchForm") SearchForm searchForm,
Model inModel,
HttpServletRequest inRequest )
{
String viewName ="changePassPage";
// do something logic related to change password.
return viewName ;
}
Form Bean Or POJO Model in spring:
public class SearchForm
{
private String password;
private String newPassword;
private String confirmPassword;
//setter & getter;
}
You can try with Spring Post Example

Getting Null from post data from jsp

<center>
<form class="form-horizontal" action="${pageContext.servletContext.contextPath}/LargeLandmarkListGet" method="post">
<div class="form-group">
<label class="control-label col-sm-2" for="SLLRID">SLLRID:</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="SLLRID" placeholder="Enter SLLRID...">
</div>
</div>
<div class="form-group">
<div class="col-sm-offset-2 col-sm-10">
<button type="submit" class="btn btn-default">Submit</button>
</div>
</div>
</form>
</center>
That is the particular definition of the action in the JSP.
String SLLRID = request.getParameter("SLLRID");
This is how I am trying to get it in the servlet, within the doPost method. However, SLLRID is always null. I've tried everything I can think of but I cannot get it to return the inputted value. However, if I hardcode the value, everything works perfectly, so I think there is something wrong when communicating between the JSP and the servlet.
What I Have Tried:
Changing the name in for in the label definition, so that id and for are named differently
Adding an id value to the button
Hardcoding the value to verify the servlet
Trying a get rather than a post (though that seemed wildly inappropriate)
Testing other servlets with the same JSP (this worked, though not with this particular submission id)
Ensuring that everything that needed entries in web.xml had said entries made
The form sends the data based on the name attribute. So instead put: <input type="text" class="form-control" id="SLLRID" name="SLLRID" placeholder="Enter SLLRID...">

Categories