I have a spring-Boot application, and
I am trying to send an object using post method to the below controller:
#PostMapping("/suggestevent")
public String receiveSuggestedEvent(#ModelAttribute SuggestedEvent event) {
return "redirect:/suggestEvent";
}
but it complains with:
There was an unexpected error (type=Method Not Allowed, status=405).
Request method 'POST' not supported
So, what is wrong?
Update:
I have tried this and it also did not work
#RequestMapping(value = "/suggestevent", method = RequestMethod.POST)
The form contains some simple inputes, and a select, which works based on Thyemeleaf. Here is my form:
<form th:action="#{/suggestevent}" method="post">
<div class="form-group">
<label for="title">Title</label>
<input type="text"
class="form-control" id="title" placeholder="Event title"
th:value="${event.title}"
name="title" required="required"/>
</div>
<div class="form-group">
<label for="mainFouce">Main Focus</label>
<input type="text"
class="form-control" id="Focus" placeholder="Focus"
th:value="${event.mainFouce}"
name="Focus" required="required"/>
</div>
Event Type
<div class="form-group">
<select class="form-control" name="type" th:value="${event.type}">
<option value="volvo">Party</option>
<option value="saab">Workshop</option>
<option value="fiat">Friendship</option>
</select>
</div>
<div class="form-group">
<label for="city">Area</label>
<input type="text"
class="form-control" id="area"
th:value="${event.area}"
placeholder="Berlin, Estonia ,or even Asia" name="area"
required="required"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" class="form-control"
th:value="${event.description}"
required="required" form="usrform"
placeholder="What makes it an special event?"></textarea>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
The sent object is:
#Entity
#Data
public class SuggestedEvent {
#Id
#GeneratedValue
Long id;
String title;
String mainFouce;
EventType type;
String area;
String description;
}
The postman can successfully reach the controller, but the thyemeleaf complains!!!
What happens when you try to add an empty SuggestedEvent object inside the form and try to populate that object like so:
<form th:action="#{/suggestevent}" th:object="${event}" method="post">
<div class="form-group">
<label for="title">Title</label>
<input type="text"
class="form-control" id="title" placeholder="Event title"
th:value="*{title}"
name="title" required="required"/>
</div>
<div class="form-group">
<label for="mainFouce">Main Focus</label>
<input type="text"
class="form-control" id="Focus" placeholder="Focus"
th:value="*{mainFouce}"
name="Focus" required="required"/>
</div>
Event Type
<div class="form-group">
<select class="form-control" name="type" th:value="*{type}">
<option value="volvo">Party</option>
<option value="saab">Workshop</option>
<option value="fiat">Friendship</option>
</select>
</div>
<div class="form-group">
<label for="city">Area</label>
<input type="text"
class="form-control" id="area"
th:value="*{area}"
placeholder="Berlin, Estonia ,or even Asia" name="area"
required="required"/>
</div>
<div class="form-group">
<label for="description">Description</label>
<textarea name="description" class="form-control"
th:value="*{description}"
required="required" form="usrform"
placeholder="What makes it an special event?"></textarea>
</div>
<button class="btn btn-default">Submit</button>
</form>
And in the #GetMapping("/suggestEvent"):
#GetMapping("/suggestEvent")
public String getSuggestEventPage(Model model) {
model.addAttribute("event", new SuggestEvent());
return "suggestEventPage";
}
Check out the official Thymeleaf doc otherwise. This shouldn't really be a problem, since I am doing the exact same thing in my project.
http://www.thymeleaf.org/doc/articles/standarddialect5minutes.html
http://www.thymeleaf.org/doc/articles/springmvcaccessdata.html
http://www.thymeleaf.org/documentation.html
Related
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!!!
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";
}
Hi am new to spring mvc i have to do sever side validation using separate validator class. i have two model with one to many relation i have to register them before register them i am new server side validation in spring mvc to use spring form and all
<form id="studentEnrollmentForm" method="post" class="form-horizontal" action="saveStudentByAdmin">
<div class="form-group">
<label class="col-xs-2 control-label">Student Full Name</label>
<div class="group">
<div class="col-xs-3">
<input type="text" class="form-control" name="studentFirstName" id="fn" placeholder="First name" />
</div>
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="studentMiddleName" placeholder="Middle name" />
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="studentLastName" placeholder="Last name" />
</div>
</div>
<div class="form-group">
<label class="col-xs-2 control-label">Parents Full Name</label>
<div class="col-xs-3">
<input type="text" class="form-control" name="parentFirstName" placeholder="First name" />
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="parentMiddleName" placeholder="Middle name" />
</div>
<div class="col-xs-3">
<input type="text" class="form-control" name="parentLastName" placeholder="Last name" />
</div>
</div>
<div class="form-group">
<label class="col-xs-2 control-label">Date-of-birth</label>
<div class="col-xs-3 ">
<div class="input-group input-append date" id="studentDOB">
<input type="Text" class="form-control" name="studentDOB" /> <span
class="input-group-addon add-on"><span
class="glyphicon glyphicon-calendar"></span></span>
</div>
</div>
<label class="col-xs-3 control-label">Gender</label>
<div class="col-xs-3">
<div class="btn-group" data-toggle="buttons">
<label class="btn btn-default">
<input type="radio" name="studentGender" value="male" />Male</label>
<label class="btn btn-default">
<input type="radio" name="studentGender" value="female" />Female</label>
</div>
</div>
</div>
<div class="form-group">
<label class="col-xs-2 control-label">Phone</label>
<div class="col-xs-3">
<input type="text" class="form-control" name="parentPhoneNumber" placeholder="Phone number" />
</div>
<label class="col-xs-3 control-label">Email</label>
<div class="col-xs-3">
<input type="text" class="form-control" name="parentEmail" placeholder="Email" />
</div>
</div>
<div class="form-group">
<label class="col-xs-2 control-label">Permanent Address</label>
<div class="col-xs-3">
<textarea class="form-control" rows="3" name="studentPermanentAddress" /></textarea>
</div>
<label class="col-xs-3 control-label">Present Address</label>
<div class="col-xs-3">
<textarea class="form-control" rows="3" name="studentPresentAddress" /></textarea>
</div>
</div>
<div class="form-group">
<label class="col-xs-2 control-label">Class to join</label>
<div class="col-xs-3">
<!-- <input type="text" class="form-control" name="className" placeholder="Enter Class" /> -->
<select name="className" class="form-control">
<option value="">Select class </option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
<option value="6">6</option>
<option value="7">7</option>
<option value="8">8</option>
<option value="9">9</option>
<option value="10">10</option>
</select>
</div>
</div>
<div class="form-group">
<div class="col-xs-1 ">
<button type="submit" class="btn btn-primary ">Submit</button>
</div>
<div class="col-xs-1 ">
<button type="reset" class="btn btn-default" id="rstbutton">Refresh</button>
</div>
</div>
</form>
Controller
#Controller
#RequestMapping("/")
public class AdminRegistrationController {
#Autowired
private IAdminRegistrationService adminRegistrationService;
#RequestMapping(value = "/register", method = RequestMethod.GET)
public String viewRegistrationPage(Model model) {
StudentDTO studentDTO = new StudentDTO();
ParentDTO pdto=new ParentDTO();
model.addAttribute("teacherDTO", studentDTO);
model.addAttribute("teacherDTO", pdto);
return "StudentEnrollmentByAdmin";
}
#RequestMapping(value = "/saveStudentByAdmin", method = RequestMethod.POST)
public String saveTeacherByAdmin(#ModelAttribute StudentDTO sdto,#ModelAttribute ParentDTO pdto) {
System.out.println(sdto.getStudentFirstName());
System.out.println(pdto.getParentFirstName());
return "redirect:/register"; // this line redirecting to above method to avoid same data insertion again when i press f5
//return "TeacherEnrollmentByAdmin"; To know duplication insertion comment above line and above method current this line
//when you get response page(after insertion of data) press f5 and see in data base
}
}
My Example validator class
#Component
public class StudentRegistrationFromAdminValidator implements Validator{
public boolean supports(Class<?> clazz) {
return StudentDTO.class.isAssignableFrom(clazz);
//return ParentDTO.class.isAssignableFrom(clazz);
}
public void validate(Object target, Errors errors) {
StudentDTO student = (StudentDTO)target;
ParentDTO parent = (ParentDTO)target;
String studentFirstName = student.getStudentFirstName();
String parentFirstName=parent.getParentFirstName();
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "studentFirstName", "student.studentFirstName.empty");
ValidationUtils.rejectIfEmptyOrWhitespace(errors, "parentFirstName", "parent.parentFirstName.empty");
if(studentFirstName.equals("pradee")){
errors.rejectValue("studentFirstName", "student.studentFirstName.invalid");
}
if(parentFirstName.equals("pradee")){
errors.rejectValue("parentFirstName", "parent.parentFirstName.invalid");
}
}
}
In StudentDTO and ParentDTO classes, you can give various validator annotations from javax.validation.constraints package and org.hibernate.validator.constraints package(if using hibernate).
public class StudentDTO {
#Size(min=6, max=12)
private String firstName;
#Size(min=6, max=12)
private String lastName;
//getter setter
}
Then add javax.validation.Valid annotation and
org.springframework.validation.BindingResult interface in controller method as follows.
#RequestMapping(value = "/saveStudentByAdmin", method = RequestMethod.POST)
public String saveTeacherByAdmin(#Valid #ModelAttribute StudentDTO sdto,#ModelAttribute ParentDTO pdto,
BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
System.out.println(bindingResult.getAllErrors().get(0).getDefaultMessage());
}
}
this is the html part when i add more email id's only first email is being validated and rest of emails treat as normal even if they are not in proper
<form action="<?php echo base_url()?>index.php/EMail/show_email">
<div class="form-group">
<label for="exampleInputEmail1">To :</label>
<input type="email" name="toa[]" ng-model="to" placeholder="To" class=" tagsinput" value="ss" />
</div>
<div class="form-group">
<label for="exampleInputEmail1">Subject :</label>
<input type="text" class="form-control" ng-model="sub" name="suba" id="exampleInputEmail1" placeholder="Subject">
<div>{{sub}}</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">CC :</label>
<input type="text" class="form-control" ng-model="to" name="cca" id="exampleInputEmail1" placeholder="CC">
<div>{{to}}</div>
</div>
<div class="form-group">
<label for="exampleInputEmail1">BCC:</label>
<input type="text" class="form-control" name="bcca" id="exampleInputEmail1" placeholder="BCC">
</div>
<div class="form-group ">
<label for="ccomment" class="control-label">Message</label>
<textarea class="form-control " id="ccomment" name="msg" required></textarea>
</div>
<div class="form-group">
<label for="exampleInputFile">File input</label>
<input type="file" id="exampleInputFile">
<p class="help-block">Example block-level help text here.</p>
</div>
<div class="checkbox">
<label>
<input type="checkbox"> Check me out
</label>
</div>
<input type="submit" onclick="mail()" class="btn btn-primary" value="Send"/>
<button type="submit" class="btn btn-Success">Draft</button>
</form>
this is my controller and "toa "is that field which i mentioned in the image
function show_email(){
$this->form_validation->set_rules("toa[]","To","valid_email");
$this->form_validation->set_rules("cca","CC ","valid_email");
$this->form_validation->set_rules("suba","Subject","required");
$this->form_validation->set_rules("bcca","bcc","valid_email");
$this->form_validation->set_rules("msg","Message","required");
if($this->form_validation->run()==FALSE){
$data["title"]="EMail";
$this->load->view('header',$data);
$this->load->view('sidebar');
$this->load->view('Mail/mail');
}else{
//finish
$ccdata=$this->input->post("cca");
$bccdata=$this->input->post("bcca");
$sub=$this->input->post("suba");
$ms=$this->input->post("msg");
$dataa["username"]="MyProject";
$dataa["msg"]=$ms;
$msg=$this->load->view('Email_Temp/mail',$dataa,TRUE);
$todata=explode(",",$data);
print_r($todata[0]);
//$this->SendEmail($todata,$ccdata,$bccdata,$msg,$sub);
}
}
[Image] this is the field (to) that i want to validate
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/