Struts+spring+jooq integration - struts action not invoked - spring

I am writing a struts+spring+jooq integration sample webapp.
I have a employee table in db and a jsp where in I can search for an employee in the db and show details. Problem is on clicking search nothing happens. There is no error in logs as well my print statements in searchEmp action don't show anything on console. Can you please tell me why the struts action method is not being invoked?Here are the details
index.jsp file
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<!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>Struts 2 Spring integration </title>
</head>
<body>
<s:form>
<s:textfield label="Enter Id" name="eid" value="Enter employee name here.."></s:textfield>
<s:textfield label="Enter name" name="name" value="Enter name here.."> </s:textfield>
<s:textfield label="Enter city" name="city" value="Enter city here.."> </s:textfield>
<s:submit value="Create new employee" action="saveEmpAction"/>
<s:submit value="Update Employee" action="updateEmpAction"></s:submit>
<s:submit value="Delete Employee" action="deleteEmpAction"></s:submit>
<s:submit value="Search Employee" action="searchEmpAction"></s:submit>
</s:form>
<s:property value="message"/>
<hr>
<table border="1">
<s:iterator value="emps">
<tr>
<td><s:property value="eid"/></td>
<td><s:property value="name"/></td>
<td><s:property value="city"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>
Here is my EmpAction.java class
package com.rewardsapp.action;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;
import test.generated.tables.pojos.Emp;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.opensymphony.xwork2.Preparable;
import com.rewardsapp.dao.EmpDao;
public class EmpAction extends ActionSupport implements ModelDriven<Emp>, Preparable{
/**
*
*/
private static final long serialVersionUID = -2435427486571261741L;
Emp emp;
EmpDao empdao;
String message;
List<Emp> empList;
#Override
public void prepare() throws Exception {
emp = new Emp();
message = "";
empList = new ArrayList<Emp>();
ServletContext ctx = ServletActionContext.getServletContext();
WebApplicationContext webappCtx = WebApplicationContextUtils.getWebApplicationContext(ctx);
empdao = (EmpDao)webappCtx.getBean("empDao");
}
#Override
public Emp getModel() {
return emp;
}
public String searchEmpAction() throws Exception {
System.out.println("In search emp action");
System.out.println("Search employee : " + emp.getName());
Emp emp2 = empdao.getEmployee(emp.getId());
empList.add(emp2);
System.out.println("In search emp action");
System.out.println("Searched employee : " + emp2.getName());
return SUCCESS;
}
public Emp getEmp() {
return emp;
}
public void setEmp(Emp emp) {
this.emp = emp;
}
public EmpDao getEmpdao() {
return empdao;
}
public void setEmpdao(EmpDao empdao) {
this.empdao = empdao;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public List<Emp> getEmpList() {
return empList;
}
public void setEmpList(List<Emp> empList) {
this.empList = empList;
}
}
Here is my dao class:
package com.rewardsapp.dao;
import org.jooq.DSLContext;
import org.springframework.dao.DataAccessException;
import com.rewardsapp.enums.ObjectType;
import com.rewardsapp.utils.NullObjectRegistry;
import static test.generated.tables.Emp.EMP;
import test.generated.tables.pojos.Emp;
import test.generated.tables.records.EmpRecord;
public class EmpDao {
/** The Constant NULL_CUSTOMER. */
private static final Emp NULL_EMP = (Emp) NullObjectRegistry.getNullObject(ObjectType.EMP);
DSLContext dslContext;
public DSLContext getDslContext() {
return dslContext;
}
public void setDslContext(DSLContext dslContext) {
this.dslContext = dslContext;
}
public Emp getEmployee(int empId) throws Exception {
try {
EmpRecord empRecord = (EmpRecord) dslContext.select().from(EMP)
.where((EMP.ID.equal(empId))).fetchAny();
return (empRecord != null) ? empRecord.into(Emp.class) : NULL_EMP;
} catch (DataAccessException e) {
e.printStackTrace();
/*throw new SystemException("Exception during getCustomerByCustomerType: " + customerType, e,
SystemErrorCode.SQL_EXCEPTION_ERROR)*/;
throw new Exception();
}
}
}
Struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
"http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<package name="default" extends="struts-default" namespace="/">
<action name="searchEmpAction" class="com.rewardsapp.action.EmpAction" method="searchEmpAction">
<result name="success">index.jsp</result>
<result name="input">index.jsp</result>
<result name="error">index.jsp</result>
</action>
</package>
</struts>

Related

not able to see spring mvc validation error messages

I am new to spring MVC. To practice out my skills I made a sample form whose elements gets populated through respective controller. Now to check the validation part, I used all methodologies through annotations i.e. #NotNull, #Size, #Valid, #ModelAttribute, and BindingResult object. Below are the files I am using. I was following every necessary aspect, but don't know why am I not able to see RED colored validation messages.
Student class
package com.sikka.springmvcworking.custombeans;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
public class Student {
private String firstName;
#NotNull
#Size(min=1,message="is required")
private String lastName;
private String country;
private String course;
private String[] knownOs;
private String[] coutries;
private Map<String,String> countryMap;
private Map<String,String> courseMap;
private Map<String,String> kosMap;
public Student() {
}
public Student(String firstName, String lastName, String country, String course, String[] knownOs, String[] coutries,
Map<String, String> countryMap, Map<String, String> courseMap, Map<String, String> kosMap) {
this.firstName = firstName;
this.lastName = lastName;
this.country = country;
this.course = course;
this.knownOs = knownOs;
this.coutries = coutries;
this.countryMap = countryMap;
this.courseMap = courseMap;
this.kosMap = kosMap;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public Map<String, String> getCountryMap() {
return countryMap;
}
public void setCountryMap(Map<String, String> countryMap) {
this.countryMap = countryMap;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public String[] getKnownOs() {
return knownOs;
}
public void setKnownOs(String[] knownOs) {
this.knownOs = knownOs;
}
public String[] getCoutries() {
return coutries;
}
public void setCoutries(String[] coutries) {
this.coutries = coutries;
}
public Map<String, String> getCourseMap() {
return courseMap;
}
public void setCourseMap(Map<String, String> courseMap) {
this.courseMap = courseMap;
}
public Map<String, String> getKosMap() {
return kosMap;
}
public void setKosMap(Map<String, String> kosMap) {
this.kosMap = kosMap;
}
}
Student Controller class
package com.sikka.springmvcworking.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import java.util.*;
import javax.validation.Valid;
import com.sikka.springmvcworking.custombeans.Student;
#Controller
#RequestMapping("stu")
public class StudentController {
#RequestMapping("studentForm")
public String getStudentForm(Model model) {
Student student = new Student();
Map<String,String> countryMap = new LinkedHashMap<String,String>();
countryMap.put("IN", "INDIA");
countryMap.put("BR", "BRAZIL");
countryMap.put("MX", "MEXICO");
student.setCountryMap(countryMap);
Map<String,String> courseMap = new LinkedHashMap<String,String>();
courseMap.put("java", "JAVA");
courseMap.put(".net", ".NET");
courseMap.put("php", "PHP");
courseMap.put("andr", "ANDROID");
student.setCourseMap(courseMap);
Map<String,String> kosMap = new LinkedHashMap<String,String>();
kosMap.put("win", "WINDOWS");
kosMap.put("lnx", "LINUX");
kosMap.put("mac", "MACINTOSH");
student.setKosMap(kosMap);
model.addAttribute("student", student);
System.out.println("inside STUDENT-FORM");
return "STUDENT-FORM";
}
#RequestMapping("processStudent")
public String outputStudent(#Valid #ModelAttribute("student") Student student, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return "redirect:studentForm";
}
return "VIEW-STUDENT";
}
}
Student Form JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
<style>
.error {color: red;}
</style>
</head>
<body>
<form:form action="processStudent" modelAttribute="student">
FirstName : <form:input type="text" path="firstName" placeholder="enter your first name"/><br>
LastName : <form:input type="text" path="lastName" placeholder="enter your last name"/>
<form:errors path="lastName" cssClass="error"/><br>
select country : <form:select path="coutries">
<form:options items="${student.countryMap}"/>
</form:select><br>
select course : <form:radiobuttons path="course" items="${student.courseMap}"/><br>
known OS(s) : <form:checkboxes items="${student.kosMap}" path="knownOs"/><br>
<input type="submit" value="submit">
</form:form>
</body>
</html>
Student Submit/View Jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<br>
Student Name : ${student.firstName} ${student.lastName} <br>
Student visited countries:<br>
<c:forEach var="t" items="${student.coutries}">
<li> ${t} </li>
</c:forEach><br>
Known OS by student : <br>
<c:forEach var="t" items="${student.knownOs}">
<li> ${t} </li>
</c:forEach><br>
Student course : ${student.course}<br>
</body>
</html>
Every time to try lastName validation, I am leaving it blank. I am being redirected to same Student Form but with no error messages.
Is there any way to show validation error message in this jsp form.
I changed my Student Controller class to below code. Basically I used RedirectAttributes in my processStudent mapping. I also separate out the spring form element making maps to different methods. In studentForm I checked if student already exist (due to after validation process in processStudent mapping). Please see code:
Student-Controller class
package com.sikka.springmvcworking.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;
import java.util.*;
import javax.validation.Valid;
import com.sikka.springmvcworking.custombeans.Student;
#Controller
#RequestMapping("stu")
public class StudentController {
#RequestMapping("studentForm")
public String getStudentForm(Model model) {
Student student = new Student();
student.setCountryMap(getCountryMap());
student.setCourseMap(getCourseMap());
student.setKosMap(getKosMap());
if (!model.containsAttribute("student")) {
System.out.println("student not there");
model.addAttribute("student",student);
}
else {
System.out.println("student already there");
}
return "STUDENT-FORM";
}
#RequestMapping("processStudent")
public String outputStudent(#Valid #ModelAttribute("student") Student student, BindingResult bindingResult,RedirectAttributes attr) {
if(bindingResult.hasErrors()) {
attr.addFlashAttribute("org.springframework.validation.BindingResult.student", bindingResult);
student.setCountryMap(getCountryMap());
student.setCourseMap(getCourseMap());
student.setKosMap(getKosMap());
attr.addFlashAttribute("student", student);
return "redirect:studentForm";
}
return "VIEW-STUDENT";
}
private Map<String,String> getCountryMap(){
Map<String,String> countryMap = new LinkedHashMap<String,String>();
countryMap.put("IN", "INDIA");
countryMap.put("BR", "BRAZIL");
countryMap.put("MX", "MEXICO");
return countryMap;
}
private Map<String,String> getCourseMap(){
Map<String,String> courseMap = new LinkedHashMap<String,String>();
courseMap.put("java", "JAVA");
courseMap.put(".net", ".NET");
courseMap.put("php", "PHP");
courseMap.put("andr", "ANDROID");
return courseMap;
}
private Map<String,String> getKosMap(){
Map<String,String> kosMap = new LinkedHashMap<String,String>();
kosMap.put("win", "WINDOWS");
kosMap.put("lnx", "LINUX");
kosMap.put("mac", "MACINTOSH");
return kosMap;
}
}
Above approach solved my problem. I am not an expert in spring. Anyone out here can explain more deeply.

PropertyNotFoundException in Spring-Boot

Why am I getting PropertyNotFoundException?
Flight.java:
package com.bulbul.flightreservation.entities;
import java.sql.Timestamp;
import java.util.Date;
import javax.persistence.Entity;
import javax.persistence.Table;
#Entity
#Table(name="Flight")
public class Flight extends AbstractEntity
{
private String Flight_Number;
public String Operating_Airlines;
private String Departure_City;
private String Arrival_City;
private Date date_Of_Departure;
private Timestamp estimated_departure_time;
public String getFlight_Number() {
return Flight_Number;
}
public void setFlight_Number(String flight_Number) {
Flight_Number = flight_Number;
}
public String getOperating_Airlines() {
return Operating_Airlines;
}
public void setOperating_Airlines(String Operating_Airlines) {
this.Operating_Airlines =Operating_Airlines;
}
public String getDeparture_City() {
return Departure_City;
}
public void setDeparture_City(String departure_City) {
Departure_City = departure_City;
}
public String getArrival_City() {
return Arrival_City;
}
public void setArrival_City(String arrival_City) {
Arrival_City = arrival_City;
}
public Timestamp getEstimated_departure_time() {
return estimated_departure_time;
}
public void setEstimated_departure_time(Timestamp estimated_departure_time) {
this.estimated_departure_time = estimated_departure_time;
}
public Date getDate_Of_Departure() {
return date_Of_Departure;
}
public void setDate_Of_Departure(Date date_Of_Departure) {
this.date_Of_Departure = date_Of_Departure;
}
}
Controller.java:
#RequestMapping(value="/findFlights",method=RequestMethod.POST)
public String findFlights(#RequestParam("from") String from,#RequestParam("to") String to,
#RequestParam("date_Of_Departure") #DateTimeFormat(pattern="yyyy-MM-dd") Date date_Of_Departure,ModelMap modelMap)
{
List<Flight> flight = flightRepository.findFlights(from,to,date_Of_Departure);
modelMap.addAttribute("flight",flight);
return "displayFlights";
}
#RequestMapping(value="/Already_User",method=RequestMethod.GET)
public String alreadyUser()
{
return "login/login";
}
FlightRepository.java
package com.bulbul.flightreservation.repository;
import java.util.Date;
import java.util.List;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import com.bulbul.flightreservation.entities.Flight;
public interface FlightRepository extends JpaRepository<Flight,Long>
{
#Query("from Flight where Departure_City=:Departure_City and Arrival_City=:Arrival_City and date_Of_Departure=:date_Of_Departure")
List<Flight> findFlights(#Param("Departure_City") String from,#Param("Arrival_City")
String to,#Param("date_Of_Departure") Date date_Of_Departure);
}
displayFlight.jsp:
<%# 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"%>
<%#page isELIgnored="false"%>
<!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>Display Flights</title>
</head>
<body>
<center>
<h1>Flight Available</h1>
<table>
<tr>
<th>Operating_Airlines</th>
<th>Departure_City</th>
<th>Arrival_City</th>
<th>Departure_Time</th>
</tr>
<c:forEach items="${flight}" var="flight">
<tr>
<td>${flight.Operating_Airlines}</td>
<td>${flight.Departure_City}</td>
<td>${flight.Arrival_City}</td>
<td>${flight.Departure_Time}</td>
<td><a href=showCompleteReservation?id=${flight.id}>Select</a></td>
</tr>
</c:forEach>
</table>
</center>
</body>
</html>
Exception:Property [Operating_Airlines] not found on type
[com.bulbul.flightreservation.entities.Flight]
javax.el.PropertyNotFoundException: Property [Operating_Airlines] not found on type [com.bulbul.flightreservation.entities.Flight]
at javax.el.BeanELResolver$BeanProperties.get(BeanELResolver.java:260) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at javax.el.BeanELResolver$BeanProperties.access$300(BeanELResolver.java:212) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at javax.el.BeanELResolver.property(BeanELResolver.java:347) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at javax.el.BeanELResolver.getValue(BeanELResolver.java:92) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at org.apache.jasper.el.JasperELResolver.getValue(JasperELResolver.java:110) ~[tomcat-embed-jasper-8.5.34.jar:8.5.34]
at org.apache.el.parser.AstValue.getValue(AstValue.java:169) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at org.apache.el.ValueExpressionImpl.getValue(ValueExpressionImpl.java:190) ~[tomcat-embed-el-8.5.34.jar:8.5.34]
at org.apache.jasper.runtime.PageContextImpl.proprietaryEvaluate(PageContextImpl.java:944) ~[tomcat-embed-jasper-8.5.34.jar:8.5.34]
at org.apache.jsp.WEB_002dINF.jsps.displayFlights_jsp._jspx_meth_c_005fforEach_005f0(displayFlights_jsp.java:196) ~[na:na]
at org.apache.jsp.WEB_002dINF.jsps.displayFlights_jsp._jspService(displayFlights_jsp.java:138) ~[na:na]
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70) ~[tomcat-embed-jasper-8.5.34.jar:8.5.34]

CRUD using spring and mybatis

HI hava a problem while creating a CRUD operation in browser
`HTTP Status 500 -
--------------------------------------------------------------------------------
type Exception report
message
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: org.apache.jasper.JasperException: org.springframework.beans.NotReadablePropertyException: Invalid property 'standard' of bean class [com.raistudies.domain.User]: Bean property 'standard' is not readable or has an invalid getter method: Does the return type of the getter match the parameter type of the setter?
org.apache.jasper.servlet.JspServletWrapper.handleJspException(JspServletWrapper.java:548)
org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:456)
org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:389)
org.apache.jasper.servlet.JspServlet.service(JspServlet.java:333)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
here I have all part of the spring mvc + mybatis operations file
//controller
package com.raistudies.controllers;
import java.util.List;
import java.util.UUID;
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 org.springframework.web.servlet.ModelAndView;
import com.raistudies.domain.User;
import com.raistudies.persistence.UserService;
import com.raistudies.validator.RegistrationValidator;
#Controller
#RequestMapping(value="/registration")
public class RegistrationController {
private RegistrationValidator validator = null;
private UserService userService = null;
#Autowired
public void setUserService(UserService userService) {
this.userService = userService;
}
public RegistrationValidator getValidator() {
return validator;
}
#Autowired
public void setValidator(RegistrationValidator validator) {
this.validator = validator;
}
#RequestMapping(method=RequestMethod.GET)
public String showForm(ModelMap model){
List<User> users = userService.getAllUser();
model.addAttribute("users", users);
User user = new User();
user.setId(UUID.randomUUID().toString());
model.addAttribute("user", user);
return "registration";
}
#RequestMapping(value="/add", method=RequestMethod.POST)
public ModelAndView add(#ModelAttribute(value="user") User user,BindingResult result){
validator.validate(user, result);
ModelAndView mv = new ModelAndView("registration");
if(!result.hasErrors()){
userService.saveUser(user);
user = new User();
user.setId(UUID.randomUUID().toString());
mv.addObject("user", user);
}
mv.addObject("users", userService.getAllUser());
return mv;
}
#RequestMapping(value="/update", method=RequestMethod.POST)
public ModelAndView update(#ModelAttribute(value="user") User user,BindingResult result){
validator.validate(user, result);
ModelAndView mv = new ModelAndView("registration");
if(!result.hasErrors()){
userService.updateUser(user);
user = new User();
user.setId(UUID.randomUUID().toString());
mv.addObject("user", user);
}
mv.addObject("users", userService.getAllUser());
return mv;
}
#RequestMapping(value="/delete", method=RequestMethod.POST)
public ModelAndView delete(#ModelAttribute(value="user") User user,BindingResult result){
validator.validate(user, result);
ModelAndView mv = new ModelAndView("registration");
if(!result.hasErrors()){
userService.deleteUser(user.getId());
user = new User();
user.setId(UUID.randomUUID().toString());
mv.addObject("user", user);
}
mv.addObject("users", userService.getAllUser());
return mv;
}
}
persistance is
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.raistudies.persistence.UserService">
<resultMap id="result" type="user">
<result property="id" column="id"/>
<result property="name" column="name"/>
<result property="studentClass" column="class"/>
<result property="roll" column="roll"/>
<!-- <result property="sex" column="sex"/>-->
</resultMap>
<select id="getAllUser" resultMap="result">
SELECT id,name,class,roll
FROM user;
</select>
<insert id="saveUser" parameterType="user">
INSERT INTO user (id,name,standard,age,sex)
VALUE (#{id},#{name},#{standard},#{age})
</insert>
<update id="updateUser" parameterType="user">
UPDATE user
SET
name = #{name},
standard = #{standard},
age = #{age},
sex = #{sex}
where id = #{id}
</update>
<delete id="deleteUser" parameterType="int">
DELETE FROM user
WHERE id = #{id}
</delete>
</mapper>
I have to do create delete update add operation but it is going to be error just like above while running my project......please help me
after changing the jsp code as per the variable that the java bean class(class containing geter or setter method) has.Then it will solve the problem.
*especially what I mean is you have to change the path in jsp <tr><td>Class : </td><td><form:input path="standard" /></td></tr>*as per the bean variable
previous jsp file (at error time)
<!DOCTYPE HTML PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<%# page session="true" %>
<%# taglib uri="http://www.springframework.org/tags/form" prefix="form"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Hello World with Spring 3 MVC</title>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1251">
<script type="text/javascript" src='<c:url value="/resources/common.js"/>'></script>
<script type="text/javascript" src='<c:url value="/resources/registration.js"/>'></script>
<script type="text/javascript">
var projectUrl = '<c:url value="/"/>';
if(projectUrl.indexOf(";", 0) != -1){
projectUrl = projectUrl.substring(0, projectUrl.indexOf(";", 0));
}
</script>
</head>
<body>
<fieldset>
<legend>Registration Form</legend>
<center>
<form:form commandName="user" action="/SpringMVCMyBatisCRUDExample/app/registration/add" name="userForm">
<form:hidden path="id"/>
<table>
<tr><td colspan="2" align="left"><form:errors path="*" cssStyle="color : red;"/></td></tr>
<tr><td>Name : </td><td><form:input path="name" /></td></tr>
<tr><td>Class : </td><td><form:input path="standard" /></td></tr>
<tr><td>RollNo: </td><td><form:input path="roll" /></td></tr>
<tr><td colspan="2"><input type="submit" value="Save Changes"/>
<input type="reset" name="newUser" value="New User" onclick="setAddForm();" disabled="disabled"/>
<input type="submit" name="deleteUser" value="Delete User" onclick="setDeleteForm();" disabled="disabled"/></td></tr>
</table>
</form:form>
</center>
</fieldset>
<c:if test="${!empty users}">
<br />
<center>
<table width="90%">
<tr style="background-color: gray;">
<th>Name</th>
<th>Class</th>
<th>RollNo</th>
</tr>
<c:forEach items="${users}" var="user">
<tr style="background-color: silver;" id="${user.id}" onclick="setUpdateForm('${user.id}');">
<td><c:out value="${user.name}"/></td>
<td><c:out value="${user.studentClass}"/></td>
<td><c:out value="${user.roll}"/></td>
</tr>
</c:forEach>
</table>
</center>
<br />
</c:if>
</body>
my java bean class
package com.raistudies.domain;
import java.io.Serializable;
public class User implements Serializable{
private static final long serialVersionUID = 3647233284813657927L;
private String id;
private String name = null;
private String studentClass = null;
private String roll;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getStudentClass() {
return studentClass;
}
public void setStudentClass(String studentClass) {
this.studentClass = studentClass;
}
public String getRoll() {
return roll;
}
public void setRoll(String roll) {
this.roll = roll;
}
#Override
public String toString() {
return "User [name=" + name + ", class="+ studentClass+ ", roll=" + roll + "]";
}
}
previously I had standard variable in java bean class(model class) but I have to change it to studentClass so not to be error we must change the jsp path that is
<tr><td>Class : </td><td><form:input path="standard" /></td></tr>.......
to
<tr><td>Class : </td><td><form:input path="studentClass" /></td></tr>

How to get data from the database?

I am having problem with getting data from the database (JavaDB).
Exactly, I think the error is in the UserBean class in the method GetAllUsersFromTable.
It is maybe bc I get entities incorrectly from the database. I have tried to write method
GetAllUsersFromTable in few different ways but it doesn't work well.
My project works well until I don't try to get the data from the database. index page is displayed correctly, usersForm also display correctly and when I click submit button it display error. On the page were the error is displayed I should see table with all users.
I use the Glassfish 4.0 and JavaDB is build in. I don't use any IDE's like Eclipse or Netbeans. My project is managed by Maven.I use also JSF CDI ManagedBeans and JPA.
Please ask me any question. I would really love to solve this issue.
I get this error:
javax.faces.el.EvaluationException: java.lang.NullPointerException
at
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke
(MethodBindingMethodExpressionAdapter.java:101)
at com.sun.faces.application.ActionListenerImpl.processAction(ActionListenerImpl.java:102)
at javax.faces.component.UICommand.broadcast(UICommand.java:315)
at javax.faces.component.UIViewRoot.broadcastEvents(UIViewRoot.java:790)
at javax.faces.component.UIViewRoot.processApplication(UIViewRoot.java:1282)
at com.sun.faces.lifecycle.InvokeApplicationPhase.execute(InvokeApplicationPhase.java:81)
at com.sun.faces.lifecycle.Phase.doPhase(Phase.java:101)
at com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:198)
at javax.faces.webapp.FacesServlet.service(FacesServlet.java:646)
at org.apache.catalina.core.StandardWrapper.service(StandardWrapper.java:1682)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:318)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:160)
at org.apache.catalina.core.StandardPipeline.doInvoke(StandardPipeline.java:734)
at org.apache.catalina.core.StandardPipeline.invoke(StandardPipeline.java:673)
at com.sun.enterprise.web.WebPipeline.invoke(WebPipeline.java:99)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:174)
at org.apache.catalina.connector.CoyoteAdapter.doService(CoyoteAdapter.java:357)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:260)
at com.sun.enterprise.v3.services.impl.ContainerMapper.service(ContainerMapper.java:188)
at org.glassfish.grizzly.http.server.HttpHandler.runService(HttpHandler.java:191)
at org.glassfish.grizzly.http.server.HttpHandler.doHandle(HttpHandler.java:168)
at org.glassfish.grizzly.http.server.HttpServerFilter.handleRead(HttpServerFilter.java:189)
at org.glassfish.grizzly.filterchain.ExecutorResolver$9.execute(ExecutorResolver.java:119)
at
org.glassfish.grizzly.filterchain.DefaultFilterChain.executeFilter(DefaultFilterChain.java:288)
at
org.glassfish.grizzly.filterchain.DefaultFilterChain.executeChainPart(DefaultFilterChain.java:206)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.execute(DefaultFilterChain.java:136)
at org.glassfish.grizzly.filterchain.DefaultFilterChain.process(DefaultFilterChain.java:114)
at org.glassfish.grizzly.ProcessorExecutor.execute(ProcessorExecutor.java:77)
at org.glassfish.grizzly.nio.transport.TCPNIOTransport.fireIOEvent(TCPNIOTransport.java:838)
at org.glassfish.grizzly.strategies.AbstractIOStrategy.fireIOEvent(AbstractIOStrategy.java:113)
at
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.run0(WorkerThreadIOStrategy.java:115)
at
org.glassfish.grizzly.strategies.WorkerThreadIOStrategy.access$100(WorkerThreadIOStrategy.java:55)
at org.glassfish.grizzly.strategies.WorkerThreadIOStrategy$WorkerThreadRunnable.
run(WorkerThreadIOStrategy.java:135)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.
doWork(AbstractThreadPool.java:564)
at org.glassfish.grizzly.threadpool.AbstractThreadPool$Worker.run(AbstractThreadPool.java:544)
at java.lang.Thread.run(Thread.java:744)
Caused by: java.lang.NullPointerException
at com.test.UserBean.getAllUsersFromTable(UserBean.java:119)
at com.test.UserBean$Proxy$_$$_WeldClientProxy.getAllUsersFromTable(Unknown Source)
at com.test.AllUsersBean.add(AllUsersBean.java:43)
at com.test.AllUsersBean$Proxy$_$$_WeldClientProxy.add(Unknown Source)
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 javax.el.ELUtil.invokeMethod(ELUtil.java:326)
at javax.el.BeanELResolver.invoke(BeanELResolver.java:536)
at javax.el.CompositeELResolver.invoke(CompositeELResolver.java:256)
at com.sun.el.parser.AstValue.invoke(AstValue.java:269)
at com.sun.el.MethodExpressionImpl.invoke(MethodExpressionImpl.java:304)
at org.jboss.weld.util.el.ForwardingMethodExpression.invoke(ForwardingMethodExpression.java:40)
at org.jboss.weld.el.WeldMethodExpression.invoke(WeldMethodExpression.java:50)
at com.sun.faces.facelets.el.TagMethodExpression.invoke(TagMethodExpression.java:105)
at
javax.faces.component.MethodBindingMethodExpressionAdapter.invoke
(MethodBindingMethodExpressionAdapter.java:87)
... 35 more
Line 119 in the UserBean.java file is
user.setId(v.getId());
package com.test;
/*Importing required java libraries */
import java.io.Serializable;
import javax.inject.Named;
import javax.inject.Inject;
import javax.enterprise.context.ApplicationScoped;
import java.util.ArrayList;
import java.util.List;
#Named("appBean")
#ApplicationScoped
public class AllUserssBean implements Serializable {
private List<UserBean> users;
private int id;
#Inject
private UserBean subBean;
public AllUsersBean(){
users = new ArrayList<UserBean>();
id = 0;
}
public String add() throws Exception {
subBean.addUserToTable();
++id;
users.add(subBean.getAllUsersFromTable(id));
subBean.reset();
return "submit";
}
/*Get total number of users */
public int getTotal(){ return users.size(); }
public List<UserBean> getUsers() { return users; }
public void setUsers(List<UserBean> users) { this.users = users; }
}
package com.test;
/*Importing required java libraries */
import java.io.Serializable;
import javax.inject.Named;
import javax.enterprise.context.SessionScoped;
import java.sql.*;
import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.PersistenceUnit;
import javax.transaction.UserTransaction;
import javax.transaction.RollbackException;
import javax.persistence.*;
import java.util.List;
import java.util.*;
#Named("subBean")
#SessionScoped
public class UserBean implements Serializable{
#PersistenceUnit(unitName="testMe")
private EntityManagerFactory emf;
#Resource
private UserTransaction transaction;
private int id;
private String fname;
private String lname;
public UserBean() {
this.fname = "";
this.lname = "";
}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getFname() { return fname; }
public void setFname(String fname) { this.fname = fname; }
public String getLname() { return lname; }
public void setLname(String lname) { this.lname = lname; }
public UserTransaction getTransaction() { return transaction; }
public void setTransaction(UserTransaction transaction) { this.transaction = transaction; }
public void addUserToTable() throws Exception
{
EntityManager manager = emf.createEntityManager();
boolean commit;
try{
transaction.begin();
manager.joinTransaction();
commit = false;
try {
User v = null;
v.setFname(fname);
v.setLname(lname);
manager.persist(v);
transaction.commit();
commit = true;
}finally {
if(commit==false){
transaction.rollback();
}
}
} catch(Exception e) {
e.printStackTrace();
}finally {
manager.close();
}
}
public UserBean getAllUsersFromTable(int id) {
EntityManager manager = emf.createEntityManager();
User v = null;
UserBean user = new UserBean();
try {
v = manager.find(User.class, id);
user.setId(v.getId());
user.setFname(v.getFname());
user.setLname(v.getLname());
}finally {
manager.close();
}
return user;
}
/*
public List getAllUsersFromTable() throws javax.transaction.SystemException,
javax.transaction.NotSupportedException {
EntityManager manager = emf.createEntityManager();
User v = null;
List<User> results;
try {
TypedQuery<User> query =
manager.createQuery("SELECT * FROM User", User.class);
results = query.getResultList();
}finally {
manager.close();
}
return results;
} */
/*reset method is used to set all the parameters to null and
to 0. This method is called after user was added to the
list of users */
public void reset(){
setFname("");
setLname("");
}
}
package com.test;
/*Importing required java libraries */
import java.io.Serializable;
import javax.persistence.EntityManagerFactory;
import javax.persistence.Persistence;
import javax.persistence.EntityManager;
import javax.persistence.Entity;
import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
#Entity
public class User implements Serializable{
#Id
#GeneratedValue
private int id;
private String fname;
private String lname;
public User() {}
public int getId() { return id; }
public void setId(int id) { this.id = id; }
public String getFname() { return fname; }
public void setFname(String fname) { this.fname = fname; }
public String getLname() { return lname; }
public void setLname(String lname) { this.lname = lname;}
}
index.xhtml
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head><title></title></h:head>
<h:body>
<div style="text-align:center">
<h1>Hello</h1>
<p><h:link value="User Form" outcome="userForm"/></p>
<p><h:link value="All users List" outcome="allUsersList"/></p>
</div>
</h:body>
</html>
userForm.xhtml
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<h:outputStylesheet library="css" name="template.css"/>
<title>User Form page</title>
</h:head>
<h:body>
<h:form id="submissionForm">
<table border="0">
<tr>
<td><h:outputLabel for="fname" value="First name:"></h:outputLabel></td>
<td><h:inputText id="firstName" value="#{subBean.fname}" maxlength="30"
requiredMessage="Please enter first name!" validatorMessage="First
name can include only letters. You can't live it empty!" >
<f:validateRegex pattern="[a-zA-Z]{1,30}"></f:validateRegex>
</h:inputText></td>
<td><h:message for="firstName" style="color:red;"></h:message></td>
</tr>
<tr>
<td><h:outputLabel for="lname" value="Last name:"></h:outputLabel></td>
<td><h:inputText id="lastName" value="#{subBean.lname}" maxlength="30"
requiredMessage="Please enter last name!" validatorMessage="Last
name can include only letters. You can't live it empty!" >
<f:validateRegex pattern="[a-zA-Z]{1,60}"></f:validateRegex>
</h:inputText></td>
<td><h:message for="lastName" style="color:red;"></h:message></td>
</tr>
<tr>
<td colspan="3">
<h:commandButton id="submit" value="Submit" action="#{appBean.add()}"
style="float:right;margin-right:10px;"/>
</td>
</tr>
</table>
</h:form>
</h:body>
</html>
allUsersForm.xhtml
<!DOCTYPE html
PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xml:lang="en" lang="en"
xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:ui="http://java.sun.com/jsf/facelets">
<h:head>
<title>List of All Users page</title>
</h:head>
<h:body>
<h:form id="AllUsersListForm">
<h2><h:outputText value="The next election date: #{msgs.date}"/></h2><p></p>
<h:dataTable value="#{appBean.users}" var="v">
<h:column>
<f:facet name="header"><h:outputText value="Id"></h:outputText></f:facet>
<h:outputText value="#{v.id}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header"><h:outputText value="First Name"></h:outputText></f:facet>
<h:outputText value="#{v.fname}"></h:outputText>
</h:column>
<h:column>
<f:facet name="header"><h:outputText value="Last Name"></h:outputText></f:facet>
<h:outputText value="#{v.lname}"></h:outputText>
</h:column>
<f:facet name="footer"><h:outputText
value="The total number of users: #{appBean.getTotal()}"></h:outputText>
</f:facet>
</h:dataTable>
<p></p>
<p><h:link value="Home page" outcome="index"/></p>
</h:form>
</h:body>
</html>
persistence.xml (It is placed under main/resources/META-iNF/perssitence.xml)
<?xml version="1.0" encoding="UTF-8"?>
<persistence version="1.0"
xmlns="http://java.sun.com/xml/ns/persistence"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/persistence
http://java.sun.com/xml/ns/persistence/persistence_1_0.xsd">
<persistence-unit name="test1" transaction-type="JTA">
<provider>org.eclipse.persistence.jpa.PersistenceProvider</provider>
<jta-data-source>jdbc/username</jta-data-source>
<exclude-unlisted-classes>false</exclude-unlisted-classes>
<properties>
<property name="javax.persistence.schema-generation.database.action"
value="drop-and-create"/>
<property name="javax.persistence.schema-generation.create-source"
value="metadata"/>
<property name="javax.persistence.schema-generation.drop-source"
value="metadata"/>
<property name="javax.persistence.jdbc.user" value="Us"/>
<property name="javax.persistence.jdbc.password" value="Us"/>
</properties>
</persistence-unit>
</persistence>
When I go to (localhost:4848/common/index.jsf)
I create JDBC Connection Pool and everything is correct. When I Ping I get success response
I also create JDBC Connection Resource and everything is set up correctly
This is what we could use us an example to add data do database
public class AddingDatabase
{
#PersistenceUnit(unitName="test_db”) private EntityManagerFactory emf;
#Resource private UserTransaction utx;
void doDML(MyEntity e) throws SystemException, NotSupportedException,
javax.transaction.RollbackException,HeuristicMixedException,HeuristicRollbackException
{
EntityManager em = emf.createEntityManager();
utx.begin();
em.joinTransaction();
try {
boolean committed = false;
try {
em.persist(e);
utx.commit();
committed = true;
} finally {
if (!committed) utx.rollback();
}
}
finally {
em.close();
}
}
}
This might not be the answer, but I need full formatting.
What are you doing in the following code?
User v = null;
v.setFname(fname);
v.setLname(lname);
manager.persist(v);
How can it possibly not produce NPE?

How to implement validations using annotations in struts2 in action that implements ModelDriven interface?

I am trying to implement validation using annotations, but these validations don't work and the form gets submitted with null values.
I don't know what is missing, how to implement validations using annotations in struts2 in action that implements ModelDriven interface?
This is my struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="default" extends="struts-default">
<action name="saveOrUpdateUser" method="saveOrUpdate1" class="com.vaannila.web.Userqqqq">
<result name="success" type="redirect">listUser</result>
<result name="input">/register.jsp</result>
</action>
<action name="listUser" method="list" class="com.vaannila.web.Userqqqq">
<result name="success">/register.jsp</result>
<result name="input">/register.jsp</result>
</action>
<action name="editUser" method="edit" class="com.vaannila.web.Userqqqq">
<result name="success">/register.jsp</result>
<result name="input">/register.jsp</result>
</action>
<action name="deleteUser" method="delete" class="com.vaannila.web.Userqqqq">
<result name="success" type="redirect">listUser</result>
<result name="input">/register.jsp</result>
</action>
</package>
</struts>
This is my jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Registration Page</title>
<s:head />
<style type="text/css">
#import url(style.css);
</style>
</head>
<body>
<s:actionerror/>
<s:form action="saveOrUpdateUser" validate="true">
<s:push value="user">
<s:hidden name="id" />
<s:textfield name="name" label="User Name" required="true"/>
<s:radio name="gender" label="Gender" list="{'Male','Female'}" />
<s:select name="country" list="{'India','USA','UK'}" headerKey=""
headerValue="Select" label="Select a country" />
<s:textarea name="aboutYou" label="About You" />
<s:checkbox name="mailingList"
label="Would you like to join our mailing list?" />
<s:submit />
</s:push>
</s:form>
<s:if test="userList.size() > 0">
<div class="content">
<table class="userTable" cellpadding="5px">
<tr class="even">
<th>Name</th>
<th>Gender</th>
<th>Country</th>
<th>About You</th>
<th>Mailing List</th>
<th>Edit</th>
<th>Delete</th>
</tr>
<s:iterator value="userList" status="userStatus">
<tr
class="<s:if test="#userStatus.odd == true ">odd</s:if><s:else>even</s:else>">
<td><s:property value="name" /></td>
<td><s:property value="gender" /></td>
<td><s:property value="country" /></td>
<td><s:property value="aboutYou" /></td>
<td><s:property value="mailingList" /></td>
<td><s:url id="editURL" action="editUser">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{editURL}">Edit</s:a></td>
<td><s:url id="deleteURL" action="deleteUser">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a></td>
</tr>
</s:iterator>
</table>
</div>
</s:if>
</body>
</html>
This is my action class
package com.vaannila.web;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.vaannila.dao.UserDAO;
import com.vaannila.domain.User;
public class UserAction extends ActionSupport implements ModelDriven<User> {
private static final long serialVersionUID = -6659925652584240539L;
private User user = new User();
private List<User> userList = new ArrayList<User>();
private UserDAO userDAO = new UserDAO();
#Override
public User getModel() {
return user;
}
/**
* To save or update user.
* #return String
*/
public String saveOrUpdate()
{
System.out.println(user.getName());
userDAO.saveOrUpdateUser(user);
return SUCCESS;
}
/**
* To list all users.
* #return String
*/
public String list()
{
userList = userDAO.listUser();
return SUCCESS;
}
/**
* To delete a user.
* #return String
*/
public String delete()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
userDAO.deleteUser(Long.parseLong(request.getParameter("id")));
return SUCCESS;
}
/**
* To list a single user by Id.
* #return String
*/
public String edit()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
user = userDAO.listUserById(Long.parseLong(request.getParameter("id")));
return SUCCESS;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public List<User> getUserList() {
return userList;
}
public void setUserList(List<User> userList) {
this.userList = userList;
}
}
This is my BEAN
package com.vaannila.domain;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
import com.opensymphony.xwork2.validator.annotations.RequiredFieldValidator;
import com.opensymphony.xwork2.validator.annotations.ValidatorType;
#Entity
#Table(name="USER1")
public class User {
private Long id;
private String name;
private String gender;
private String country;
private String aboutYou;
private Boolean mailingList;
#Id
#GeneratedValue
#Column(name="USER_ID")
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
#RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "name", message = "User Name field is empty.")
#Column(name="USER_NAME")
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
#RequiredFieldValidator(type = ValidatorType.SIMPLE, fieldName = "gender", message = "gender field is empty.")
#Column(name="USER_GENDER")
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
#Column(name="USER_COUNTRY")
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
#Column(name="USER_ABOUT_YOU")
public String getAboutYou() {
return aboutYou;
}
public void setAboutYou(String aboutYou) {
this.aboutYou = aboutYou;
}
#Column(name="USER_MAILING_LIST")
public Boolean getMailingList() {
return mailingList;
}
public void setMailingList(Boolean mailingList) {
this.mailingList = mailingList;
}
}
You need to add #VisitorFieldValidator annotation to user getter inside your action class.
#VisitorFieldValidator(appendPrefix = false)
public User getUser() {
return user;
}
Note that you need to set appendPrefix to false if your are using field names without user. prefix in JSP.
Also, you are probably want #RequiredStringValidator not #RequiredFieldValidator inside your bean.
#RequiredStringValidator(message = "User Name field is empty.")
#Column(name="USER_NAME")
public String getName() {
return name;
}

Resources