I am newbie in spring. I'm trying to perform add,delete,edit operation on database through spring and hibernate.delete and add operation are successfully executed but When i am trying to edit by clicking on edit. i'm getting this error:
full stacktrace:
org.hibernate.QueryParameterException: could not locate named parameter [UserId]
at org.hibernate.engine.query.ParameterMetadata.getNamedParameterDescriptor(ParameterMetadata.java:75)
at org.hibernate.engine.query.ParameterMetadata.getNamedParameterExpectedType(ParameterMetadata.java:81)
at org.hibernate.impl.AbstractQueryImpl.determineType(AbstractQueryImpl.java:413)
at org.hibernate.impl.AbstractQueryImpl.setParameter(AbstractQueryImpl.java:383)
at UserDao.userDaoImpl.getUserById(userDaoImpl.java:48)
at UserService.userServiceImpl.getUserById(userServiceImpl.java:41)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.aop.support.AopUtils.invokeJoinpointUsingReflection(AopUtils.java:307)
at org.springframework.aop.framework.ReflectiveMethodInvocation.invokeJoinpoint(ReflectiveMethodInvocation.java:183)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:150)
at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:108)
at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:172)
at org.springframework.aop.framework.JdkDynamicAopProxy.invoke(JdkDynamicAopProxy.java:202)
at com.sun.proxy.$Proxy17.getUserById(Unknown Source)
at UserController.userController.edit(userController.java:51)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:606)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:710)
at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:167)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:414)
at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:402)
at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:771)
at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:716)
at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:647)
at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:552)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:620)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:727)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:303)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:241)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:208)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:220)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:122)
at org.apache.catalina.authenticator.AuthenticatorBase.invoke(AuthenticatorBase.java:501)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:171)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:102)
at org.apache.catalina.valves.AccessLogValve.invoke(AccessLogValve.java:950)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:116)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:408)
at org.apache.coyote.http11.AbstractHttp11Processor.process(AbstractHttp11Processor.java:1040)
at org.apache.coyote.AbstractProtocol$AbstractConnectionHandler.process(AbstractProtocol.java:607)
at org.apache.tomcat.util.net.JIoEndpoint$SocketProcessor.run(JIoEndpoint.java:316)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1145)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:615)
at org.apache.tomcat.util.threads.TaskThread$WrappingRunnable.run(TaskThread.java:61)
at java.lang.Thread.run(Thread.java:745)
My jsp: "user.jsp"
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Spring</title>
</head>
<body>
<h2>Add User Data</h2>
<form:form method="POST" modelAttribute="user" action="/SpringHibernate1/addUser">
<table>
<tr>
<td><form:label path="name">Name:</form:label></td>
<td><form:input path="name" value="${user.name}"/></td>
</tr>
<tr>
<td><form:label path="department">Department:</form:label></td>
<td><form:input path="department" value="${user.department}"/></td>
</tr>
<tr>
<td><form:label path="password">Password:</form:label></td>
<td><form:input path="password" value="${user.password}"/></td>
</tr>
<tr>
<td colspan="2"><input type="submit" value="Submit"/></td>
</tr>
</table>
</form:form>
<h2>List users</h2>
<table align="left" border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Department</th>
<th>Password</th>
<th>Actions on Row</th>
</tr>
<c:forEach items="${userList}" var="user1">
<tr>
<td><c:out value="${user1.id}"/></td>
<td><c:out value="${user1.name}"/></td>
<td><c:out value="${user1.department}"/></td>
<td><c:out value="${user1.password}"/></td>
<td align="center">Edit | Delete</td>
</tr>
</c:forEach>
</table>
</body>
</html>
Controller Class:" userController.java"
#Controller
public class userController {
#Autowired
private userService userService;
#RequestMapping("/user")
public String listUser(Map<String, Object> map) {
map.put("user", new User());
map.put("userList", userService.listUser());
return "user";
}
#RequestMapping(value = "/addUser",method = RequestMethod.POST)
public String addUser(#ModelAttribute("user")User user, BindingResult result)
{
if(null == user.getId()) {
userService.addUser(user);
}
else {
userService.updateUser(user);
}
return "redirect:/user";
}
#RequestMapping("/delete/{userId}")
public String deleteUser(#PathVariable("userId") Integer userId)
{
userService.deleteUser(userId);
return "redirect:/user";
}
#RequestMapping("/edit/{userId}")
public String edit(#PathVariable("userId")Integer userId,Map<String, Object> map)
{
map.put("user", userService.getUserById(userId));
map.put("userList", userService.listUser());
return "user";
}
}
Dao Implemetation: "userDaoImpl.java"
#Repository
public class userDaoImpl implements userDao {
#Autowired
private SessionFactory sessionFactory;
#Override
public void addUser(User user) {
sessionFactory.getCurrentSession().save(user);
}
#Override
public void deleteUser(Integer id) {
User user = (User)sessionFactory.getCurrentSession().load(User.class,id);
if(null != user) {
sessionFactory.getCurrentSession().delete(user);
}
}
#Override
#SuppressWarnings("unchecked")
public List<User> listUser() {
return sessionFactory.getCurrentSession().createQuery("from User").list();
}
#Override
public void updateUser(User user) {
sessionFactory.getCurrentSession().update(user);
}
#Override
#SuppressWarnings("unchecked")
public User getUserById(Integer id) {
Session session = sessionFactory.getCurrentSession();
List<User> list = session.createQuery("from User u where u.id = :id").setParameter("UserId",id).list();
return list.size() > 0 ?(User)list.get(0): null;
}
public SessionFactory getSessionFactory() {
return sessionFactory;
}
public void setSessionFactory(SessionFactory sessionFactory) {
this.sessionFactory = sessionFactory;
}
}
need to change as below
List<User> list = session.createQuery("from User u where u.id = :id").setParameter("id",id).list();
Related
I create a project where admin and user can log in. I have JSP pages, only the admin can enter there, because access is restricted to the user. The user can go to certain pages.
I have two pages "allStudents.jsp" - only admin can go there.
And on this page "allStudentsUser.jsp" - only the user can enter.
So this is how to write the code in the controller correctly so that Tomkat read my "allStudentsUser.jsp" page.
Student Controller
#Controller
public class StudentController {
#Autowired
private ServletContext servletContext;
// Constructor based Dependency Injection
private StudentService studentService;
public StudentController() {
}
#Autowired
public StudentController(StudentService studentService) {
this.studentService = studentService;
}
#RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUser() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudents");
return mv;
}
#RequestMapping(value = "/allStudentsUser", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}
#RequestMapping(value = "/addStudent", method = RequestMethod.GET)
public ModelAndView displayNewUserForm() {
ModelAndView mv = new ModelAndView("addStudent");
mv.addObject("headerMessage", "Add Student Details");
mv.addObject("student", new Student());
return mv;
}
#PostMapping(value = "/addStudent")
public String saveNewStudent(#RequestParam("name") #NonNull String name,
#RequestParam("surname") #NonNull String surname,
#RequestParam("avatar") MultipartFile file)
throws IOException {
Student student = new Student();
student.setSurname(surname);
student.setName(name);
if (file != null && !file.isEmpty()) {
student.setAvatar(studentService.saveAvatarImage(file).getName());
}
studentService.saveStudent(student);
return "redirect:/allStudents";
}
#GetMapping(value = "/editStudent/{id}")
public ModelAndView displayEditUserForm(#PathVariable Long id) {
ModelAndView mv = new ModelAndView("editStudent");
Student student = studentService.getStudentById(id);
mv.addObject("headerMessage", "Редактирование студента");
mv.addObject("student", student);
return mv;
}
#PostMapping(value = "/editStudent")
public String saveEditedUser(
#RequestParam("id") Long id,
#RequestParam("name") String name,
#RequestParam("surname") String surname,
#RequestParam("avatar") MultipartFile file) {
try {
studentService.updateStudent(name, surname, file, studentService.getStudentById(id));
} catch (FileSystemException ex) {
ex.printStackTrace();
} catch (IOException e) {
return "redirect:/error";
}
return "redirect:/allStudents";
}
#GetMapping(value = "/deleteStudent/{id}")
public ModelAndView deleteUserById(#PathVariable Long id) {
studentService.deleteStudentById(id);
ModelAndView mv = new ModelAndView("redirect:/allStudents");
return mv;
}
}
Security Config
#Configuration
#EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {
#Override
protected void configure(final AuthenticationManagerBuilder auth) throws Exception {
auth.inMemoryAuthentication()
.withUser("admin").password(passwordEncoder().encode("1234")).roles("ADMIN")
.and()
.withUser("user").password(passwordEncoder().encode("user1234")).roles("USER")
.and();
}
#Override
protected void configure(HttpSecurity http) throws Exception {
http.authorizeRequests()
.antMatchers("/allStudentsUser**").permitAll()
.antMatchers("/allStudents**").hasRole("ADMIN")
.antMatchers("/addStudent/**").hasAnyRole("USER", "ADMIN")
.antMatchers("/editStudent/**").hasRole("ADMIN")
.antMatchers("/deleteStudent/**").hasRole("ADMIN")
.and()
.formLogin()
.loginPage("/login")
.defaultSuccessUrl("/allStudents")
.failureUrl("/login?error=true")
.and()
.logout()
.logoutSuccessUrl("/login?logout=true")
.and()
.csrf().disable();
}
#Bean
public PasswordEncoder passwordEncoder() {
return new BCryptPasswordEncoder();
}
}
AllStudents.jsp (for Admin)
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<link href="../css/style.css" rel="stylesheet" type="text/css">
<style><%#include file="/css/style.css"%></style>
<title>Все студенты</title>
</head>
<body>
<br>
<br>
<br>
<br>
<div class="it">
<h3>Список всех студентов</h3>
${message}
<br>
<br>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Avatar</th>
</tr>
</thead>
<tbody>
<c:forEach var="student" items="${studentList}">
<tr>
<th scope="row">1</th>
<td>${student.name}</td>
<td>${student.surname}</td>
<td><img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}" style="max-height: 200px; max-width: 200px;" /></td>
<td>
<sec:authorize access="hasRole('ADMIN')">
<a href="${pageContext.request.contextPath}/editStudent/${student.id}">
<button type="button" class="btn btn-primary">Edit</button>
</a>
</sec:authorize>
</td>
<td>
<sec:authorize access="hasRole('ADMIN')">
<a href="${pageContext.request.contextPath}/deleteStudent/${student.id}">
<button type="button" class="btn btn-primary">Delete</button>
</a>
</sec:authorize>
</td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
AllStudentsUser.jsp (For User)
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" isELIgnored="false"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%# taglib prefix="sec" uri="http://www.springframework.org/security/tags"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.4.0/js/bootstrap.min.js"></script>
<link href="../css/style.css" rel="stylesheet" type="text/css">
<style><%#include file="/css/style.css"%></style>
<title>Все студенты</title>
</head>
<body>
<br>
<br>
<br>
<br>
<div class="it">
<h3>Список всех студентов</h3>
${message}
<br>
<br>
<table class="table">
<thead>
<tr>
<th scope="col">#</th>
<th scope="col">Name</th>
<th scope="col">Surname</th>
<th scope="col">Avatar</th>
</tr>
</thead>
<tbody>
<c:forEach var="student" items="${studentList}">
<tr>
<th scope="row">1</th>
<td>${student.name}</td>
<td>${student.surname}</td>
<td><img src="${pageContext.request.contextPath}/avatar?avatar=${student.avatar}" style="max-height: 200px; max-width: 200px;" /></td>
</tr>
</c:forEach>
</tbody>
</table>
</div>
</body>
</html>
Student Controller (add Secured)
#RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUser() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudents");
return mv;
}
#Secured("ROLE_ADMIN")
#RequestMapping(value = "/allStudentsAdmin", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}
#Secured("ROLE_USER")
#RequestMapping(value = "/allStudentsUser", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
System.out.println("User Page Requested : All Students");
ModelAndView mv = new ModelAndView();
List<Student> studentList = studentService.getAllStudents();
mv.addObject("studentList", studentList);
mv.setViewName("allStudentsUser");
return mv;
}
i recommend to use #Secured("ADMIN") or #Secured("USER").
if you want use it, add to #EnableGlobalMethodSecurity(securedEnabled = true) at SecurityConfig.java.
example for your code:
#Secured("ROLE_ADMIN")
#RequestMapping(value = "/allStudents", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUser() {
// ...
}
#Secured("ROLE_USER")
#RequestMapping(value = "/allStudentsUser", method = {RequestMethod.GET, RequestMethod.POST})
public ModelAndView displayAllUsers() {
// ...
}
guide link : https://docs.spring.io/spring-security/site/docs/5.2.0.M3/reference/htmlsingle/#jc-method
This is my Entity
#Entity
public class User implements java.io.Serializable {
#Id
#GeneratedValue(strategy = GenerationType.AUTO)
private int id;
private String name;
private String mobNum;
private String email;
String gender;
#Type(type="org.jadira.usertype.dateandtime.joda.PersistentLocalDateTime")
LocalDate bdate;
public LocalDate getDate() {
return bdate;
}
public void setDate(LocalDate bdate) {
this.bdate = bdate;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public User() {
}
public String getName() {
return this.name;
}
public void setName(String name) {
this.name = name;
}
public String getMobNum() {
return this.mobNum;
}
public void setMobNum(String mobNum) {
this.mobNum = mobNum;
}
public String getEmail() {
return this.email;
}
public void setEmail(String email) {
this.email = email;
}
}
and here is my Spring-Form
<%#taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<form:form action="add_student_data.htm" method="POST" commandName="user">
<table>
<tr>
<td><form:label path="name">Name</form:label></td>
<td><form:input path="name"/></td>
<td><font color="red" /><form:errors path="name" cssClass="error" /></td>
</tr>
<tr>
<td><form:label path="bdate" >Date Of Birth</form:label></td>
<td><form:input path="bdate"/></td>
<td><font color="red" /><form:errors path="bdate" cssClass="bdate" /></td>
</tr>
<tr>
<td><form:label path="gender" >Gender</form:label></td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td><form:label path="mobNum">Mob Num</form:label></td>
<td><form:input path="mobNum"/></td>
<td><font color="red" /><form:errors path="mobNum" ccssClass="error"/></td>
</tr>
<tr>
<td><form:label path="email">Email</form:label></td>
<td><form:input path="email"/></td>
<td><font color="red" /><form:errors path="email" cssClass="error" /></td>
</tr>
</table>
<input type="submit" value="submit">
</form:form>
</body>
</html>
when i want to open this fom error is occured like
"org.apache.jasper.JasperException: org.springframework.beans.NotReadablePropertyException: Invalid property 'dateOfBirth' of bean class [com.domain.User]: Bean property 'dateOfBirth' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?"
I am using joda.org.time.LocalDate in User entity.What is the cause of the problem?
Your getter/setter method name and variable name in JSP do not match, change the following methods from:
public LocalDate getDate() {
return bdate;
}
public void setDate(LocalDate bdate) {
this.bdate = bdate;
}
to
public LocalDate getBdate() {
return bdate;
}
public void setBdate(LocalDate bdate) {
this.bdate = bdate;
}
I am not getting the drop down value in Profession. Actually I am getting exception
javax.servlet.ServletException: Type [java.lang.String] is not valid for option items
org.apache.jasper.runtime.PageContextImpl.doHandlePageException(PageContextImpl.java:848)
org.apache.jasper.runtime.PageContextImpl.handlePageException(PageContextImpl.java:781)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspService(org.apache.jsp.WEB_002dINF.views.Registration_jsp:85)
org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:322)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:314)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:264)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.springframework.web.servlet.view.InternalResourceView.renderMergedOutputModel(InternalResourceView.java:238)
org.springframework.web.servlet.view.AbstractView.render(AbstractView.java:263)
org.springframework.web.servlet.DispatcherServlet.render(DispatcherServlet.java:1208)
org.springframework.web.servlet.DispatcherServlet.processDispatchResult(DispatcherServlet.java:992)
org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:939)
org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:856)
org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:936)
org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:827)
javax.servlet.http.HttpServlet.service(HttpServlet.java:697)
org.springframework.web.servlet.FrameworkServlet.service(FrameworkServlet.java:812)
javax.servlet.http.HttpServlet.service(HttpServlet.java:810)
org.jboss.web.tomcat.filters.ReplyHeaderFilter.doFilter(ReplyHeaderFilter.java:81)
root cause
javax.servlet.jsp.JspException: Type [java.lang.String] is not valid for option items
org.springframework.web.servlet.tags.form.OptionWriter.writeOptions(OptionWriter.java:142)
org.springframework.web.servlet.tags.form.SelectTag.writeTagContent(SelectTag.java:223)
org.springframework.web.servlet.tags.form.AbstractFormTag.doStartTagInternal(AbstractFormTag.java:103)
org.springframework.web.servlet.tags.RequestContextAwareTag.doStartTag(RequestContextAwareTag.java:80)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspx_meth_form_select_0(org.apache.jsp.WEB_002dINF.views.Registration_jsp:283)
org.apache.jsp.WEB_002dINF.views.Registration_jsp._jspx_meth_form_form_0(org.apache.jsp.WEB_002dINF.views.Registration_jsp:144)
I understand something wrong with select tag .
please help
RegisterController
package net.codejava.spring.controller;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import net.codejava.spring.model.User;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
#Controller
#RequestMapping(value = "/register")
public class RegisterController {
#RequestMapping(method = RequestMethod.GET)
public ModelAndView initForm() {
User user = new User();
user.setUsername("Anukul");
ModelAndView mav = new ModelAndView("Registration");
//=== default user name======
//model.addAttribute("userNameDefault", "Enter Name");
mav.addObject("userNameDefault", "Enter Name");
//==== creating drop down list =====
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
// //==== adding drop down to user ====
mav.addObject("ProffesionList", profDropDown);
mav.addObject("user",user);
//==== user added to model =========
return mav;
}
#RequestMapping(method = RequestMethod.POST)
public String submitForm(Model model,#ModelAttribute User user) {
model.addAttribute(user);
// implement your own registration logic here...
return "RegistrationSuccess";
}
}
Registration.jsp
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Registration</title>
</head>
<body>
<div align="center">
<h1>reached here</h1>
<form:form action="register" method="POST" commandName="user">
<table border="0">
<tr>
<td colspan="2" align="center"><h2>Spring MVC Form Demo - Registration</h2></td>
</tr>
<tr>
<td>User Name:</td>
<td><form:input path="username" /></td>
</tr>
<tr>
<td>Password:</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>E-mail:</td>
<td><form:input path="email" /></td>
</tr>
<tr>
<td>Birthday (mm/dd/yyyy):</td>
<td><form:input path="birthDate" /></td>
</tr>
<tr>
<td>Profession:</td>
<td><form:select path="profession" items="${ProffesionList}" /></td>
</tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="Register" /></td>
</tr>
</table>
</form:form>
</div>
</body>
User.java
package net.codejava.spring.model;
import java.util.Date;
public class User {
private String username;
private String password;
private String email;
private Date birthDate;
private String profession;
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 getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public Date getBirthDate() {
return birthDate;
}
public void setBirthDate(Date birthDate) {
this.birthDate = birthDate;
}
public String getProfession() {
return profession;
}
public void setProfession(String profession) {
this.profession = profession;
}
}
----------------
does this works for you
<form:select id="profession" path="profession">
<form:options items="${ProffesionList}"/>
</form:select>
or try with this
<form:select id="profession" path="profession">
<c:forEach var="prof" items="${ProffesionList}">
<form:option value="${prof.key}" label="${prof.value}" />
</c:forEach>
</form:select>
Controller
#RequestMapping(method = RequestMethod.POST)
public String submitForm(Model model,#ModelAttribute User user) {
//==== creating drop down list =====
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
// //==== adding drop down to user ====
mav.addObject("ProffesionList", profDropDown);
model.addAttribute(user);
// implement your own registration logic here...
return "RegistrationSuccess";
}
or add #ModelATtribute
#ModelAttribute("ProffesionList")
public Map<String,String> getProfessions(){
Map<String,String> profDropDown = new HashMap<String, String>();
profDropDown.put("Lecturer", "Lecturer");
profDropDown.put("proff", "proff");
return profDropDown;
}
i m encountering the date problem in UI using spring , when i fetch query from database the data format is shown in my UI is 1987-02-12 00:00:00.0 when i submit the values null is going in database . I have used the
return getJdbcTemplate().update(
QUERY_CREATE_PROJECT,
new Object[] { employeeProject.getEmployeeNumber(),
employeeProject.getProjectCode(),
employeeProject.getStartDate(),
employeeProject.getEndDate(),
employeeProject.getProjectRole() }) != 0 ? true : false;
} method of spring , my reqiurement is to show date in format (dd/MM/yyyy) and insert the date in same format .How to convert the format of date in our custom date plz help me and also tell me where to use customization of date , should i customize date in controller layer ,DAO layer or in service layer
my controller method of creating is
package com.nousinfo.tutorial.controllers;
import java.util.Map;
import javax.validation.Valid;
import org.springframework.stereotype.Controller;
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 org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;
import com.nousinfo.tutorial.model.ProjectForm;
import com.nousinfo.tutorial.service.impl.ProjectServiceImpl;
import com.nousinfo.tutorial.service.model.EmployeeProjectBO;
/**
*
* #author ankurj
*
*/
#Controller
#RequestMapping("projectController")
public class ProjectController {
private ProjectServiceImpl projectServiceImpl;
public ProjectServiceImpl getProjectServiceImpl() {
return projectServiceImpl;
}
public void setProjectServiceImpl(ProjectServiceImpl projectServiceImpl) {
this.projectServiceImpl = projectServiceImpl;
}
/**
* Used to set the view
* #param id
* #return
* #throws Exception
*/
#RequestMapping(value = "/projectForm", method = RequestMethod.GET)
public ModelAndView view(#RequestParam("id") int id) throws Exception {
ModelAndView modelAndView = new ModelAndView();
System.out.println(id);
ProjectForm projectForm = new ProjectForm();
projectForm.setEmployeeNumber(id);
modelAndView.addObject("projectForm", projectForm);
modelAndView.setViewName("projectForm");
return modelAndView;
}
/**
* Create the project for an employee
* #param projectForm
* #param bindingResult
* #param model
* #return
* #throws Exception
*/
#RequestMapping(value = "/createProject", method = RequestMethod.POST)
public String createEmployee(#Valid ProjectForm projectForm,
BindingResult bindingResult, Map<String, ProjectForm> model)
throws Exception {
String form = null;
if (bindingResult.hasErrors()) {
return "projectForm";
}
model.put("projectForm", projectForm);
projectForm.setUpdateStatus("A");
if (projectForm.getUpdateStatus().charAt(0) == 'A') {
boolean flag = projectServiceImpl
.actionDecider(convertprojectFormToprojectBO(projectForm));
if (flag == false)
form = "DBError";
else
form = "Success";
}
return form;
}
/**
* This method update the existing detail of project
* #param projectForm
* #param bindingResult
* #return
*/
#RequestMapping(value = "/updateProject", method = RequestMethod.POST)
public String updateDepartment(
#ModelAttribute("projectForm") ProjectForm projectForm,
BindingResult bindingResult) {
String form = null;
projectForm.setUpdateStatus("M");
if (projectForm.getUpdateStatus().charAt(0) == 'M') {
boolean flag = projectServiceImpl
.actionDecider(convertprojectFormToprojectBO(projectForm));
if (flag == false)
form = "DBError";
else
form = "Success";
}
return form;
}
and this is my model class
package com.nousinfo.tutorial.model;
import java.util.Date;
import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.NumberFormat;
public class ProjectForm {
#NotNull
#NumberFormat
#Min(1)
private Integer employeeNumber;
#NotEmpty(message = "project code can't be blank")
private String projectCode;
private Date startDate;
private Date endDate;
private String role;
private String updateStatus;
public String getProjectCode() {
return projectCode;
}
public void setProjectCode(String projectCode) {
this.projectCode = projectCode;
}
public Date getStartDate() {
return startDate;
}
public void setStartDate(Date startDate) {
this.startDate = startDate;
}
public Date getEndDate() {
return endDate;
}
public void setEndDate(Date endDate) {
this.endDate = endDate;
}
public String getRole() {
return role;
}
public void setRole(String role) {
this.role = role;
}
public Integer getEmployeeNumber() {
return employeeNumber;
}
public void setEmployeeNumber(Integer employeeNumber) {
this.employeeNumber = employeeNumber;
}
public String getUpdateStatus() {
return updateStatus;
}
public void setUpdateStatus(String updateStatus) {
this.updateStatus = updateStatus;
}
}
this is my jsp for date
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%#taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib uri="http://www.springframework.org/tags" prefix="spring"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title></title>
<script>
function actionChange(url) {
if (url == 'Save') {
document.form.action = "/EmployeeWebSpring/projectController/updateProject";
}
if (url == 'Delete') {
document.form.action = "/EmployeeWebSpring/projectController/deleteProject";
}
}
function home() {
window.location.href = "/EmployeeWebSpring/search/searchspring";
}
</script>
</head>
<body background="../images/flower.jpg">
<img src="../images/Header.png" width="1500"/>
<hr width="1500">
<form:form name='form' commandName="projectForm">
<fmt:message key="project.searchResult.header" />
<c:choose>
<c:when test="${empty requestScope.projectBO}">
<fmt:message key="searchResult.noresult" />
</c:when>
<c:otherwise>
<table align="center">
<form:hidden path="updateStatus" />
<tr align="center">
<th><fmt:message key="employeeNumber" /></th>
<td><form:input path="employeeNumber"
value="${requestScope.projectBO.employeeNumber}" /></td>
</tr>
<tr align="center">
<th><fmt:message key="projectCode" /></th>
<td><form:input path="projectCode"
value="${requestScope.projectBO.projectCode}" /></td>
</tr>
<tr>
<tr align="center">
<th><fmt:message key="startDate" /></th>
<td><form:input path="startDate"
value="${requestScope.projectBO.startDate}" /></td>
</tr>
<tr>
<tr align="center">
<th><fmt:message key="endDate" /></th>
<td><form:input path="endDate"
value="${requestScope.projectBO.endDate}" /></td>
</tr>
<tr>
<tr align="center">
<th><fmt:message key="role" /></th>
<td><form:input path="role"
value="${requestScope.projectBO.role}" /></td>
</tr>
</table>
<br>
<center>
<table>
<tr>
<td><input type="submit" name="method" value="Save"
onclick="actionChange(this.value)" /></td>
<td><input type="submit" name="method" value="Delete"
onclick="actionChange(this.value)" /></td>
<td><input type="button" onclick="home" value="Cancel" /></td>
</tr>
</table>
</center>
</c:otherwise>
</c:choose>
<br />
<fmt:message key="searchResult.searchAgain" />
<a href="/EmployeeWebSpring/search/searchspring"> <fmt:message
key="searchResult.click" />
</a>
</form:form>
</body>
</html>
All you need is the custom editor for Date type, through which you can format the incoming & outgoing date object.This was already explained in the post
Spring MVC - Binding a Date Field
I am trying to bind the input type checkbox using spring form controller,But i failed .
Here i am posting Controller,bean and jsp example,One more thing is i can't use
.
Below is the code:
Controller:
package com.test.web;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.SimpleFormController;
import com.vaannila.domain.User;
import com.vaannila.service.UserService;
#SuppressWarnings("deprecation")
public class UserController extends SimpleFormController {
private UserService userService;
public UserController() {
setCommandClass(User.class);
setCommandName("user");
}
public void setUserService(UserService userService) {
this.userService = userService;
}
#Override
protected ModelAndView onSubmit(Object command) throws Exception {
User user = (User) command;
user.setCommunity(user.getCommunity());
userService.add(user);
return new ModelAndView("userForm","user",user);
}
}
jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<script>
function submitForm(){
document.testForm.submit();
}
</script>
</head>
<body>
<form:form method="POST" commandName="user" name="testForm" action="./userRegistration.htm">
<table>
<tr>
<td>User Name :</td>
<td><form:input path="name" /></td>
</tr>
<tr>
<td>Password :</td>
<td><form:password path="password" /></td>
</tr>
<tr>
<td>Gender :</td>
<td><form:radiobutton path="gender" value="M" label="M" />
<form:radiobutton path="gender" value="F" label="F" /></td>
</tr>
<tr>
<td>Country :</td>
<td><form:select path="country">
<form:option value="0" label="Select" />
<form:option value="1" label="India" />
<form:option value="2" label="USA" />
<form:option value="3" label="UK" />
</form:select></td>
</tr>
<tr>
<td>About you :</td>
<td><form:textarea path="aboutYou" /></td>
</tr>
<tr>
<td>Community :</td>
<td><input type="checkbox" name="community" value="Hibernate"/>Hibernate</br>
<input type="checkbox" name="community" value="test"/>test</br>
<input type="checkbox" name="community" value="test1"/>test1</br>
</td>
</tr>
<tr>
<td></td>
<td><form:checkbox path="mailingList"
label="Would you like to join our mailinglist?" /></td>
</tr>
<tr>
<td colspan="2"><input type="submit" onclick="submitForm();"></td>
</tr>
</table>
</form:form>
</body>
</html>
Java beans:
package com.test.domain;
public class User {
private String name;
private String password;
private String gender;
private String country;
private String aboutYou;
private String[] community;
private Boolean mailingList;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
public String[] getCommunity() {
return community;
}
public void setCommunity(String[] community) {
this.community = community;
}
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
I tried different ways,but no luck.Any hints please.
the browser will not send the field in the request if the checkbox isn't checked. the value will either be "true" or not sent. you will never get a "false" value.
add a hidden field with _name for every checkbox
EX:
<input type="checkbox" name="community" value="Hibernate"/>
<input type="hidden" name="_community" value="on"/>
Then, spring will take care of it.
If you do not use the form tag it will not automaticly bind your checkboxes. If you use plain html you have to bind the your self.
You can solve this by adding a list of community objects and then use form:checkboxes.
For example:
<form:checkboxes path="communityList" items="${communityList}" itemValue="key" itemLabel="value" />
I would also recomend you to use a HashMap when using ModelAndView like this:
Map<String, Object> model = new HashMap<String, Object>();
model.put("user", user);
model.put("communityList", communityList);
return new ModelAndView("userFormat", model);
Manually bind using 'ServletRequestUtils'... http://static.springsource.org/spring/docs/2.5.x/api/org/springframework/web/bind/ServletRequestUtils.html
Example
public ModelAndView test(HttpServletRequest request, HttpServletResponse response) throws ServletRequestBindingException {
Long subscriptionOwnerId = ServletRequestUtils.getLongParameter(request, "id");
return new ModelAndView('test'); }`