How to use jsp tag for select? - spring

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/

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!!!

Request method 'POST' not supported

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

How to do server side validation in spring mvc using validator class

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());
}
}

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());
}

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