I have a local Oracle database with which I've established a solid connection. Now I just want to POST data from an HTML input form using a Controller to handle said data.
My form looks like this:
<form action="/request/save" method="post">
<input type="text" id="dateInput" name="requestDate" value="1" style="display: none;"/>
<input type="text" name="description" value="This is a test request." style="display: none;"/>
<input type="text" name="status" value="false" style="display: none;"/>
<div style="width: 200px;"><input type="submit" value="Submit Request" style="display: block;"></div>
</form>
Controller:
#RequestMapping(value = "/save", method = RequestMethod.POST)
String saveRequest(Principal principal, #ModelAttribute Request request, Model model) {
// Set UserId to Request Field USER_ID
Users user = usersRepository.findOneByInitialName(principal.getName());
Request requestObj = new Request(user, new Date());
requestObj.setId(user.getId());
// Set Additional Request Fields
requestObj.setDescription("Test");
requestObj.setStatus(false);
requestObj.setRequestDate(new Date());
// Save Request Object
requestRepository.save(requestObj);
return "requests";
}
Entity (for completion):
#Entity
public class Request {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="request_id")
private Long id;
private Date requestDate;
private String description;
private Boolean status;
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="user_id", nullable = false)
private Users users;
public Request() {}
public Request(Users user, Date requestDate) {
this.setUsers(user);
this.setRequestDate(requestDate);
}
#Override
public String toString() {
return String.format(
"Request[id=%d, inital='%s', requestDate='%s']",
getId()
, getUsers().getInitialName()
, getRequestDate());
}
public Date getRequestDate() {
return requestDate;
}
public void setRequestDate(Date requestDate) {
this.requestDate = requestDate;
}
public Boolean getStatus() {
return status;
}
public void setStatus(Boolean status) {
this.status = status;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public Users getUsers() {
return users;
}
public void setUsers(Users users) {
this.users = users;
}
}
How can I send the data from the form to my database?
Error:
Invalid CSRF Token 'null' was found on the request parameter '_csrf' or header 'X-CSRF-TOKEN'.
You might have configured csrf filter in your web.xml, so you need to pass "X-CSRF-TOKEN" in your request header.
Related
Good afternoon!I get error "Access to fetch at 'http://localhost:8080/registration' from origin 'http://localhost:3000' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled."
I am trying to put information from web app angular, react into java app(spring boot). I looked many different links and did not find where the error in code is.
here is my Registration.js, I suppose there is a mistake, but cannot find where.
import fetch from "node-fetch";
class Registration extends Component{
constructor(props) {
super(props);
this.handleChange = this.handleChange.bind(this);
this.handleSubmit = this.handleSubmit.bind(this);
this.state = {
username: '',
password: '',
confirmPassword: '',
user_fullname: '',
user_email: '',
company_name: '',
position_name: '',
};
}
handleChange = (event, title) => this.setState({[title]: event.target.value});
handleSubmit = async event => {
event.preventDefault();
this.setState({isloading: true});
console.log(this.state);
const headers: HttpHeaders = new HttpHeaders().set('Content-Type', 'application/json;charset=UTF-8')
.append('Content-type', 'application/json;')
.append('Accept','application/json')
.append('Access-Control-Allow-Origin', '*')
return fetch('http://localhost:8080/registration',
{ mode:"no-cors" , headers: headers, method:"POST" ,body:this.state}
).then(response => {
console.log(response);
})
.catch(error => {
console.log(error)
})
};
render() {
return (
<form method="POST" onSubmit={this.handleSubmit} action="/registration">
<FormGroup controlId="username" bssize="large">
<FormControl name="username" value={this.state.username} type="text" onChange={ this.handleUsernameChange} />
</FormGroup>
<FormGroup controlId="password" bssize="large">
<FormControl name="password" value={this.state.password} onChange={this.handlePasswordChange} type="text" />
</FormGroup>
<FormGroup controlId="confirmPassword" bssize="large">
<FormControl name="confirmPassword" value={this.state.confirmPassword} onChange={this.handleConfirmPasswordChange} type="text"/>
</FormGroup>
<FormGroup controlId="user_fullname" bssize="large">
<FormControl name="user_fullname" value={this.state.user_fullname} type="text" onChange={this.handleUser_FullnameChange} />
</FormGroup>
<FormGroup controlId="user_email" bssize="large">
<FormControl name="user_email" value={this.state.user_email} type="text" onChange={this.handleUser_emailChange} />
</FormGroup>
<FormGroup controlId="company_name" bssize="large">
<FormControl name="company_name" value={this.state.company_name} type="text" onChange={this.handleCompany_nameChange} />
</FormGroup>
<FormGroup controlId="position_name" bssize="large">
<FormControl name="position_name" value={this.state.position_name} type="text" onChange={this.handlePosition_nameChange} />
</FormGroup>
<Button bssize="large" type="submit"> Registration </Button>
</form>
);
}}export default Registration;
My UserController.java
#RequestMapping(value = "/registration", method = {RequestMethod.POST}, produces={"application/json"})
#ResponseBody
public ResponseEntity<User> registration(#RequestBody User user, HttpStatus httpStatus) {
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.valueOf(MediaType.APPLICATION_JSON_UTF8_VALUE));
userService.saveUser(user);
return new ResponseEntity<User>(user, HttpStatus.CREATED);
}
#GetMapping("/registration")
public String registration(Model model) {
model.addAttribute("userForm", new User());
return "registration";
}
User.java
#Entity
#Table(name = "users")
public class User {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name = "id")
private int id;
#Column(name = "username")
private String username;
#Column(name = "password")
private String password;
#Transient
#Column(name = "confirmPassword")
private String confirmPassword;
#Column(name = "user_fullname")
private String user_fullname;
#Column(name = "user_email")
private String user_email;
#Column(name = "company_name")
private String company_name;
#Column(name = "position_name")
private String position_name;
#Column(name = "date")
private Date date = new Date(System.currentTimeMillis());
#ManyToMany(cascade = CascadeType.ALL)
#JoinTable(name = "user_roles", joinColumns = #JoinColumn(name = "user_id"), inverseJoinColumns = #JoinColumn(name = "role_id"))
private Set<Roles> roles;
public User(){
}
public User(Integer id,String username, String password, String confirmPassword, String user_fullname, String user_email,String company_name, String position_name ){
this.id = id;
this.username=username;
this.password = password;
this.confirmPassword = confirmPassword;
this.user_fullname = user_fullname;
this.user_email = user_email;
this.company_name = company_name;
this.position_name = position_name;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getConfirmPassword() {
return confirmPassword;
}
public void setConfirmPassword(String confirmPassword) {
this.confirmPassword = confirmPassword;
}
public String getUser_fullname() {
return user_fullname;
}
public void setUser_fullname(String user_fullname) {
this.user_fullname = user_fullname;
}
public String getUser_email() {
return user_email;
}
public void setUser_email(String user_email) {
this.user_email = user_email;
}
public String getCompany_name() {
return company_name;
}
public void setCompany_name(String company_name) {
this.company_name = company_name;
}
public String getPos_name() {
return position_name;
}
public void setPos_name(String position_name) {
this.position_name = position_name;
}
public Set<Roles> getRoles() {
return roles;
}
public void setRoles(Set<Roles> roles) {
this.roles = roles;
}
public Date getDate() {
return date;
}
}
Users db
CREATE TABLE users (
id INT AUTO_INCREMENT PRIMARY KEY,
username VARCHAR(255) NOT NULL ,
password VARCHAR(255) NOT NULL ,
user_fullname VARCHAR(255),
user_email VARCHAR(255) ,
company_name VARCHAR(255),
position_name VARCHAR(255),
date DATETIME
)
ENGINE = InnoDB;
It seems like you have a problem with Spring Boot security. Assuming you have Spring Boot security enabled, based on the error message you've received "Response to preflight request doesn't pass access control check", you need to allow pre-flight request in the back-end. You can try to create a new class and extend WebSecurityConfigurerAdaptor like so:
#Configuration
#EnableWebSecurity
public class WebSecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers(Http.OPTIONS, "/**").permitAll()
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
Http.OPTIONS are pre-flight requests send to the server to make sure you have the right authentication to retrieve the resource. Here, you are permitting all pre-flight requests to let the actual request retrieve the resource.
Like #Andreas has Mentioned use #RequestBody instead of #ModelAttribute ( I believe #ModelAttribute annotation binds a method parameter) and also in client side you are posting that as JSON.
So try using below
#PostMapping(value = "/registration")
public String registration(#RequestBody User userForm, BindingResult bindingResult) {
//Code Logic
}
I believe #ModelAttribute only maps request parameters, i.e. values from query string or from form POST content with content type application/x-www-form-urlencoded or multipart/form-data.
Since you're sending the data as JSON, you need to change annotation to #RequestBody.
I write simple app that let us writing, updating and removing posts. So far I can write and update, but my delete command seems to not work. Here is my jsp code:
<table>
<tr>
<th>Number</th>
<th>Title</th>
<th>Author</th>
<th></th>
</tr>
<c:forEach var="post" items="${listOfPosts}">
<tr>
<td>${post.id}</td>
<td>${post.title}</td>
<td>${post.author}</td>
<td>
<a href="<c:url value="/editPost/${post.id}" />" >Edit</a>
<form:form action="deletePost" method="post" commandName="deletedBlogpost">
<input type="submit" value="Delete post">
</form:form>
</td>
</tr>
</c:forEach>
</table>
and my controller methods, where I tried to implement Post-Redirect-Get Pattern:
#RequestMapping(value = "deletePost", method = RequestMethod.POST)
public String deletePostPOST (#ModelAttribute("deletedBlogpost") BlogPost blogpost, BindingResult bindingResult, RedirectAttributes ra) {
if (bindingResult.hasErrors()) {
return ERROR_PAGE_VIEW;
}
repo.delete(blogpost);
ra.addFlashAttribute("blogpost", blogpost);
return "redirect:/delete-success";
}
#RequestMapping(value = "delete-success", method = RequestMethod.GET)
public String deletePostGET(#ModelAttribute("deletedBlogpost") BlogPost blogpost, Model model){
model.addAttribute(M_LIST_OF_POSTS, repo.findAll());
return RESULT_PAGE_VIEW;
}
I guess it has to be something with jsp form, because my code isn't even reaching controller's code. Any help will be appreciated, 'casue I'm still a beginner here and I am still struggling with basics.
EDIT here is my entity BlogPost
#Entity
#Table(name="posts")
public class BlogPost {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private long id;
#Column(name="post_title")
private String title;
#Column(name="post_content")
private String content;
#Column(name="post_author", nullable = false)
private String author;
public BlogPost(){}
public BlogPost(String title, String content, String author) {
this.title = title;
this.content = content;
this.author = author;
}
public long getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public String toString(){
return "ID: "+getId()+", tytul: "+getTitle()+", tresc: "+getContent()+", autor: "+getAuthor()+"\n";
}
}
and my application.properties where I can establish a PostgreSQL connection:
#PostgreSQL
spring.datasource.driverClassName=org.postgresql.Driver
spring.datasource.url=jdbc:postgresql://localhost:5432/blogdatabase
spring.datasource.username=username
spring.datasource.password=password
spring.jpa.database-platform=org.hibernate.dialect.PostgreSQLDialect
spring.jpa.generate-ddl=true
spring.jpa.show-sql=true
EDIT:
I tried to solve it by adding to jsp form
<input name="id" type="hidden" value="${post.id}"/>
and by adding to deletePostPost method
repo.delete(deletedBlogpost.getId());
Nothing has changed. Clicking button isn't calling any action.
Try
yourRepository.deleteById(id)
Good afternoon,
I am newbie to Spring MVC. I'm stuck with the following error while running my project "The request sent by the client was syntactically incorrect."
My project has two entities, Team and Country which have a ManyToOne relationship. Both these entities map tables created in mysql database.
I started the project with only the Team entity, and sucessfuly created my classes (DAO, controller, services, etc) and jsp to create new teams.
Now, I created the class Country to relate both entities and I added a dropdown list in the "add-team-form.jsp" to select the country of the new team. This page is correctly displayed (all countries appear in the dropdown list), however, when I click "submit" to create the new team, I get the error "The request sent by the client was syntactically incorrect."
Can you please help me to identify my error? I'm guessing it's in the "add-team-form.jsp".
1 - Entity Team:
#Entity
#Table(name="teams")
public class Team implements Serializable{
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
#Column(name = "name", length = 40, nullable = false)
private String name;
#Column(name = "rating", length = 6, nullable = false)
private Integer rating;
#ManyToOne(fetch = FetchType.EAGER)
#JoinColumn(name = "id_country", nullable = false)
private Country country;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public Integer getRating() {
return rating;
}
public void setRating(Integer rating) {
this.rating = rating;
}
public Country getCountry() {
return country;
}
public void setCountry(Country country) {
this.country = country;
}
}
2 - Entity Country:
#Entity
#Table(name = "countries")
public class Country implements Serializable{
#Id
#Column(name= "id_country", length = 6)
private String idCountry;
#Column(name = "name", length = 255, nullable = false)
private String name;
#OneToMany(fetch = FetchType.LAZY, mappedBy = "country")
private List<Team> teams;
public String getIdCountry() {
return idCountry;
}
public void setIdCountry(String idCountry) {
this.idCountry = idCountry;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
My Team DAO
#Repository
public class TeamDAOImpl implements TeamDAO {
#Autowired
private SessionFactory sessionFactory;
private Session getCurrentSession() {
return sessionFactory.getCurrentSession();
}
#Override
public void addTeam(Team team) {
getCurrentSession().save(team);
}
}
My Team Service
#Service
#Transactional
public class TeamServiceImpl implements TeamService {
#Autowired
private TeamDAO teamDAO;
public void addTeam(Team team) {
teamDAO.addTeam(team);
}
My Team Controller
#Controller
#RequestMapping(value="/team")
public class TeamController {
#Autowired
private TeamService teamService;
#Autowired
private FilterService filterService;
#RequestMapping(value="/add", method=RequestMethod.GET)
public ModelAndView addTeamPage() {
ModelAndView modelAndView = new ModelAndView("add-team-form");
modelAndView.addObject("team", new Team());
return modelAndView;
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView addingTeam(#ModelAttribute Team team) {
ModelAndView modelAndView = new ModelAndView("home");
teamService.addTeam(team);
String message = "Team was successfully added.";
modelAndView.addObject("message", message);
return modelAndView;
}
#ModelAttribute("countryList")
public Map<String, String> getCountryList(){
Map<String, String> countryList = filterService.getCountries();
return countryList;
}
...
}
My "add-team-form.jsp"
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form" %>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Add team page</title>
</head>
<body>
<h1>Add team page</h1>
<form:form method="POST"
modelAttribute="team"
action="${pageContext.request.contextPath}/team/add.html">
<table>
<tbody>
<tr>
<td>Name:</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Rating:</td>
<td><form:input path="rating" /></td>
</tr>
<tr>
<td><label>Country</label></td>
<td>
<form:select path="country.idCountry">
<form:options items="${countryList}" />
</form:select>
</td>
<tr>
<td><input type="submit" value="Add" /></td>
<td></td>
</tr>
</tbody>
</table>
</form:form>
</body>
</html>
There is no error showing in the console of eclipse, but here is the error im receiving from the browser:
HTTP Status 400 -
type Status report
message
description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.47
There's a couple of problems I can see here - you are posting to add/team/add.html and not hitting your post handler. You don't need the action attribute as you're posting to the same endpoint;
<form:form method="POST" modelAttribute="team" >
Secondly your are injecting the countries as a map, so these are ID/display values which works great for key/value pairs and for binding a value to a string field. In this case, Spring is trying to bind your country ID (String) to the team.country(Country) field which will fail. To help Spring out you need a databinder; in your controller add;
#InitBinder
public void initBinder (WebDataBinder binder) {
binder.registerCustomEditor(Country.class, new CountryEditor());
}
and create the property editor class;
public class CountryEditor extends PropertyEditorSupport {
#Override
public void setValue(Object value) {
super.setValue(value);
}
public String getAsText() {
if (getValue() == null) return null;
return ((Country) getValue()).getName();
};
public void setAsText(String text) throws IllegalArgumentException {
if (text != null) {
Country country = // something like filterService.getCountryById(text);
setValue(country);
}
};
}
There's more information in the Spring documentation
The error you are receiving generally happens if a parameter is missing or is in a different format and cannot be converted to the expected type.Check the values being passed to the Team object.You can either log the request and response or set the log level to "DEBUG",this will display the exact error in logs.
I am using Spring MVC + thymeleaf and when I am submitting my form it gives me all the time validation error(Null) in the binding result. Any advise would be appreciated! Thanks!
Error message
"Field error in object 'createForm' on field 'authorId': rejected value [null]; codes [NotNull.createForm.authorId,NotNull.authorId,NotNull]; arguments [org.springframework.context.support.DefaultMessageSourceResolvable: codes [createForm.authorId,authorId]; arguments []; default message [authorId]]; default message [may not be null]"
#NotNull
#Size(min= 2, max = 100, message = "your title should be between 2 and 100 symbols")
private String title;
#NotNull
#Size(min = 2, message = "Please fill your message")
private String content;
#DateTimeFormat(pattern = "yyyy-mm-dd")
private Date date;
#NotNull
private String authorId;
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Date getDate() {
return date;
}
public void setDate(Date date) {
this.date = date;
}
public String getId() {
return authorId;
}
public void setId(String authorId) {
this.authorId = authorId;
}
}
And my HTML
<form id="create-form" method="post" th:object="${createForm}">
<div><label for="title">Title:</label></div>
<input id="title" type="text" name="title" th:value="*{title}"/>
<span class="formError" th:if="${#fields.hasErrors('title')}" th:errors="*{title}">Invalid title</span>
<div><label for="content">Content:</label></div>
<textarea name="content" rows="30" cols="100" id="content" th:value="*{content}"></textarea>
<span class="formError" th:if="${#fields.hasErrors('content')}" th:errors="*{content}">Invalid content</span>
<div><label for="date">Date:</label></div>
<input id="date" type="date" name="date" th:value="*{date}"/>
<span class="formError" th:if="${#fields.hasErrors('date')}" th:errors="*{date}">Invalid date</span>
<div><label for="authorId">Author ID:</label></div>
<input id="authorId" type="text" name="authorId" th:value="*{authorId}"/>
<span class="formError" th:if="${#fields.hasErrors('id')}" th:errors="*{authorId}">Invalid id</span>
<br/>
<br/>
<div><input type="submit" value="Create"/></div>
</form>
As written in the comment to the question:
Annotation #NotNull won't protect you from null. It's your own contract with you and other developers working on this code that there can't be null there.
This means that you have to validate data by yourself. There are two approaches. You can create AuthorTO which will allow nulls and then create Author if and only if there are no unexpected nulls or validate on front-end side.
Hi I am new to Spring Mvc i have 3 tables first is role,resources,roleresource tables respectively. I have a created a jsp in which a list of resources are shown along with check boxes and also rolename where user enters,my prob is i need to insert rolename to role table and generated roleid to roleresource table with selected resources ids. problem here is i am not able to bind selected checkbox values here is my controller
package com.steadyground.controller;
import java.util.ArrayList;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import com.steadyground.constants.URLConstants;
import com.steadyground.entity.Organization;
import com.steadyground.entity.Resources;
import com.steadyground.form.RoleResourceForm;
import com.steadyground.service.ResourcesService;
#Controller
public class RoleResoucesMappingController {
#Autowired
private ResourcesService resourcesService;
#RequestMapping(value = URLConstants.ROLERESOURCEMAPPING_PAGE, method = RequestMethod.GET)
public String landRoleResourceMapping(ModelMap map)
{
map.addAttribute("roleResourceForm",new RoleResourceForm());
return "roleResourcesMapping";
}
#RequestMapping(value = URLConstants.ROLERESOURCEMAPPING_ADD, method = RequestMethod.POST)
public String createRoleResourceMapping(#ModelAttribute(value="roleResourceForm") RoleResourceForm roleResourceForm, BindingResult result, ModelMap map)
{
System.out.println(roleResourceForm.getResources());
System.out.println(roleResourceForm.getResources().size());
//System.out.println(roleResourceForm.getRole().getRoleResources());
return "roleResourcesMapping";
}
#ModelAttribute("resources")
public List<Resources> getAllResources() {
List<Resources> listResources = new ArrayList<Resources>();
listResources = resourcesService.getAllResources();
return listResources;
}
}
here is my role.java file
#Entity
#Table(name = "role", catalog = "steadyground")
public class Role implements java.io.Serializable {
private Integer roleId;
private String roleName;
private Set<RoleResource> roleResources = new HashSet<RoleResource>(0);
public Role() {
}
public Role(String roleName) {
this.roleName = roleName;
}
public Role(String roleName, String applicationName,
Set<RoleResource> roleResources) {
this.roleName = roleName;
this.roleResources = roleResources;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "role_id", unique = true, nullable = false)
public Integer getRoleId() {
return this.roleId;
}
public void setRoleId(Integer roleId) {
this.roleId = roleId;
}
#Column(name = "role_name", nullable = false, length = 100)
public String getRoleName() {
return this.roleName;
}
public void setRoleName(String roleName) {
this.roleName = roleName;
}
#OneToMany(fetch = FetchType.LAZY, mappedBy = "role")
public Set<RoleResource> getRoleResources() {
return this.roleResources;
}
public void setRoleResources(Set<RoleResource> roleResources) {
this.roleResources = roleResources;
}
}
here is my resources.java
#Entity
#Table(name = "resources", catalog = "steadyground")
public class Resources implements java.io.Serializable {
private Integer resourceId;
private String url;
private String urlName;
public Resources() {
}
public Resources(String url, String urlName) {
this.url = url;
this.urlName = urlName;
}
#Id
#GeneratedValue(strategy = IDENTITY)
#Column(name = "resource_id", unique = true, nullable = false)
public Integer getResourceId() {
return this.resourceId;
}
public void setResourceId(Integer resourceId) {
this.resourceId = resourceId;
}
#Column(name = "url", length = 100)
public String getUrl() {
return this.url;
}
public void setUrl(String url) {
this.url = url;
}
#Column(name = "url_name", length = 200)
public String getUrlName() {
return this.urlName;
}
public void setUrlName(String urlName) {
this.urlName = urlName;
}
}
here is my roleresource.java
#Entity
#Table(name="role_resource"
,catalog="steadyground"
)
public class RoleResource implements java.io.Serializable {
private Integer roleResourceId;
private Role role;
private Integer resourceId;
public RoleResource() {
}
public RoleResource(Role role, Integer resourceId) {
this.role = role;
this.resourceId = resourceId;
}
#Id #GeneratedValue(strategy=IDENTITY)
#Column(name="role_resource_id", unique=true, nullable=false)
public Integer getRoleResourceId() {
return this.roleResourceId;
}
public void setRoleResourceId(Integer roleResourceId) {
this.roleResourceId = roleResourceId;
}
#ManyToOne(fetch=FetchType.LAZY)
#JoinColumn(name="role_id")
public Role getRole() {
return this.role;
}
public void setRole(Role role) {
this.role = role;
}
#Column(name="resource_id")
public Integer getResourceId() {
return this.resourceId;
}
public void setResourceId(Integer resourceId) {
this.resourceId = resourceId;
}
}
and my jsp page
<springform:form method="post" action="createRoleResourcesMapping" class="form-horizontal" commandName="roleResourceForm" >
<div class="span12">
<div class="center">
<div class="control-group span6">
<label class="control-label" for="Role_Id">Role Id</label>
<div class="control-group span6">
<label class="control-label" for="url_Name">Role Name</label>
<div class="controls">
<div class="span12">
<springform:input path="role.roleName"/>
</div>
</div>
</div>
<div class="page-header position-relative"></div>
<table id="sample-table-2" class="table table-striped table-bordered table-hover">
<thead>
<tr>
<th>Resources</th>
</tr>
</thead>
<tbody>
<tr>
<td><springform:checkboxes path="resources" items="${resources}" itemLabel="urlName" itemValue="resourceId"/>
</td></tr></tbody>
</table>
<div class="controls">
<div class="span12">
<input type="submit" class="btn btn-primary" value="Submit">
<input type="button" class="btn " value="Cancel">
</div>
</div>
</div>
</div>
</springform:form>
could someone help me in how to receive the data and save it in two tables
<springform:checkboxes path="resources" items="${resources}" itemLabel="urlName" itemValue="resourceId"/>
From your code, what I've understood, the RoleResourcesForm is more like a wrapper of the 2 entities Resource & Role with another object resources.
I think, to use form:checkboxes you better give it an object List in the path.
And what's this variable resources?
If it's really an List object in the RoleResourcesForm wrapper, in the items, you should use
items="${roleResourceForm.resources}"
When you commit it, it will send the form model attribute with only checked checkbox values.