Spring MVC :- Form Submission (HTTP Status 400 - The request sent by the client was syntactically incorrect.) - spring

There are two forms each having one submit button in my jsp page ... I want to send form 1 to my controller which consists of two images and few form fields.
Controller.java
#RequestMapping(value="/schoolDetails",method=RequestMethod.GET)
public ModelAndView getschoolDetails(){
ModelAndView model = new ModelAndView();
School schools=new School();
Map referenceData = new HashMap();
referenceData.put("schoolObject", schools);
ModelAndView mav = new ModelAndView("schoolDetails", referenceData);
return mav;
}
#RequestMapping(value="/addSchoolDetails",method=RequestMethod.POST)
public String addSchoolDetails(#ModelAttribute("schoolObject") School school,
#RequestParam("image") MultipartFile image,#RequestParam("logo") MultipartFile logo){
if(result.hasErrors()){
return "schoolDetails"; }
Object principal = SecurityContextHolder.getContext().getAuthentication().getPrincipal();
CustomUser user=null;
if (principal instanceof CustomUser) {
user = ((CustomUser)principal);
}
return "schoolDetails";
}
schoolDetails.jsp
<form:form method="POST" role="form" action="/GenericApp/addSchoolDetails" enctype="multipart/form-data" modelAttribute="schoolObject">
<div class="col s3" id="sName">School Name :</div>
<input id="form_text" name="schoolname" type="text" placeholder="School Name"/>
<div class="col s3" id="sName">Email ID :</div>
<input id="form_text" name="email" type="email" placeholder="Email ID"/>
<div class="col s3" id="sName">State :</div>
<select name="state" id="state_id" >
<option>State</option>
<option>Karnataka</option>
</select>
<div class="col s12 m4 l4" id="sName">Upload School Logo :</div>
<input type="file" name="logo" id="fileUpload" accept="image/x-png, image/gif, image/jpeg"/>
<span class="button teal ">Choose a Image</span>
<button class="waves-effect waves-light btn" type="submit" name="action">Submit</button>
</form:form>

As your jsp does not contain any tag having name image correct your jsp file by adding tag with name image also , as below
<form:form method="POST" role="form" action="/GenericApp/addSchoolDetails" enctype="multipart/form-data" modelAttribute="schoolObject">
<div class="col s3" id="sName">School Name :</div>
<input id="form_text" name="schoolname" type="text" placeholder="School Name"/>
<div class="col s3" id="sName">Email ID :</div>
<input id="form_text" name="email" type="email" placeholder="Email ID"/>
<div class="col s3" id="sName">State :</div>
<select name="state" id="state_id" >
<option>State</option>
<option>Karnataka</option>
</select>
<div class="col s12 m4 l4" id="sName">Upload School Logo :</div>
<input type="file" name="logo" id="fileUpload" accept="image/x-png, image/gif, image/jpeg"/>
<span class="button teal ">Choose a Image</span>
<input type="file" name="image" id="image" accept="image/x-png, image/gif, image/jpeg"/>
<button class="waves-effect waves-light btn" type="submit" name="action">Submit</button>
</form:form>

Related

Request method 'GET' is not supported

have two controllers, that should give Form (html +Thymeleaf) to Update entity and post new data, after redirect to List Entities;
My Controllers
#GetMapping ("/fromUpdate")
public String updateInstructor (Model model, Long instructorId) {
Instructor instructor = instructorService.loadInstructorById(instructorId);
model.addAttribute("instructor", instructor);
return "views/updateInstructor";
}
#PostMapping ("/update")
public String update (Instructor instructor) {
instructorService.updateInstructor(instructor);
return "redirect:/instructors/index";
}
Html form + Thymeleaf
<div class="col-md-6 offset-3 mt-3">
<form class="form-control" method="post"
th:action="#{/instructors/update}" th:object="${instructor}">
<div class="mb-3 mt-3">
<label class="form-label"> Instructor Id :</label>
<input type="number" name="instructorId" class="form-control"
th:value="${instructor.getInstructorId()}">
</div>
<div class="mb-3 mt-3">
<label for="firstName" class="form-label"> First Name :</label>
<input id="firstName" type="text" name="firstName" class="form-control"
th:value="${instructor.getInstructorFirstName()}">
</div>
<div class="mb-3 mt-3">
<label for ="lastName" class="form-label"> Last Name :</label>
<input id="lastName" type="text" name="lastName" class="form-control"
th:value="${instructor.getInstructorLastName()}">
</div>
<div class="mb-3 mt-3">
<label for="instructorSummary" class="form-label"> Summary :</label>
<input id="instructorSummary" type="text" name="instructorSummary" class="form-control"
th:value="${instructor.getInstructorSummary()}">
</div>
<div class="mb-3 mt-3" th:each ="course: ${instructor.getCourses()}">
<input name="courses" class="form-control"
th:value="${instructor.courses[courseStat.index].getCourseId()}">
</div>
<div class ="mb-3 mt-3">
<input name ="user" class="form-control" th:field="${instructor.user}">
</div>
<button type ="submit" class ="btn btn-primary"> Update </button>
</form>
</div>
When i load update form i give next exception
80 --- [nio-8071-exec-1] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.HttpRequestMethodNotSupportedException: Request method 'GET' is not supported]
Must say, when i set in first controller #GetMapping (value =/update) analogical Url with Post my form load with all data.
If you know where my problem, please say me, tnx!!!

Springboot - java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'user' available as request attribute [duplicate]

This question already has answers here:
What causes "java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'command' available as request attribute"?
(7 answers)
Closed 5 years ago.
I get the following error:
java.lang.IllegalStateException: Neither BindingResult nor plain target object
for bean name 'user' available as request attribute
When I try to call this method:
#RequestMapping(value="/invite", method = RequestMethod.GET)
public ModelAndView showInvitePage(ModelAndView modelAndView,#ModelAttribute("user") User user){
return modelAndView;
}
this is the thymeleaf page:
<div class="container">
<div class="wrapper">
<form class="form-activate" th:action="#{/invite}" method="post" th:object="${user}">
<h2 class="form-activate-heading">Nodig een student uit</h2>
<p>Vul hier het e-mailadres in van de student die je wil uitnodigen:</p>
<div class="form-group">
<input type="text" th:field="*{username}" class="form-control input-lg"
placeholder="Username" tabindex="1"/>
</div>
<div class="form-group">
<input type="text" th:field="*{email}" class="form-control input-lg"
placeholder="Username" tabindex="2"/>
</div>
<div class="row">
<div class="col-xs-6 col-sm-6 col-md-6">
<input type="submit" class="btn btn-secondary" value="Invite"/>
</div>
</div>
</form>
</div>
It's odd because I have another method which is almost a copy of this one and it works perfectly fine here:
#RequestMapping(value="/register", method = RequestMethod.GET)
public ModelAndView showRegistrationPage(ModelAndView modelAndView, #ModelAttribute User user){
return modelAndView;
}
and the thymeleaf page:
<div class="wrapper">
<form class="form-signin" th:action="#{/register}" method="post" th:object="${user}">
<h2 class="form-signin-heading">Registratie</h2>
<div class="form-group">
<input type="text" th:field="*{username}" class="form-control input-lg"
placeholder="Username" tabindex="1"/>
</div>
<div class="form-group">
<input type="text" th:field="*{email}" class="form-control input-lg"
placeholder="Email" tabindex="2"/>
</div>
<div class="form-group">
<input type="password" th:field="*{encryptedPassword}" id="password" class="form-control input-lg"
placeholder="Password" tabindex="3"/>
</div>
<div class="form-group">
<input type="password" name="password_confirmation" id="password_confirmation"
class="form-control input-lg" placeholder="Confirm Password" tabindex="4"/>
</div>
The only thing I might think of is that when you call the invite method, a user is already logged in and is doing the actual inviting. When registering, no user is logged in yet.
EDIT:
I removed the thymeleaf th:field from the input fields and used the classic way and it works fine now.
<div class="form-group">
<input type="text" name="username" id="username" class="form-control input-lg"
placeholder="Username" tabindex="2"/>
</div>
<div class="form-group">
<input type="text" name="email" id="email" class="form-control input-lg"
placeholder="Email" tabindex="2"/>
</div>
You are getting this exception because there is no user object to which Spring can bind. So add one to the model in your GET method:
#GetMapping("/invite") //use shorthand
public String showInvitePage(Model model) {
model.addAttribute("user", new User()); //or however you are creating them
return "theFormNameWithoutTheExtension";
}
Then your POST would have the processing:
#PostMapping("/register")
public String showRegistrationPage(#ModelAttribute("user") User user) {
//do your processing
return "someConfirmationPage";
}

Cannot submit a form on SpringMVC

I am fairly new to SpringMVC and have a form that can not submit to the back-end. I created the form as following and when I submit it error 404 will be returned. I changed action to /MyProject/contact but did not work.
<form class="form-horizontal" role="form" method="post"
action="/contact">
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Name
</label> <input type="text" class="form-control" id="name"
name="name" placeholder="Your name" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Email
Address</label> <input type="email" class="form-control" id="email"
name="email" placeholder="Your email" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Phone
Number</label> <input type="number" class="form-control" id="phone"
name="phone" placeholder="Phone number" value="">
</div>
</div>
<div class="form-group">
<div class="col-md-12">
<label class="sr-only" for="exampleInputName2">Enquiry</label>
<textarea class="form-control" rows="4" name="message"
placeholder="Please enter your enquiry"></textarea>
</div>
</div>
<div class="form-group">
<div class="col-md-2 " style="float: right;">
<input id="submit" name="submit" type="submit" value="Send"
class="btn btn-primary">
</div>
</div>
<div class="form-group">
<div class="col-sm-10 col-sm-offset-2">
<! Will be used to display an alert to the user>
</div>
</div>
</form>
Controller
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
Error
HTTP Status 404 - /contact
type Status report
message /contact
description The requested resource is not available.
Its beacuse spring does not know how to pass the param Contact contact to your controller method. You need to do couple of things to make it work. Change your form to like below.
<form class="form-horizontal" role="form" method="post" modelAttribute="contact" action="/contact">
Your controller to take contact as model attribute.
#Controller
public class ContactController {
#RequestMapping(value="/contact", method=RequestMethod.POST)
public String processForm(#ModelAttribute Contact contact, Model model){
System.err.println("Contact Name is:" + contact.getName());
return null;
}
}
For a better understanding of what a model attribute does, there are plenty of samples and explanation online. Hope this helps.
I could solve the problem by help of minion's answer, following this tutorial and adding following link
#RequestMapping(value = "/contact", method = RequestMethod.GET)
public ModelAndView contactForm() {
System.err.println("here in GET");
return new ModelAndView("contact", "command", new Contact());
}

How to use jsp tag for select?

I have a view model and one of the fields has to be mapped to a dropdown. I manage to populate the dropdown but i don't know how to specify the selected value.
edituser.jsp
<%# include file="/WEB-INF/template/taglibs.jsp"%>
<div class="container">
<%# include file="menu.jsp"%>
<form:form commandName="editForm" method="post" class="form-horizontal form-width">
<fieldset>
<legend>Edit user</legend>
<div class="form-group">
<input class="hidden" type="text" value="${id}" hidden="true" name="id"/>
<label for="firstName" class="col-lg-2 control-label">First
name</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="firstName"
placeholder="First name" name="firstName" value="${fname}">
</div>
</div>
<div class="form-group">
<label for="lastName" class="col-lg-2 control-label">Last
name</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="lastName"
placeholder="Last name" name="lastName" value="${lname}">
</div>
</div>
<div class="form-group">
<label for="select" class="col-lg-2 control-label">Role</label>
<div class="col-lg-10">
<select name="role" class="form-control">
<option value="NONE">Select role</option>
<c:forEach items="${roles}" var="role">
<option value="${role}">${role}</option>
</c:forEach>
</select>
</div>
</div>
<div class="form-group">
<label for="username" class="col-lg-2 control-label">Username</label>
<div class="col-lg-10">
<input type="text" class="form-control" id="username"
placeholder="Username" name="username" value="${username}">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-lg-2 control-label">Password</label>
<div class="col-lg-10">
<input type="password" class="form-control" id="inputPassword"
placeholder="Password" name="password" value="${guid}">
</div>
</div>
<div class="form-group">
<label for="inputPassword" class="col-lg-2 control-label">Confirm password</label>
<div class="col-lg-10">
<input type="password" class="form-control" id="inputPassword"
placeholder="Password" name="confirmedpassword" value="${guid}">
</div>
</div>
<div class="form-group">
<div class="col-lg-10 col-lg-offset-2">
<a class="btn btn-warning" href="http://localhost:8080/Catering/index/users">Cancel</a>
<button type="submit" class="btn btn-warning">Submit</button>
</div>
</div>
</fieldset>
</form:form>
</div>
UsersController
#Controller
public class UsersController {
#RequestMapping(value = "/editUser", method = RequestMethod.GET)
public String getEditUserPage(#RequestParam int id, Model model, Authentication authentication) {
logger.debug("Received request to show edit user page(GET)");
model.addAttribute("username", "You are logged in as " + authentication.getPrincipal());
UserModel user = UserDataAccess.getUserById(id);
model.addAttribute("id", user.getId());
model.addAttribute("fname", user.getFirstName());
model.addAttribute("lname", user.getLastName());
model.addAttribute("role", user.getRole());
model.addAttribute("username", user.getUsername());
model.addAttribute("guid", guid);
model.addAttribute("editForm", new UserViewModel());
return "edituser";
}
}
UserViewModel
public class UserViewModel {
private int id;
private String firstName;
private String lastName;
private String role;
private String username;
private String password;
private String confirmedpassword;
//getters and setters
}
You can do something like (not tested)
<select name="role" class="form-control">
<option value="NONE">Select role</option>
<c:forEach items="${roles}" var="curRole">
<c:choose>
<c:when test="${curRole eq role}">
<option selected="selected">${role}</option>
</c:when>
<c:otherwise>
<option>${role}</option>
</c:otherwise>
</c:choose>
</c:forEach>
</select>
You also must add a Collection in your controller, representing the list of all roles. I cannot see it from your code.
I suggest you to take a look at spring-form.tld facilities, in your particular case: select tags: http://docs.spring.io/spring/docs/current/spring-framework-reference/html/spring-form.tld.html#spring-form.tld.select
Here you can find a simple example on how using spring:form tag: http://www.mkyong.com/spring-mvc/spring-mvc-dropdown-box-example/

Spring MVC: Multiple Models in A form: Binding problems and blank screen

I want combine 2 model(users and userData) for get Request Params but as a result i saw a blank screen. what is problem in my code?
Register object is a ModelAttribute
users and userData models have some fields.
Data Models
public class Register {
private Users users;
private UserData userData;
//getters and setters
}
register.jspx
<form:form action="register" method="post" commandName="register">
<fieldset>
<div class="span12">
<legend>Sign Up as a Merchant</legend>
</div>
<form:input type="hidden" path="enabled" value="true"/>
<div class="span6">
<div class="control-group" id="usernameCtl">
<label class="control-label" for="username">Username</label>
<div class="controls">
<form:input type="text" class="input-xlarge" id="username" path="users.username"/>
<form:errors path="users.username"/>
</div>
</div>
<div class="control-group" id="passwordCtl">
<label class="control-label" for="password">Password</label>
<div class="controls">
<form:input type="password" class="input-xlarge" id="password" path="users.password"/>
<form:errors path="users.password"/>
</div>
</div>
<div class="control-group" id="confirmCtl">
<label class="control-label" for="confirm">Confirm</label>
<div class="controls">
<form:input type="password" class="input-xlarge" id="confirm" name="confirm"/>
</div>
</div>
<div class="control-group" id="emailCtl">
<label class="control-label" for="email">Email</label>
<div class="controls">
<form:input type="text" class="input-xlarge" id="email" path="userData.email"/>
<form:errors path="userData.email"/>
</div>
</div>
</div>
<div class="span6">
<div class="control-group" id="nameCtl">
<label class="control-label" for="name">Name</label>
<div class="controls">
<form:input type="text" class="input-xlarge" id="name" path="userData.name"/>
<form:errors path="userData.name"/>
</div>
</div>
<div class="control-group" id="surnameCtl">
<label class="control-label" for="surname">Surname</label>
<div class="controls">
<form:input type="text" class="input-xlarge" id="surname" path="userData.surname"/>
<form:errors path="userData.surname"/>
</div>
</div>
<div class="control-group" id="IDNumberCtl">
<label class="control-label" for="streetAddress">Id Number</label>
<div class="controls">
<form:input type="text" class="input-xlarge" id="idNumber" path="userData.idNumber"/>
<form:errors path="userData.idNumber"/>
</div>
</div>
<div class="control-group" id="FactoryCtl">
<label class="control-label" for="city">Factory</label>
<div class="controls">
<form:select path="userData.factory">
<form:options itemValue="id" itemLabel="name" items="${factory}" />
</form:select>-->
</div>
</div>
<div class="control-group" id="IssueSectionCtl">
<label class="control-label" for="state">IssueSection</label>
<div class="controls">
<form:select path="userData.issueSection">
<form:options itemValue="id" itemLabel="name" items="${issueSection}" />
</form:select>-->
</div>
</div>
<input class="btn btn-primary btn-large" type="submit" value="Register"/>
Cancel
</div>
</fieldset>
</form:form>
UsersController_Roo_Controller
#RequestMapping(method = RequestMethod.POST, produces = "text/html",value = "/register")
public String UsersController.register(#ModelAttribute("register") Register register, BindingResult bindingResult, Model uiModel, HttpServletRequest httpServletRequest) {
if (bindingResult.hasErrors()) {
populateRegisterForm(uiModel, register);
return "userses/register";
}
uiModel.asMap().clear();
//users.setUserData(userData);
register.getUsers().persist();
return "redirect:/userses/" + encodeUrlPathSegment(register.getUsers().getId().toString(), httpServletRequest);
}
#RequestMapping(params = "register", produces = "text/html")
public String UsersController.registerForm(Model uiModel) {
populateRegisterForm(uiModel, new Register());
return "userses/register";
}
void UsersController.populateRegisterForm(Model uiModel, Register register) {
uiModel.addAttribute("factory", Factory.findAllFactorys());
uiModel.addAttribute("issueSection", IssueSection.findAllIssueSections());
uiModel.addAttribute("register",register);
}
I solved problem..
in
<input class="btn btn-primary btn-large" type="submit" value="Register"/>
I converted to  
and problem solved.

Resources