JSP form: HttpStatus 400: The request sent by the client was syntactically incorrect - spring

I have this in a jsp:
<form:form method="POST" modelAttribute="answer">
<table>
<tr>
<td><label for="chosenanswer">answer: </label> </td>
<td>
<form:radiobutton path="chosenAnswer" value="Male" />Male
<form:radiobutton path="chosenAnswer" value="Female" />Female
<form:radiobutton path="chosenAnswer" value="Other" />Other
</td>
</tr>
When I hit the submit button, I get a HTTPStatus 400 with this message:
The request sent by the client was syntactically incorrect.
This is what I have in my Controller class:
#RequestMapping(value = { "/take-exam-{examid}" }, method = RequestMethod.GET)
public String takeExam(#PathVariable String examid, ModelMap model) {
model.addAttribute("answer",new SelectedAnswer());
model.addAttribute("questiontext","Dummy question text");
return "exam";
}
/*
*Answering a question
*/
#RequestMapping(value = { "/take-exam-{examid}" }, method = RequestMethod.POST)
public String answerQuestion(SelectedAnswer answer, BindingResult result,
ModelMap model, #PathVariable String ssn) {
model.addAttribute("answer", "SelectedAnswer: "+answer.toString());
model.addAttribute("success", "SelectedAnswer: "+answer.toString());
return "success";
}
My SelectedAnswer class is:
public class SelectedAnswer {
private String chosenAnswer;
public String getChosenAnswer() {
return chosenAnswer;
}
public void setChosenAnswer(String chosenAnswer) {
this.chosenAnswer = chosenAnswer;
}
public String toString()
{
return "SelectedAnswer = "+chosenAnswer;
}
}
The page loads fine, but when I hit the submit button, I get the error with HttpStatus 400: The request sent by the client was syntactically incorrect.
Any idea what is going on?
Thanks,
Regards,
Serban

Why is there a ssn param in answerQuestion method? Trying changing that to examid

Related

Spring not reading model attributes from form submission

In my current spring-boot project, I have this form:
<form class="form-container" id="form" method="post" th:object="${command}" th:action="#{/usuario/register}">
...
<div class="form-row">
<div class="col-25">
<label for="login">Login</label>
</div>
<div class="col-75">
<input type="text" id="login" th:field="*{username}" placeholder="Login">
</div>
</div>
...
</form>
which is handled by this spring controller:
#RequestMapping(value = "/register", method=RequestMethod.POST)
#ResponseBody
public void doRegister(#Valid Usuario object, BindingResult result) throws Exception {
this.serv.register(object);
}
my problem is that object is getting a null value, not allowing the program to persist the data. Displaying the content for both variables object and result, they show null; but if I try display the parameter's value with:
System.out.println("result.model.username: "+result.getModel().get("username"));
the correct value is shown. What's the issue here, why #Valid Usuario object, BindingResult result get me a null value, but HttpServletRequest gets the correct values?
UPDATE
Based on the sugestion below, I try this:
#ModelAttribute(value = "usuario")
public Usuario newEntity()
{
return new Usuario();
}
#RequestMapping(value = "/register", method=RequestMethod.GET)
public String formRegister(Model model) {
model.addAttribute("command", newEntity());
return "register";
}
#RequestMapping(value = "/register", method=RequestMethod.POST)
#ResponseBody
public void doRegister(#ModelAttribute("usuario") Usuario object) throws Exception {
this.serv.register(object);
}
But got the same problem.
I managed to solve this issue changing the parameter:
#ModelAttribute("usuario") Usuario object
to:
#ModelAttribute("command") Usuario object
following the suggestion in the comment above (from M.Deinum)

How to pass loop paramters from JSP to Spring Controller

I am having a loop on my JSP page and want to pass these values in my Spring Controller. On every click on Retry button in JSP, I need all values in my controller for further processing. The code which I tried so far is:
Any help much appreciated.
JSP File
<table class="gridtable">
<tr>
<th>Queue Name</th>
<th>Retry Attempt</th>
<th>Reason for failure</th>
<th>Action</th>
</tr>
<% int i=0; %>
<c:forEach var="queueRowDetail" items="${queueRowDetailList}">
<tr>
<td>${queueRowDetail.queueName}</td>
<td>${queueRowDetail.attempt}</td>
<td>${queueRowDetail.errorDetails}</td>
<td>
<form:form method="post" action="/retry" id="frmFailure_<%=i%>" modelAttribute="queueRowDetail"/>
<form:hidden path="queueName<%=i %>" value="${queueRowDetail.queueName}"/>
<form:hidden path="attempt<%=i %>" value="${queueRowDetail.attempt}"/>
<form:hidden path="errorDetails<%=i %>" value="${queueRowDetail.errorDetails} "/>
<input type="button" value="Retry" onClick="sendobj(<%=i%>)" />
</form>
</td>
</tr>
<% i++; %>
</c:forEach>
function sendObj()
<script>
function sendobj(i)
{
var x = document.getElementById("frmFailure_"+i);
alert(obj);
alert("frmFailure_"+i);
x.submit();// Form submission
}
</script>
QueueRowDetail Class
package com.gartner.gqueuefailureapi.model;
public class QueueRowDetail {
private String queueName;
private String errorDetails;
private int attempt;
private Object payLoad;
public String getQueueName() {
return queueName;
}
public void setQueueName(String queueName) {
this.queueName = queueName;
}
public String getErrorDetails() {
return errorDetails;
}
public void setErrorDetails(String errorDetails) {
this.errorDetails = errorDetails;
}
public int getAttempt() {
return attempt;
}
public void setAttempt(int attempt) {
this.attempt = attempt;
}
public Object getPayLoad() {
return payLoad;
}
public void setPayLoad(Object payLoad) {
this.payLoad = payLoad;
}
}
InderController.Java
#RequestMapping(value = "/retry", method = RequestMethod.POST)
public String retryMessage( #ModelAttribute("queueRowDetail")QueueRowDetail queueRowDetail, ModelMap model) {
model.addAttribute("queuename", queueRowDetail.getQueueName());
return "success";
}

Spring form binding return null with many-2-one relationship

Here is the problem, when I try to submit form, user entity returns null.
Form is
<form:form class="g-form" modelAttribute="objView" id="userAssignmentForm">
<form:hidden path="id" value="${objView.id}"/>
${objView.user.id}
<div class="g-form-group required">
<label for="user">User</label>
<form:hidden id="user" path="user" value="${objView.user}"/>
<input type="text" value="${objView.user.userName}" readonly="true"/>
<input type="button" class="import-input" onclick="gImport.showImportUserForm()"/>
</div>
Controller is
#RequestMapping(value = "/create", method = RequestMethod.POST)
public #ResponseBody
String create(
#ModelAttribute("objView") UserAssignmentView objView, BindingResult result,
SessionStatus status,
HttpServletRequest request) throws UnsupportedEncodingException {
UserAssignment obj = new UserAssignment();
obj.setUser(objView.getUser());
userAssignmentService.create(obj);
return "ok";
}
Model is below contains a view entity. What am I missing?
public class UserAssignmentView extends UserAssignment {
public UserAssignmentView() {
}
public UserAssignmentView(UserAssignment obj) {
setId(obj.getId());
setStatus(obj.getStatus());
setUser(obj.getUser());
}
}
And this is form view part of controller
#RequestMapping(value = "/form", method = RequestMethod.POST)
public ModelAndView form(HttpServletRequest request) {
UserAssignment obj = new UserAssignment();
Account account = AccountRegistry.getByHttpSession(request.getSession());
ModelAndView modelAndView = new ModelAndView("forms/userAssignmentForm");
modelAndView.addObject("objView", UserAssignmentWrapper.wrap(obj));
return modelAndView;
}
I could not solve since 3 days, how can I set user to userassignment?

Neither BindingResult nor plain target object for bean name 'loginuser' available as request attribute

#Controller
#RequestMapping("Page/Login.do")
public class HomeController
{
#RequestMapping(method = RequestMethod.GET)
protected String showLoginPage(HttpServletRequest req,BindingResult result) throws Exception
{
loginuser lu=new loginuser();
lu.setLoginn("Amit");
System.out.println(lu.getLoginn());
return "Login";
}
}
Above code is ##HomeController.java##
loginuser.java
package Com.Site.Name.Order;
public class loginuser
{
private String Loginn;
public String getLoginn()
{
System.out.println("hi i m in login get");
return Loginn;
}
public void setLoginn(String loginn)
{
System.out.println("I m in Loin set");
Loginn = loginn;
}
}
My JSP PAGE IS
Login.jsp
<form:form action="Login.do" method="post" commandName="loginuser">
<div id="Getin">
<img alt="" src="Image/loginttt.png">
</div>
<div id="login">
</div>
<form:input path="Loginn"/>
<input type="submit" value="LOGIN"/>
</form:form>
You are trying to use a Model attribute (commandName) but there is no such attribute added to the model or request attributes. You need to add it. Also, the BindingResult in your handler makes no sense. Remove it.
#RequestMapping(method = RequestMethod.GET)
protected String showLoginPage(HttpServletRequest req, Model model) throws Exception
{
loginuser lu=new loginuser();
lu.setLoginn("Amit");
System.out.println(lu.getLoginn());
model.addAttribute("loginuser", lu);
return "Login";
}
The Model attributes are added to the request attributes and are therefore available in the jsp.

How to show field error in a Spring Roo custom controller' form

I am stuck with the following problem: error messages are not shown in the user form, but exist in the BindingResult. Need your assistance.
I am using the Spring Roo generated controller SignUpController
#RequestMapping("/signup/**")
#Controller
public class SignUpController {
List<ObjectError> signUpErrors;
#Autowired
private SignUpValidator validator;
#ModelAttribute("UserRegistrationForm")
public UserRegistrationForm formBackingObject() {
return new UserRegistrationForm();
}
#RequestMapping(params = "form", produces = "text/html")//, method = RequestMethod.GET)
public String createForm(Model uiModel) {
populateSignUpForm(uiModel, new UserRegistrationForm());
//uiModel.addAttribute("signUpErrors", signUpErrors);
return "signup/index";
}
#RequestMapping(method = RequestMethod.POST, produces = "text/html")
public String create(#Valid UserRegistrationForm userRegistration,
BindingResult bindingResult, Model uiModel, HttpServletRequest request) {
validator.validate(userRegistration, bindingResult);
if (bindingResult.hasErrors()) {
populateSignUpForm(uiModel, userRegistration);
//uiModel.addAttribute("signUpErrors", bindingResult.getAllErrors());
return "signup/index";
}
...
for a custom form-backing object UserRegistrationForm
public class UserRegistrationForm {
#NotNull(message="Must be filled.")
#Size(min=6, max = 45)
private String login;
#Email
private String email;
#NotNull
#Size(min=6, max = 45)
, try to validate it using custom validator. I can show error messages to users, directly passing BindingResults into the jspx, and using the code as follows:
<c:if test="${signUpErrors.size()>0}">
<util:panel id="title" title="${title}">
<h2>
<spring:message code="signup_index_error" />
</h2>
<p></p>
<c:forEach var="err" items="${signUpErrors}">
<br />
<tr>
<td>${err.objectName} </td>
<td>${err.codes} </td>
<td>${err.arguments} </td>
<td>${err.defaultMessage} </td>
</tr>
</c:forEach>
</util:panel>
<p></p>
</c:if
But the standart Roo and Spring tags doesn't work:
<field:input field="login"
id="fc_.._UserRegistrationForm_login" required="true"
z="" />
<sf:errors path="login" cssStyle="error"></sf:errors>
<field:input field="email"
id="fc_.._UserRegistrationForm_email" required="true"
z="" />
<sf:errors path="*" cssStyle="error"></sf:errors>

Resources