Currently, I am facing the problem of data binding using model attribute.
(I am following the tutorial from https://www.baeldung.com/spring-mvc-and-the-modelattribute-annotation)
I have defined the modelattribute in form as well as the controller, but the error still appear (shown in following)
org.springframework.web.util.NestedServletException: Request processing failed; nested exception is java.lang.IllegalStateException: Neither BindingResult nor plain target object for bean name 'systemAccount' available as request attribute
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:1013)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:897)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:687)
at org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:882)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:790)
at org.eclipse.jetty.servlet.ServletHolder.handle(ServletHolder.java:812)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1669)
at org.eclipse.jetty.websocket.server.WebSocketUpgradeFilter.doFilter(WebSocketUpgradeFilter.java:201)
at org.eclipse.jetty.servlet.ServletHandler$CachedChain.doFilter(ServletHandler.java:1652)
at org.eclipse.jetty.servlet.ServletHandler.doHandle(ServletHandler.java:585)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:143)
at org.eclipse.jetty.security.SecurityHandler.handle(SecurityHandler.java:577)
at org.eclipse.jetty.server.session.SessionHandler.doHandle(SessionHandler.java:223)
at org.eclipse.jetty.server.handler.ContextHandler.doHandle(ContextHandler.java:1127)
at org.eclipse.jetty.servlet.ServletHandler.doScope(ServletHandler.java:515)
at org.eclipse.jetty.server.session.SessionHandler.doScope(SessionHandler.java:185)
at org.eclipse.jetty.server.handler.ContextHandler.doScope(ContextHandler.java:1061)
at org.eclipse.jetty.server.handler.ScopedHandler.handle(ScopedHandler.java:141)
at org.eclipse.jetty.server.handler.ContextHandlerCollection.handle(ContextHandlerCollection.java:215)
at org.eclipse.jetty.server.handler.HandlerWrapper.handle(HandlerWrapper.java:97)
at org.eclipse.jetty.server.Server.handle(Server.java:499)
at org.eclipse.jetty.server.HttpChannel.handle(HttpChannel.java:311)
at org.eclipse.jetty.server.HttpConnection.onFillable(HttpConnection.java:258)
at org.eclipse.jetty.io.AbstractConnection$2.run(AbstractConnection.java:544)
at org.eclipse.jetty.util.thread.QueuedThreadPool.runJob(QueuedThreadPool.java:635)
at org.eclipse.jetty.util.thread.QueuedThreadPool$3.run(QueuedThreadPool.java:555)
at java.lang.Thread.run(Thread.java:748)
I have search for solution from the internet, but still haven't find the right solution for me.
The following is my code:
1.form code snippet
<form:form modelAttribute="systemAccount" action="/loginVali" method="post">
<form:input path="username" />
<form:input path="password" />
<input type="submit" type="submit" value="submit"/>
</form:form>
2.controller code snippet
#Controller
public class GenericController {
#RequestMapping(value="loginVali", method = RequestMethod.POST)
public ModelAndView loginAuthentication(#ModelAttribute("systemAccount") SystemAccount sys,
BindingResult bindingResult){
System.out.println("-----------------------");
System.out.println(sys.getUsername() + " "+ sys.getPassword());
System.out.println("-----------------------");
return null; //for testing purpose, so I didn't put any operation
}
}
3.entity code snippet (The entity is using the Hibernate framrwork).
#Entity
#Table(name = "SYSTEM_ACCOUNT")
public class SystemAccount {
#Id
#GeneratedValue(strategy= GenerationType.SEQUENCE, generator="SYSTEM_ACCOUNT_SEQ")
#SequenceGenerator(allocationSize=1,name="SYSTEM_ACCOUNT_SEQ", sequenceName="SYSTEM_ACCOUNT_SEQ")
#Column(name = "ACCOUNT_ID")
private int accountID;
#Column(name = "USERNAME")
private String username;
#Column(name = "PASSWORD")
private String password;
#OneToOne(mappedBy="systemAccount", cascade = CascadeType.ALL)
private Manager manager;
#OneToOne(mappedBy="systemAccount", cascade = CascadeType.ALL)
private CounterStaff counterStaff;
#OneToOne(mappedBy="systemAccount", cascade = CascadeType.ALL)
private Customer customer;
#OneToOne(mappedBy="systemAccount", cascade = CascadeType.ALL)
private Doctor doctor;
public SystemAccount() {
}
public int getAccountID() {
return accountID;
}
public void setAccountID(int accountID) {
this.accountID = accountID;
}
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 Manager getManager() {
return manager;
}
public void setManager(Manager manager) {
this.manager = manager;
}
public CounterStaff getCounterStaff() {
return counterStaff;
}
public void setCounterStaff(CounterStaff counterStaff) {
this.counterStaff = counterStaff;
}
public Customer getCustomer() {
return customer;
}
public void setCustomer(Customer customer) {
this.customer = customer;
}
public Doctor getDoctor() {
return doctor;
}
public void setDoctor(Doctor doctor) {
this.doctor = doctor;
}
#Override
public String toString() {
return "SystemAccount{" +
"accountID=" + accountID +
", username='" + username + '\'' +
", password='" + password + '\'' +
", manager=" + manager +
", counterStaff=" + counterStaff +
", customer=" + customer +
", doctor=" + doctor +
'}';
}
}
Thank you Mr. M. Deinum! I have solved my issue!
#RequestMapping(value = "/", method = RequestMethod.GET)
public String displayLogin(Model model) {
model.addAttribute("systemAccount", new SystemAccount());
return "index";
}
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'm a novice java developer and now develop User Management application using Spring-Hibernate. I have two entities User and Email. And User entity has a field Email which is mapped to Email entity as #ManyToOne. Any Email can be used by multiple users.
When I save a new User in DB for every new user I get a new row Email, even if the same record is already in the Email Table. How to properly make save operation to avoid duplication of the same records in the table Email?
User.java
#Entity
#Table(name = "USER")
public class User implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="ID")
private Long id;
#Column(name = "name")
private String name;
#ManyToOne
#JoinColumn(name = "email_id")
private Email email;
public User(){
}
public Email getEmail() {
return email;
}
public void setEmail(Email email) {
this.email = email;
}
...
}
Email.java
#Entity
#Table(name = "EMAIL")
public class Email implements Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
#Column(name="ID")
private Long id;
#Column(name = "emailaddress")
private String emailaddress;
#OneToMany (mappedBy = "email", targetEntity=User.class)
private Set<User> user= new HashSet<User>();
public Email() {
}
public Email(String emailaddress) {
this.emailaddress = emailaddress;
}
public String getEmailaddress() {
return emailaddress;
}
public void setEmailaddress(String emailaddress) {
this.emailaddress = emailaddress;
}
...
}
Controller.java
#Transactional
#RequestMapping(value = "/adduser", method = RequestMethod.POST)
public String saveOrder(#ModelAttribute("user") User user, BindingResult result, #RequestParam String action){
emailDAO.create(user.getEmail());
userDAO.create(user);
return "index";
...
}
EmailDAO.java
#Transactional
#Repository
public class EmailDAO{
#Autowired
private SessionFactory sessionFactory;
public Email create(Email email) {
sessionFactory.getCurrentSession().save(email);
return email;
}
}
UserDAO.java
#Transactional
#Repository
public class UserDAO{
#Autowired
private SessionFactory sessionFactory;
public User create(User user) {
sessionFactory.getCurrentSession().save(user);
return user;
}
}
webform.jsp
<form:form action="${formUrl}" method="post" modelAttribute="user">
<form:label path="name" for="appname">username</form:label>
<form:input path="name" id= "appname" cssClass="form-control"/>
<form:label path="email.emailaddress" for="appemail">Email</form:label>
<form:input path="email.emailaddress" id= "appemail"/>
<button type="submit" name="action" value="Add">Save</button>
</form:form>
database diagram
Example of the DB records
That is because you keep on saving the Email as a new Record
#Transactional
#RequestMapping(value = "/adduser", method = RequestMethod.POST)
public String saveOrder(#ModelAttribute("user") User user, BindingResult result, #RequestParam String action){
emailDAO.create(user.getEmail()); // Inserting Email as New Record
userDAO.create(user);
return "index";
...
}
And you don't have unique=true on Email Entity
#Column(name = "emailaddress", unique = true)
private String emailaddress;
Which you should ideally have so that there will be no duplicate Emails will get inserted even by accidentally.
You need to modify EmailDAO
#Transactional
#Repository
public class EmailDAO{
#Autowired
private SessionFactory sessionFactory;
public Email create(Email email) {
sessionFactory.getCurrentSession().save(email);
return email;
}
public Email getEmail(String inputEmail) {
Email email = null;
Query query = sessionFactory.getCurrentSession().createQuery("FROM Email e WHERE e.emailaddress = :email");
query.setString("email", inputEmail);
List emails = query.list();
if(emails != null && emails.size() > 0) {
email = (Email)emails.get(0);
} else {
email = new Email();
email.setEmailAddress(inputEmail);
}
return email;
}
}
And you getEmail
#Transactional
#RequestMapping(value = "/adduser", method = RequestMethod.POST)
public String saveOrder(#ModelAttribute("user") User user, BindingResult result, #RequestParam String action){
user.setEmail(emailDAO.getEmail(user.getEmail().getEmailAddress())); // Inserting Email as New Record
userDAO.create(user);
return "index";
...
}
Hi I am doing project in Spring Roo. Where can I put restrictions that the phone number must be 10 digits? I have already put restrictions in create.jspx and in User_Roo_DbManaged.aj but it doesn't work.
it accepts letters and shorter input.
create.jspx
<?xml version="1.0" encoding="UTF-8" standalone="no"?>
<div xmlns:c="http://java.sun.com/jsp/jstl/core" xmlns:field="urn:jsptagdir:/WEB-INF/tags/jquery/form/fields" xmlns:form="urn:jsptagdir:/WEB-INF/tags/jquery/form" xmlns:jsp="http://java.sun.com/JSP/Page" xmlns:spring="http://www.springframework.org/tags" version="2.0">
<jsp:directive.page contentType="text/html;charset=UTF-8"/>
<jsp:output omit-xml-declaration="yes"/>
<form:create id="fc_edu_ndnu_capstone_domain_User" modelAttribute="user" path="/users" render="${empty dependencies}" z="wGrfaSchPJDWXlsq1jiCSRc0pAA=">
<field:simple field="emergencies" id="c_edu_ndnu_capstone_domain_User_emergencies" messageCode="entity_reference_not_managed" messageCodeAttribute="Emergency" z="96v/orisk+QZ0UvamFbdCmNUM9g="/>
<field:select field="typeId" id="c_edu_ndnu_capstone_domain_User_typeId" itemValue="id" items="${usertypes}" path="/usertypes" z="cuXEuKQFS8VdksWWbETwOj+Ps4k="/>
<field:input field="name" id="c_edu_ndnu_capstone_domain_User_name" required="true" z="AvB38b/End0hXemXNC8GrbD8SAw="/>
<field:input field="email" id="c_edu_ndnu_capstone_domain_User_email" required="true" validationMessageCode="field_invalid_email" z="OGADRfESfWyp/4F216swLnNdyoQ="/>
<field:input field="username" id="c_edu_ndnu_capstone_domain_User_username" required="true" z="MiEOzhgH466ktY7pKT/tYMLt5S0="/>
<field:input field="password" id="c_edu_ndnu_capstone_domain_User_password" required="true" z="kEW4oQdeXWi+JyIwdUJkmMKHYII=" type="password"/>
<field:input field="phone" id="c_edu_ndnu_capstone_domain_User_phone" required="true" validationMessageCode="field_invalid_number" max="10" min="10" z="k42Av41wIfhbInJmZhCY/WbW+h4="/>
<field:input field="year" id="c_edu_ndnu_capstone_domain_User_year" required="true" validationMessageCode="field_invalid_number" max="4" min="4" z="HL+hSR+nz8/34t6nn2HXLRJaIyA="/>
<field:input field="active" id="c_edu_ndnu_capstone_domain_User_active" required="true" validationMessageCode="field_invalid_integer" max="1" min="1" z="wMEcOQjcrIJKY5RQ7mQ4/Uu9Ago="/>
<field:input field="description" id="c_edu_ndnu_capstone_domain_User_description" required="true" z="6TJHmWCAvkCtONvKOBHftLCMtso="/>
</form:create>
<form:dependency dependencies="${dependencies}" id="d_edu_ndnu_capstone_domain_User" render="${not empty dependencies}" z="Do0kIZAQM8ZWzWNlt1c/uMANnj4="/>
</div>
User_Roo_DbManaged.aj
// WARNING: DO NOT EDIT THIS FILE. THIS FILE IS MANAGED BY SPRING ROO.
// You may push code into the target .java compilation unit if you wish to edit any member(s).
package edu.ndnu.capstone.domain;
import edu.ndnu.capstone.domain.Emergency;
import edu.ndnu.capstone.domain.User;
import edu.ndnu.capstone.domain.UserType;
import java.util.Calendar;
import java.util.Set;
import javax.persistence.Column;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Temporal;
import javax.persistence.TemporalType;
import javax.validation.constraints.NotNull;
import org.springframework.format.annotation.DateTimeFormat;
privileged aspect User_Roo_DbManaged {
#OneToMany(mappedBy = "userId")
private Set<Emergency> User.emergencies;
#ManyToOne
#JoinColumn(name = "type_id", referencedColumnName = "id", nullable = false)
private UserType User.typeId;
#Column(name = "name", length = 256)
#NotNull
private String User.name;
#Column(name = "email", length = 256, unique = true)
#NotNull
private String User.email;
#Column(name = "username", length = 150, unique = true)
#NotNull
private String User.username;
#Column(name = "password")
#NotNull
private String User.password;
#Column(name = "phone", length = 10, unique = true)
#NotNull
private String User.phone;
#Column(name = "year", length = 4)
#NotNull
private String User.year;
#Column(name = "active", length = 1)
#NotNull
private Integer User.active;
#Column(name = "created", updatable = false)
#NotNull
#Temporal(TemporalType.TIMESTAMP)
#DateTimeFormat(style = "MM")
private Calendar User.created = java.util.Calendar.getInstance();
#Column(name = "description", length = 1024)
#NotNull
private String User.description;
public Set<Emergency> User.getEmergencies() {
return emergencies;
}
public void User.setEmergencies(Set<Emergency> emergencies) {
this.emergencies = emergencies;
}
public UserType User.getTypeId() {
return typeId;
}
public void User.setTypeId(UserType typeId) {
this.typeId = typeId;
}
public String User.getName() {
return name;
}
public void User.setName(String name) {
this.name = name;
}
public String User.getEmail() {
return email;
}
public void User.setEmail(String email) {
this.email = email;
}
public String User.getUsername() {
return username;
}
public void User.setUsername(String username) {
this.username = username;
}
public String User.getPassword() {
return password;
}
public void User.setPassword(String password) {
this.password = password;
}
public String User.getPhone() {
return phone;
}
public void User.setPhone(String phone) {
this.phone = phone;
}
public String User.getYear() {
return year;
}
public void User.setYear(String year) {
this.year = year;
}
public Integer User.getActive() {
return active;
}
public void User.setActive(Integer active) {
if(active==0 || active==1)
this.active = active;
else
this.active = 2;
}
public Calendar User.getCreated() {
return created;
}
public void User.setCreated(Calendar created) {
this.created = created;
}
public String User.getDescription() {
return description;
}
public void User.setDescription(String description) {
this.description = description;
}
}
First, you shouldn't modify any .aj because Spring Roo will overwrite your changes next time you run it. To customize your field you have to move its declaration into related .java file (we call it push-in).
To set the field validation, Roo uses the JSR-303 specification, using the Hibernate validation as implementation.
So, to archive it, try:
Push-in the phone declaration into User.java and add javax.validation.constraints.Size annotation:
public class User {
#Column(name = "phone", length = 10, unique = true)
#NotNull
#Size(max=10,min=10)
private String phone;
}
Run Spring Roo console.
After that, Roo will:
remove phone definition from User_Roo_DbManaged.aj
create the getter and setter on User_Roo_bean.aj
Update User related .jspx
Note that #Column definition refers to database declaration. Any other field validation you should use the javax.validation.constraints.* annotations or create yours (here you have an example)
Good luck!
I have a web service based on a number of entity classes. one of them is shows below
#Entity
#Table(name = "users")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Users.findAll", query = "SELECT u FROM Users u"),
#NamedQuery(name = "Users.findByUserName", query = "SELECT u FROM Users u WHERE u.userName = :userName"),
#NamedQuery(name = "Users.findByUserPassword", query = "SELECT u FROM Users u WHERE u.userPassword = :userPassword")})
public class Users implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#Basic(optional = false)
#Column(name = "user_name")
private String userName;
#Basic(optional = false)
#Column(name = "user_password")
private String userPassword;
#JoinColumn(name = "user_category_id", referencedColumnName = "category_id")
#ManyToOne(optional = false)
private UserCategory userCategoryId;
#OneToMany(cascade = CascadeType.ALL, mappedBy = "userName")
private List<UserRecord> userRecordList;
public Users() {
}
public Users(String userName) {
this.userName = userName;
}
public Users(String userName, String userPassword) {
this.userName = userName;
this.userPassword = userPassword;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getUserPassword() {
return userPassword;
}
public void setUserPassword(String userPassword) {
this.userPassword = userPassword;
}
public UserCategory getUserCategoryId() {
return userCategoryId;
}
public void setUserCategoryId(UserCategory userCategoryId) {
this.userCategoryId = userCategoryId;
}
#XmlTransient
public List<UserRecord> getUserRecordList() {
return userRecordList;
}
public void setUserRecordList(List<UserRecord> userRecordList) {
this.userRecordList = userRecordList;
}
#Override
public int hashCode() {
int hash = 0;
hash += (userName != null ? userName.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Users)) {
return false;
}
Users other = (Users) object;
if ((this.userName == null && other.userName != null) || (this.userName != null && !this.userName.equals(other.userName))) {
return false;
}
return true;
}
#Override
public String toString() {
return userName;
}
}
I was able to successfully deploy the web service and then i added a new Restful web client using netbeans, which created the following class
public class Client {
private WebTarget webTarget;
private javax.ws.rs.client.Client client;
private static final String BASE_URI = "http://localhost:31691/ProductionEntitiesService/api";
public Client() {
client = javax.ws.rs.client.ClientBuilder.newClient();
webTarget = client.target(BASE_URI).path("entities.users");
}
...
public <T> T find_XML(Class<T> responseType, String id) throws ClientErrorException {
WebTarget resource = webTarget;
resource = resource.path(java.text.MessageFormat.format("{0}", new Object[]{id}));
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
public <T> T findAll_XML(Class<T> responseType) throws ClientErrorException {
WebTarget resource = webTarget;
return resource.request(javax.ws.rs.core.MediaType.APPLICATION_XML).get(responseType);
}
public void close() {
client.close();
}
}
This line of code then returned an xml result of the query
result = c.findAll_XML(String.class);
which had this format
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<userss>
<users>
<userCategoryId>
<categoryId>2</categoryId>
<userCategory>admin</userCategory>
</userCategoryId>
<userName>admin</userName>
<userPassword>d033e22ae348aeb5660fc2140aec35850c4da997</userPassword>
</users>
</userss>
However, this line of code
List<Users> l = (List<Users>)c.findAll_XML(Users.class);
produces an exception, which seems to be caused by the "userss" tag that surrounds the xml result, I'm not sure how that came about.
Can anyone help me resolve this?
Exception in thread "AWT-EventQueue-0" javax.ws.rs.BadRequestException: HTTP 400 Bad Request
at org.glassfish.jersey.message.internal.AbstractRootElementJaxbProvider.readFrom(AbstractRootElementJaxbProvider.java:124)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor$TerminalReaderInterceptor.aroundReadFrom(ReaderInterceptorExecutor.java:188)
at org.glassfish.jersey.message.internal.ReaderInterceptorExecutor.proceed(ReaderInterceptorExecutor.java:134)
at org.glassfish.jersey.message.internal.MessageBodyFactory.readFrom(MessageBodyFactory.java:988)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:833)
at org.glassfish.jersey.message.internal.InboundMessageContext.readEntity(InboundMessageContext.java:768)
at org.glassfish.jersey.client.InboundJaxrsResponse.readEntity(InboundJaxrsResponse.java:96)
at org.glassfish.jersey.client.JerseyInvocation.translate(JerseyInvocation.java:740)
at org.glassfish.jersey.client.JerseyInvocation.access$500(JerseyInvocation.java:88)
at org.glassfish.jersey.client.JerseyInvocation$2.call(JerseyInvocation.java:650)
at org.glassfish.jersey.internal.Errors.process(Errors.java:315)
at org.glassfish.jersey.internal.Errors.process(Errors.java:297)
at org.glassfish.jersey.internal.Errors.process(Errors.java:228)
at org.glassfish.jersey.process.internal.RequestScope.runInScope(RequestScope.java:421)
at org.glassfish.jersey.client.JerseyInvocation.invoke(JerseyInvocation.java:646)
at org.glassfish.jersey.client.JerseyInvocation$Builder.method(JerseyInvocation.java:375)
at org.glassfish.jersey.client.JerseyInvocation$Builder.get(JerseyInvocation.java:275)
at service.Client.findAll_XML(Client.java:83)
at examples.Find.<init>(Find.java:44)
at examples.Find$1.run(Find.java:166)
at java.awt.event.InvocationEvent.dispatch(InvocationEvent.java:311)
at java.awt.EventQueue.dispatchEventImpl(EventQueue.java:744)
at java.awt.EventQueue.access$400(EventQueue.java:97)
at java.awt.EventQueue$3.run(EventQueue.java:697)
at java.awt.EventQueue$3.run(EventQueue.java:691)
at java.security.AccessController.doPrivileged(Native Method)
at java.security.ProtectionDomain$1.doIntersectionPrivilege(ProtectionDomain.java:75)
at java.awt.EventQueue.dispatchEvent(EventQueue.java:714)
at java.awt.EventDispatchThread.pumpOneEventForFilters(EventDispatchThread.java:201)
at java.awt.EventDispatchThread.pumpEventsForFilter(EventDispatchThread.java:116)
at java.awt.EventDispatchThread.pumpEventsForHierarchy(EventDispatchThread.java:105)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:101)
at java.awt.EventDispatchThread.pumpEvents(EventDispatchThread.java:93)
at java.awt.EventDispatchThread.run(EventDispatchThread.java:82)
Caused by: javax.xml.bind.UnmarshalException: unexpected element (uri:"", local:"userss"). Expected elements are <{}userCategory>,<{}users>
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.handleEvent(UnmarshallingContext.java:681)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:247)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportError(Loader.java:242)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.Loader.reportUnexpectedChildElement(Loader.java:109)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext$DefaultRootLoader.childElement(UnmarshallingContext.java:1086)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext._startElement(UnmarshallingContext.java:510)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallingContext.startElement(UnmarshallingContext.java:492)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.SAXConnector.startElement(SAXConnector.java:163)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.startElement(AbstractSAXParser.java:509)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.scanStartElement(XMLNSDocumentScannerImpl.java:378)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl$NSContentDriver.scanRootElementHook(XMLNSDocumentScannerImpl.java:604)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl$FragmentContentDriver.next(XMLDocumentFragmentScannerImpl.java:3122)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl$PrologDriver.next(XMLDocumentScannerImpl.java:880)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentScannerImpl.next(XMLDocumentScannerImpl.java:606)
at com.sun.org.apache.xerces.internal.impl.XMLNSDocumentScannerImpl.next(XMLNSDocumentScannerImpl.java:117)
at com.sun.org.apache.xerces.internal.impl.XMLDocumentFragmentScannerImpl.scanDocument(XMLDocumentFragmentScannerImpl.java:510)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:848)
at com.sun.org.apache.xerces.internal.parsers.XML11Configuration.parse(XML11Configuration.java:777)
at com.sun.org.apache.xerces.internal.parsers.XMLParser.parse(XMLParser.java:141)
at com.sun.org.apache.xerces.internal.parsers.AbstractSAXParser.parse(AbstractSAXParser.java:1213)
at com.sun.org.apache.xerces.internal.jaxp.SAXParserImpl$JAXPSAXParser.parse(SAXParserImpl.java:649)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal0(UnmarshallerImpl.java:243)
at com.sun.xml.internal.bind.v2.runtime.unmarshaller.UnmarshallerImpl.unmarshal(UnmarshallerImpl.java:214)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:140)
at javax.xml.bind.helpers.AbstractUnmarshallerImpl.unmarshal(AbstractUnmarshallerImpl.java:123)
at org.glassfish.jersey.message.internal.XmlRootElementJaxbProvider.readFrom(XmlRootElementJaxbProvider.java:140)
at org.glassfish.jersey.message.internal.AbstractRootElementJaxbProvider.readFrom(AbstractRootElementJaxbProvider.java:122)
... 33 more
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.