I've two classes
public class User {
private int id;
priavte List<Hobby> hobbies;
//setter getter
}
public class Hobby {
private int id;
private String hobbyName;
//setter getter
}
now i want to create form for User.java
my form.jsp is
<form:form method="POST" action="saveEmployee.html" commandName="user" name="register-form" id="register-form" cssClass="smart-green">
<form:select path="hobbies" multiple="true" size="3">
<form:option value="1">Cricket</form:option>
<form:option value="2">Computer Games</form:option>
<form:option value="3">Tennis</form:option>
<form:option value="4">Music</form:option>
</form:select>
</form:form>
myController.java
#RequestMapping(value = "/saveEmployee.html", method = RequestMethod.POST)
public ModelAndView addEmployee(
#ModelAttribute("user") User user BindingResult result) {
System.out.println(user.getChoice()); // giving null
// usrDao.saveUser(user);
return new ModelAndView("redirect:add.html", model);
}
How could i get the value for List from my form so that i could get the value?
The Solution to Bind your multi select value to the POJO Object list is done under CustomCollectionEditor class. This is important when binding complex data types such as in your case.
Add this below code in your controller class myController.java :
#InitBinder
protected void initBinder(WebDataBinder binder)
{
binder.registerCustomEditor(List.class, "hobbies", new CustomCollectionEditor(List.class)
{
#Override
protected Object convertElement(Object element)
{
Long id = null;
String name = null;
if(element instanceof String && !((String)element).equals(""))
{
//From the JSP 'element' will be a String
try{
id = Long.parseLong((String) element);
}
catch (NumberFormatException e) {
e.printStackTrace();
}
}
else if(element instanceof Long)
{
//From the database 'element' will be a Long
id = (Long) element;
}
// Here you can get Hobby object from database based on the id you have got.
//You any other way you can get hobbyName and set in hobby object and return it
Hobby h = new Hobby();
h.setId(Integer.parseInt(String.valueOf(id)));
h.setHobbyName(name);
return h;
}
});
}
Reference Link for more details :
SpringMVC bind Multi Select with object in Form submit
Multiple Select in Spring 3.0 MVC.
Related
I created a custom validation to <form:select> that populate country list.
Customer.jsp
Country:
<form:select path="country" items="${countries}" />
<form:errors path="country" cssClass="error"/>
FomeController.java
#RequestMapping(value = "/customer", method = RequestMethod.POST)
public String prosCustomer(Model model,
#Valid #ModelAttribute("defaultcustomer") Customer customer,
BindingResult result
) {
CustomerValidator vali = new CustomerValidator();
vali.validate(customer, result);
if (result.hasErrors()) {
return "form/customer";
} else {
...
}
}
CustomValidator.java
public class CustomerValidator implements Validator {
#Override
public boolean supports(Class<?> type) {
return Customer.class.equals(type);
}
#Override
public void validate(Object target, Errors errors) {
Customer customer = (Customer) target;
int countyid=Integer.parseInt(customer.getCountry().getCountry());
if (countyid==0) {
errors.rejectValue("country", "This value is cannot be empty");
}
}
}
Customer.java
private Country country;
Validation is working perfectly fine. But the problem is that the validation method has attached another message too.
Please tell me how to correct this message.
Can you try changing the implementation of Validator in controller as explained in https://stackoverflow.com/a/53371025/10232467
So you controller method can be like
#Autowired
CustomerValidator customerValidator;
#InitBinder("defaultcustomer")
protected void initDefaultCustomerBinder(WebDataBinder binder) {
binder.addValidators(customerValidator);
}
#PostMapping("/customer")
public String prosCustomer(#Validated Customer defaultcustomer, BindingResult bindingResult) {
// if error
if (bindingResult.hasErrors()) {
return "form/customer";
}
// if no error
return "redirect:/sucess";
}
Additionally the form model name in jsp should be defined as "defaultcustomer"
EDIT :
I missed the nested Country object in Customer class. In validator replace
errors.rejectValue("country", "This value is cannot be empty");
with
errors.rejectValue("defaultcustomer.country", "This value is cannot be empty");
Also found that Customer class should be modified as
#Valid
private Country country;
I am trying to make a select box using jstl throgh model view and i am a pure noob, someone i have gone through this and created this can anyone help me to get the monngodb values in select box
here are my codes
Controller
#RequestMapping(value = "getSpeciality", method = RequestMethod.GET)
public ModelAndView getSpeciality(HttpServletRequest request) {
Map<String, Object> myModel = new HashMap<String, Object>();
myModel.put("myVar", getSpeciality( UtilsManagementService.getSpeciality() )); // here is showing error UtilsManagementService cannot be resolved
return new ModelAndView("view", myModel);
}
Management layer
package com.geniedoc.management.service;
import java.util.List;
import com.geniedoc.exception.BussniessException;
import com.geniedoc.exception.UserNotFoundException;
import com.geniedoc.vo.CityVo;
import com.geniedoc.vo.SpecialityVO;
public interface UtilsManagementService {
public List<SpecialityVO> getSpeciality(String key) throws BussniessException; }
DB
#Override
public Speciality getSpeciality(String specialityName) {
Query findSpecialityQuery = new Query();
findSpecialityQuery.addCriteria(Criteria.where(SPECIALITY_NAME).regex(specialityName));
Speciality speciality = null;
try{
speciality = this.specialityRepository.getDocument(Speciality.class, findSpecialityQuery, SPECIALITY_TABLE);
}catch(MongoDBDocumentNotFoundException e){
e.printStackTrace();
}
return speciality;
}
and jsp
<select id="Speciality" name=""Speciality"">
<c:forEach var="item" items="${myModel}">
<option value="${item.key}">${item.value}</option>
</c:forEach>
</select>
Speciality Vo
package com.geniedoc.vo;
public class SpecialityVO {
private int _id;
private String speciality_name;
private String speciality_description;
public String getSpeciality_name() {
return speciality_name;
}
public void setSpeciality_name(String speciality_name) {
this.speciality_name = speciality_name;
}
public String getSpeciality_description() {
return speciality_description;
}
public void setSpeciality_description(String speciality_description) {
this.speciality_description = speciality_description;
}
public int get_id() {
return _id;
}
public void set_id(int _id) {
this._id = _id;
}
}
You need to inject UtilsManagementService (which would have an Implementation) to your Controller. Define the bean and autowire it.
Then use the model which is return by the service.
I do not find any issues with your jstl code.
I am new to spring + hibernate. When I add a customer and its destinations (one to many relationship), everything is fine. But when I update the customer's destination, all previous destinations remain in the database with a null customer foreign key.
Suppose I insert 4 destinations a, b, c, d. After updating the customer, I insert x, y. Then it stores total 6 destinations: a, b, c, d with null references and x, y with customer references.
Here is my code:
1). Customer Entity
Has one-to-many relationship with destination and relationship is unidirectional.
#Entity
#Table(name="customers")
#Proxy(lazy=false)
public class CustomerEntity {
#Id
#Column(name="id")
#GeneratedValue
private Integer id;
private String description;
private String panNo;
private String cstNo;
private String vatNo;
#OneToMany(fetch = FetchType.EAGER,cascade = CascadeType.ALL)
#JoinColumn(name = "customer_id", referencedColumnName = "id")
public List<DestinationsEntity> destination = new AutoPopulatingList<DestinationsEntity>(DestinationsEntity.class);
//getter and setters
}
2). Destination Entity
#Entity
#Table(name = "destinations")
#Proxy(lazy = false)
public class DestinationsEntity {
#Id
#Column(name = "id")
#GeneratedValue
private Integer id;
#Column(name="destination")
private String destination;
// getter and setter
}
1). AddCustomer.jsp
This code for adding more destinations in Autopopulate list
<div id="destination_container">
<div><textarea row="3" col="5" class="destination_address" name= "destination[${0}].destination" placeholder="Please enter address"></textarea></div>
</div>
<script type="text/javascript">
$(document).ready(function(){
var index = 1;
/*
* Add more destination
*/
$('#add_more_destination').click(function(){
$('#destination_container').append('<div><textarea row="3" col="5" class="destination_address" name= "destination[${"'+index+'"}].destination" placeholder="Please enter address"></textarea><span class="remove_dest">*</span></div>');
index++;
});
});
</script>
2). updateCustomer.jsp
All destinations added by customer is show here and he/she can be change destinations(like before inserted pune, mumbai , banglore) now updating destinations( delhi, punjab)
<c:set var="index" scope="page" value="${fn:length(destinationss)}"/>
<c:forEach items="${destinationss}" var="dest" varStatus="i">
<div>
<textarea class="destination_address" name= "destination[${i.index}].destination" placeholder="Please enter address">${dest.destination}</textarea><span class="remove_dest">*</span>
</div>
</c:forEach>
<button type ="button" id="add_more_destination">Add More Destinations</button>
<script type="text/javascript">
$(document).ready(function(){
/*
* Add a destination
*/
var index = ${index};
$('#add_more_destination').click(function(){
$('#destination_container').append('<div><textarea row="3" col="5" class="destination_address" name=destination["'+index+'"].destination placeholder="Please enter address"></textarea><span class="remove_dest">*</span></div>');
alert(index);
index++;
});
</script>
Controller
#RequestMapping(value = "/addCustomerForm", method = RequestMethod.GET)
public String addCustomerForm(ModelMap map) {
return "master/addCustomer";
}
#RequestMapping(value = "/addCustomer", method = RequestMethod.POST)
public String addCustomer(#ModelAttribute(value = "customer") CustomerEntity customer,BindingResult result, HttpServletRequest request) {
customerService.addCustomer(customer);
return "redirect:/customer";
}
Update Customer
This is new thing I tried last night. Problem is solved partially.
#ModelAttribute
public void updateOperation(HttpServletRequest request, ModelMap map) {
if(null !=request.getParameter("id"))
map.addAttribute("customer1", customerService.findOne(Integer.parseInt(request.getParameter("id"))));
}
#RequestMapping(value = "/updateCustomerForm/{customerId}", method = RequestMethod.GET)
public String updateCustomerForm(#PathVariable("customerId") Integer customerId, ModelMap map, HttpServletRequest request) {
CustomerEntity customerEntity = customerService.findOne(customerId);
map.addAttribute("customer", customerEntity);
map.addAttribute("destinationss",customerEntity.getDestination());
}
#RequestMapping(value = "/updateCustomer", method = RequestMethod.POST)
public String updateCustomer(#ModelAttribute(value = "customer1")CustomerEntity customer1,BindingResult result, HttpServletRequest request,HttpServletResponse response) {
customerService.updateCustomer(customer1);
return "redirect:/customer";
}
}
1). CustomerServiceImpl
public class CustomerServiceImpl implements CustomerService{
#Autowired
private CustomerDao customerDao;
#Override
#Transactional
public void addCustomer(CustomerEntity customer) {
customerDao.addCustomer(customer);
}
#Override
#Transactional
public CustomerEntity findOne(Integer id){
return customerDao.findOne(id);
}
#Override
#Transactional
public void updateCustomer(CustomerEntity customerEntity){
if (null != customerEntity) {
customerDao.updateCustomer(customerEntity);
}
}
}
2).CustomerDaoImpl
public class CustomerDaoImpl implements CustomerDao{
#Autowired
private SessionFactory sessionFactory;
#Override
#Transactional
public void addCustomer(CustomerEntity customer){
this.sessionFactory.getCurrentSession().save(customer);
}
#Override
public CustomerEntity findOne(Integer id){
return (CustomerEntity) sessionFactory.getCurrentSession().load(CustomerEntity.class, id);
}
#Override
#Transactional
public void updateCustomer(CustomerEntity customerEntity){
if (null != customerEntity) {
this.sessionFactory.getCurrentSession().update(customerEntity);
}
}
}
The issue is Spring will give you new Customer entity, so I guess the Destination entities in this Customer is empty initially. So in your update operation you are just adding some new Destination entities and then adding them to customer as per your code.
So in this case, the customer entity is having only the new Destination objects where as the already existing Destination entities which were mapped earlier are not present in your Customer entity.
To fix the issue, first get the Customer entity from database, then this entity will have the set of Destination objects. Now to this Customer you can add new Destination objects and also update the existing Destination objects if needed then ask Hibernate to do the update operation. In this case Hibernate can see your earlier destination objects and also the new destination objects and based on that it will run the insert & update queries.
The code looks something like this:
// First get the customer object from database:
Customer customer = (Customer) this.sessionFactory.getCurrentSession().get(Customer.class, customerId);
// Now add your destination objects, if you want you can update the existing destination entires here.
for (int i = 0; i < destinationAddrs.length; i++) {
DestinationsEntity destination = new DestinationsEntity();
destination.setDestination(destinationAddrs[i]);
customer.getDestinationEntity().add(destination);
}
// Then do the update operation
this.sessionFactory.getCurrentSession().update(customer);
I'm hoping somebody can help me this... I've been looking at this error for a while now.
I'm getting a "HTTP Status 400 - The request sent by the client was syntactically incorrect." error on the submit of a spring form.
The error is related to following code in my JSP spring form.
<form:input path="game_week_id"></form:input>
When I removed this line of code the error is not thrown (but of course I want to set the game_week_id from the form value entered). Just to note that game_week_id isn't actually an id (primary key) of the fixtures table - but just a name which I've given the column. The primary key for the table is actually an autonumber.
I want to insert a row into my fixtures table (based on the user form input) which is controlled by the Fixtures class.
I'm thinking I have something wrong in the binding of the game_week_id form field back to the object (or maybe the issue is the binding of game_week_id to the underlying database column).
Any direction or any help would be appreciated (go easy on me! - I'm aware this is probably something stupid I'm doing)
Code from my controller, Fixture object and JSP form is displayed below:
//CONTROLLER
#RequestMapping(value="/addFixtures", method=RequestMethod.POST)
public ModelAndView registerFixture(#ModelAttribute Fixture fixture, Map<String, Object> map1, HttpServletRequest request1)
{
String message;
System.out.println("Adding fixture..");
ModelAndView modelAndView = new ModelAndView();
System.out.println("Fixture: Game Week ID " + fixture.getGame_week_id());
System.out.println("Fixture: Game ID " + fixture.getGame_id());
fixtureService.addFixture(fixture);
modelAndView.setViewName("addFixtures");
message = "Fixture successfully added";
modelAndView.addObject("message", message);
return modelAndView;
}
Fixture Class
#Entity
#Table(name = "fixtures")
public class Fixture implements java.io.Serializable {
private Integer id;
public Gameweek game_week_id;
private Integer game_id;
private PPTeam home_team;
private PPTeam away_team;
public Fixture(){
}
public Fixture(
Gameweek game_week_id,
Integer game_id,
PPTeam home_team, PPTeam away_team, PPTeam homeTeam) {
this.game_week_id = game_week_id;
this.game_id = game_id;
this.home_team = home_team;
this.away_team = away_team;
}
#Id
#GeneratedValue
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
#ManyToOne(cascade = CascadeType.PERSIST)
#JoinColumn(name ="game_week_id")
public Gameweek getGame_week_id() {
return game_week_id;
}
public void setGame_week_id(Gameweek game_week_id) {
this.game_week_id = game_week_id;
}
public void setGame_week_id_int(Integer game_week_id_int) {
this.game_week_id = game_week_id;
}
public Integer getGame_id() {
return game_id;
}
public void setGame_id(Integer game_id) {
this.game_id = game_id;
}
#ManyToOne
#JoinColumn(name = "home_team", referencedColumnName = "teamId")
public PPTeam getHome_team() {
return this.home_team;
}
public void setHome_team(PPTeam home_team) {
this.home_team = home_team;
}
#ManyToOne
#JoinColumn(name = "away_team", referencedColumnName = "teamId")
public PPTeam getAway_team() {
return this.away_team;
}
public void setAway_team(PPTeam away_team) {
this.away_team = away_team;
}
#Override
public String toString() {
return "Fixture [id=" + id + ", game_week_id=" + game_week_id
+ ", game_id=" + game_id + ", home_team=" + home_team
+ ", away_team=" + away_team + "]";
}
}
And finally my JSP form
<form:form method="POST" commandName="fixture" action="${pageContext.request.contextPath}/team/addFixtures">
<table>
<tr>
<td>Gameweek Number:</td>
<td>
<form:input path="game_week_id"></form:input>
</td>
</tr>
<tr>
<td>Game No:</td>
<td>
<form:input path="game_id"></form:input>
</td>
</tr>
</table>
<br>
<input type="submit" value ="Add Fixture">
</form:form>
What is your GameWeek class? I thing that problem is that you try to bind text-field to an object GameWeek. When you send request with game_week_id it is string in Spring model map, and Spring cant make an GameWeek object from string.
I have been wrestling with how to implement a form that creates many-to-many relations in a web application I am building with Spring 3 and Hibernate 4. I am trying to build a simple blog tool with a tagging system. I have created a model BlogPost that has a many-to-many relationship with the model Tags. When I create a new BlogPost object, the web form input for tags is a single-lined text input. I'd like to be able to split this text string by whitespace and use it to create Tag objects. Alternatively, when editing an existing BlogPost, I'd like to be able to take the Set of Tag objects associated with the BlogPost and convert it to a String that is used as the value of the input element. My problem is in converting between the text input and the referenced set of Tag objects using my form.
What is the best practice for binding/fetching/updating many-to-many relationships with web forms? Is there an easy way to do this that I am unaware of?
UPDATE
I decided, as suggested in the answer below, to manually handle the object conversion between the String tag values in the form and the Set<Tag> object required for the object model. Here is the final working code:
editBlogPost.jsp
...
<div class="form-group">
<label class="control-label col-lg-2" for="tagInput">Tags</label>
<div class="col-lg-7">
<input id="tagInput" name="tagString" type="text" class="form-control" maxlength="100" value="${tagString}" />
</div>
<form:errors path="tags" cssClass="help-inline spring-form-error" element="span" />
</div>
....
BlogController.java
#Controller
#SessionAttributes("blogPost")
public class BlogController {
#Autowired
private BlogService blogService;
#Autowired
private TagService tagService;
#ModelAttribute("blogPost")
public BlogPost getBlogPost(){
return new BlogPost();
}
//List Blog Posts
#RequestMapping(value="/admin/blog", method=RequestMethod.GET)
public String blogAdmin(ModelMap map, SessionStatus status){
status.setComplete();
List<BlogPost> postList = blogService.getAllBlogPosts();
map.addAttribute("postList", postList);
return "admin/blogPostList";
}
//Add new blog post
#RequestMapping(value="/admin/blog/new", method=RequestMethod.GET)
public String newPost(ModelMap map){
BlogPost blogPost = new BlogPost();
map.addAttribute("blogPost", blogPost);
return "admin/editBlogPost";
}
//Save new post
#RequestMapping(value="/admin/blog/new", method=RequestMethod.POST)
public String addPost(#Valid #ModelAttribute BlogPost blogPost,
BindingResult result,
#RequestParam("tagString") String tagString,
Model model,
SessionStatus status)
{
if (result.hasErrors()){
return "admin/editBlogPost";
}
else {
Set<Tag> tagSet = new HashSet();
for (String tag: tagString.split(" ")){
if (tag.equals("") || tag == null){
//pass
}
else {
//Check to see if the tag exists
Tag tagObj = tagService.getTagByName(tag);
//If not, add it
if (tagObj == null){
tagObj = new Tag();
tagObj.setTagName(tag);
tagService.saveTag(tagObj);
}
tagSet.add(tagObj);
}
}
blogPost.setPostDate(Calendar.getInstance());
blogPost.setTags(tagSet);
blogService.saveBlogPost(blogPost);
status.setComplete();
return "redirect:/admin/blog";
}
}
//Edit existing blog post
#Transactional
#RequestMapping(value="/admin/blog/{id}", method=RequestMethod.GET)
public String editPost(ModelMap map, #PathVariable("id") Integer postId){
BlogPost blogPost = blogService.getBlogPostById(postId);
map.addAttribute("blogPost", blogPost);
Hibernate.initialize(blogPost.getTags());
Set<Tag> tags = blogPost.getTags();
String tagString = "";
for (Tag tag: tags){
tagString = tagString + " " + tag.getTagName();
}
tagString = tagString.trim();
map.addAttribute("tagString", tagString);
return "admin/editBlogPost";
}
//Update post
#RequestMapping(value="/admin/blog/{id}", method=RequestMethod.POST)
public String savePostChanges(#Valid #ModelAttribute BlogPost blogPost, BindingResult result, #RequestParam("tagString") String tagString, Model model, SessionStatus status){
if (result.hasErrors()){
return "admin/editBlogPost";
}
else {
Set<Tag> tagSet = new HashSet();
for (String tag: tagString.split(" ")){
if (tag.equals("") || tag == null){
//pass
}
else {
//Check to see if the tag exists
Tag tagObj = tagService.getTagByName(tag);
//If not, add it
if (tagObj == null){
tagObj = new Tag();
tagObj.setTagName(tag);
tagService.saveTag(tagObj);
}
tagSet.add(tagObj);
}
}
blogPost.setTags(tagSet);
blogPost.setPostDate(Calendar.getInstance());
blogService.updateBlogPost(blogPost);
status.setComplete();
return "redirect:/admin/blog";
}
}
//Delete blog post
#RequestMapping(value="/admin/delete/blog/{id}", method=RequestMethod.POST)
public #ResponseBody String deleteBlogPost(#PathVariable("id") Integer id, SessionStatus status){
blogService.deleteBlogPost(id);
status.setComplete();
return "The item was deleted succesfully";
}
#RequestMapping(value="/admin/blog/cancel", method=RequestMethod.GET)
public String cancelBlogEdit(SessionStatus status){
status.setComplete();
return "redirect:/admin/blog";
}
}
BlogPost.java
#Entity
#Table(name="BLOG_POST")
public class BlogPost implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="POST_ID")
private Integer postId;
#NotNull
#NotEmpty
#Size(min=1, max=200)
#Column(name="TITLE")
private String title;
...
#ManyToMany(fetch = FetchType.LAZY, cascade = {CascadeType.ALL})
#JoinTable(name="BLOG_POST_TAGS",
joinColumns={#JoinColumn(name="POST_ID")},
inverseJoinColumns={#JoinColumn(name="TAG_ID")})
private Set<Tag> tags = new HashSet<Tag>();
...
public Set<Tag> getTags() {
return tags;
}
public void setTags(Set<Tag> tags) {
this.tags = tags;
}
}
Tag.java
#Entity
#Table(name="TAG")
public class Tag implements Serializable {
#Id
#GeneratedValue(strategy=GenerationType.AUTO)
#Column(name="TAG_ID")
private Integer tagId;
#NotNull
#NotEmpty
#Size(min=1, max=20)
#Column(name="TAG_NAME")
private String tagName;
#ManyToMany(fetch = FetchType.LAZY, mappedBy="tags")
private Set<BlogPost> blogPosts = new HashSet<BlogPost>();
public Integer getTagId() {
return tagId;
}
public void setTagId(Integer tagId) {
this.tagId = tagId;
}
public String getTagName() {
return tagName;
}
public void setTagName(String tag) {
this.tagName = tag;
}
public Set<BlogPost> getBlogPosts() {
return blogPosts;
}
public void setBlogPosts(Set<BlogPost> blogPosts) {
this.blogPosts = blogPosts;
}
}
If you choose to encode your Tags in a String as the transfer data model between client and server you might make your life a little harder if you want to improve your UX later on.
I would consider having Set<Tag> as its own model element and I would do the transformation directly in the front-end using JavaScript on a JSON model.
Since I would like to have auto completion for my tagging, I would pass all existing Tags as part of the /admin/blog/new model with the ability to mark which tags belong to the blog post (e.g. as a Map<Tag, Boolean> or two Sets) - most likely with a JSON mapping. I would modify this model using JavaScript in the frontend (perhaps utilizing some jquery plugins that provides some nice autocomplete features) and rely on default JSON Mapping (Jackson) for the back conversion.
So my model would have at least two elements: the blog post and all the tags (some who are marked as "assigned to this BlogPost". I would use a TagService to ensure existence of all relevant tags, query them with where name in (<all assigned tag names>) and set my BlogPost.setTags(assignedTags).
In addition I would want to have some cleanup function to remove unused Tags from the DB. If I would want to make it easier for the server, I would have another model element with the removed removed tags (so I can check whether this was the last BlogPost that used this Tag).
This should work in your form:
<div class="form-check">
<input class="form-check-input" type="checkbox" value="1"
name="categories"> <label class="form-check-label"
for="categories"> Cat 1 </label>
<input class="form-check-input"
type="checkbox" value="2" name="categories"> <label
class="form-check-label" for="categories"> Cat 2 </label>
</div>