CRUD using spring and mybatis - spring

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>

Related

"Neither BindingResult nor plain target object for bean name 'command' available as request attribute"

I am getting an exception while creating a form using spring forms tag library
"Neither BindingResult nor plain target object for bean name 'command' available as request attribute"
The jsp page is index.jsp
<%# include file="views/static_include.jsp" %>
<%# 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>Login to AVA Corp</title>
</head>
<body>
<form:form method="POST" commandName="user" action="login.jsp">
<table>
<tbody><tr>
<td><form:label path="firstName">Name:</form:label></td>
<td><form:input path="firstName"></form:input></td>
</tr>
<tr>
<td><form:label path="age">Age:</form:label></td>
<td><form:input path="age"></form:input></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Submit">
</td>
<td></td>
<td></td>
</tr>
</tbody></table>
</form:form>
</body>
</html>
The bean class is:
import java.io.Serializable;
public class Person implements Serializable {
private static final long serialVersionUID = 1949001721422434327L;
private String firstName;
private Integer age;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
}
The controller class is
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView initForm(Model model) {
return new ModelAndView("index", "user", new Employee());
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(#ModelAttribute("user") Employee employee, BindingResult result, SessionStatus status){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user", employee);
return "UserFormSuccess";
}
}
I found that the issue was with the controller method with method type = "get". The value of the request method needs to be the URL mapping of the page on which the form resides e.g. index.jsp in our case so the controller class will be
#Controller
public class LoginController {
#RequestMapping(value = "/login", method = RequestMethod.GET)
public ModelAndView initForm(Model model) {
return new ModelAndView("index", "user", new Employee());
}
#RequestMapping(value = "/login", method = RequestMethod.GET)
public String login(#ModelAttribute("user") Employee employee, BindingResult result, SessionStatus status){
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("user", employee);
return "UserFormSuccess";
}
}

Binding form parameters from JSP to spring controller

I know this is a question which has been asked before. I did look at those questions but I was still not able to resolve my problem and thus writing in on stackoverflow. I am trying to bind the form parameters from my form addArticles.jsp to the controller. On the controller when I do a system.out.println I only get the categoryId and do not get the categoryName. I am not sure what I am doing is incorrect and pretty amused.
addArticles.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"%>
<%#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>Add Article</title>
</head>
<body>
<center>
<h2>Create New Article</h2>
<form:form action="/one2one/articles/save.do" method="POST" modelAttribute="command">
<table>
<tr>
<td><form:label path="id">Article ID</form:label></td>
<td><form:input path="id" value="${article.id}"></form:input></td>
</tr>
<tr>
<td><form:label path="title">Article Title</form:label></td>
<td><form:input path="title" value="${article.title}"></form:input></td>
</tr>
<tr>
<td><form:label path="description">Article Description:</form:label></td>
<td><form:input path="description" value="${article.description}" cssStyle="width: 150px;"></form:input></td>
</tr>
<tr>
<td><form:label path="category.categoryId">Category Type</form:label></td>
<td><form:select path="category.categoryId" cssStyle="width: 150px;">
<option value="-1">Select a type</option>
<c:forEach items="${categories}" var="category">
<option <c:if test="${category.categoryName eq article.category.categoryName}">selected="selected"</c:if>
value="${category.categoryId}">${category.categoryName}</option>
</c:forEach>
</form:select>
</td>
</tr>
<tr>
<td><form:label path="keywords">Article Keywords:</form:label></td>
<td><form:input path="keywords" value="${article.keywords}"></form:input></td>
</tr>
<tr>
<td><form:label path="content">Article Content:</form:label></td>
<td><form:input path="content" value="${article.content}"></form:input></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="SAVE"/></td>
</tr>
</table>
</form:form>
</center>
</body>
</html>
ArticlesController.java
package com.java.bricks.controller;
import java.util.HashMap;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
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.servlet.ModelAndView;
import com.java.bricks.model.Article;
import com.java.bricks.model.Category;
import com.java.bricks.service.ArticleService;
import com.java.bricks.service.CategoryService;
#Controller("articlesController")
#RequestMapping(value="/articles")
public class ArticlesController {
#Autowired
private ArticleService articleService;
#Autowired
private CategoryService categoryService;
#RequestMapping(value="/list", method=RequestMethod.GET)
public ModelAndView listArticles(#ModelAttribute("command") Article article, BindingResult bindingResult){
Map<String,Object> model = new HashMap<String,Object>();
model.put("articles", articleService.listArticles());
return new ModelAndView("articlesList",model);
}
#RequestMapping(value="/add",method=RequestMethod.GET)
public ModelAndView addArticle(#ModelAttribute("command") Article article, BindingResult bindingResult) {
Map<String,Object> model = new HashMap<String,Object>();
model.put("articles", articleService.listArticles());
model.put("categories", categoryService.listCategories());
return new ModelAndView("addArticle",model);
}
#RequestMapping(value="/save",method=RequestMethod.POST)
public ModelAndView saveArticle(#ModelAttribute("command") Article article, BindingResult bindingResult) {
Map<String,Object> model = new HashMap<String,Object>();
System.out.println("----------------------");
System.out.println(article.getCategory());
System.out.println(article.getCategory().getCategoryName());
System.out.println(article.getCategory().getCategoryId());
articleService.addArticle(article);
model.put("articles",articleService.listArticles());
return new ModelAndView("addArticle",model);
}
}
when I click save the first 4 lines of the SOP statements are
System.out.println(article.getCategory());
output: Category [categoryId=29, categoryName=null]
System.out.println(article.getCategory().getCategoryName());
null
System.out.println(article.getCategory().getCategoryId())
29
I am not sure why the categoryName is not populated in the controller.
Article.java
package com.java.bricks.model;
public class Article {
private Long id;
private String title;
private String description;
private String keywords;
private String content;
private Category category;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String getKeywords() {
return keywords;
}
public void setKeywords(String keywords) {
this.keywords = keywords;
}
public String getContent() {
return content;
}
public void setContent(String content) {
this.content = content;
}
public Category getCategory() {
return category;
}
public void setCategory(Category category) {
this.category = category;
}
}
You aren't going to get the category name in the form's content because the category's name is being used a the label for the option. Only the value gets bound. This is your binding path="category.categoryId". You aren't binding anything to path="category.categoryName" so it's going to be null.
So in your controller you have to get the category by its ID. If you want to do some automatic custom conversion, that is a separate question.
Here's a nice article on entity conversion.

Struts+spring+jooq integration - struts action not invoked

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>

Spring Framework <form:errors/> tag not showing errors

I know there are many similar questions here, but none of them solved my problem.
I'm using Spring 4.0.3 and Hibernate Validator 5.1.0.
The problem occurs when I try to omit the path attribute of the <form:errors/> tag, so:
<form:errors path="contato.nome" /> works
<form:errors path="*" /> works
<form:errors /> doesn't work
I don't know why it happens. Spring javadocs (org.springframework.web.servlet.tags.form.ErrorsTag) says it should work like that:
Field only - set path to the field name (or path)
Object errors only - omit path
All errors - set path to *
Can you help me, please?
The interested code is in the 'edicao.jsp' and in the method 'confirmarEdicao' of the ContatoController.java. Sorry if my english is bad.
ContatoController.java
#Controller
#RequestMapping("/contatos")
public class ContatoController {
#Autowired
private ContatoService contatoService;
#Autowired
private MessageSource messageSource;
#RequestMapping(value = "/confirmarEdicao", method = RequestMethod.POST)
public String confirmarEdicao(#Valid Contato contato, BindingResult bindingResult) {
if(bindingResult.hasErrors()) {
return "contatos/edicao";
}
contatoService.save(contato);
return "redirect:/contatos";
}
#RequestMapping(method = RequestMethod.GET)
public ModelAndView form(HttpServletRequest request) {
String message = messageSource.getMessage("teste", null, new Locale("pt", "BR"));
System.out.println(message);
return new ModelAndView("contatos/listagem")
.addObject("contatos", contatoService.list());
}
#RequestMapping("/remover/{id}")
public String remover(Contato contato) {
contatoService.delete(contato);
return "redirect:/contatos";
}
#RequestMapping("/editar/{id}")
public ModelAndView formEdicao(Contato contato) {
contato = contatoService.find(contato.getId());
return new ModelAndView("contatos/edicao")
.addObject(contato);
}
#RequestMapping(value = "/cadastrar")
public String formCadastro() {
return "contatos/cadastro";
}
#RequestMapping(value = "/confirmarCadastro", method = RequestMethod.POST)
public String confirmarCadastro(#Valid Contato contato, BindingResult bindingResult,
RedirectAttributes redirectAttributes) {
if (bindingResult.hasFieldErrors()) {
return "contatos/cadastro";
}
contatoService.save(contato);
redirectAttributes.addFlashAttribute("mensagem", "Contato cadastrado com sucesso.");
return "redirect:/contatos";
}
#ResponseBody
#RequestMapping(value = "/pesquisar/{nome}", method = RequestMethod.GET,
produces="application/json")
public List<Contato> pesquisar(#PathVariable String nome) {
return contatoService.findByName(nome);
}
}
edicao.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# 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=UTF-8">
<title>Editar contato</title>
</head>
<body>
<c:set var="context">${pageContext.request.contextPath}</c:set>
<script type="text/javascript">var context = "${context}";</script>
<script src="${context}/resources/js/jquery-2.1.0.min.js"></script>
<script src="${context}/resources/js/contatos/edicao.js"></script>
<form:form commandName="contato" action="${context}/contatos/confirmarEdicao" method="post">
<form:errors/>
<table>
<form:hidden path="id"/>
<tr>
<td>Nome:</td>
<td><form:input path="nome" /></td>
</tr>
<tr>
<td>Telefone:</td>
<td><form:input path="telefone"/></td>
</tr>
<tr>
<td><input type="button" value="Voltar" id="btn_voltar"/><input type="submit" value="Salvar"/></td>
</tr>
</table>
</form:form>
</body>
</html>
Contato.java
package com.handson.model;
import javax.validation.constraints.Size;
import org.hibernate.validator.constraints.NotEmpty;
public class Contato {
private Long id;
#Size(min = 3, message = "Nome deve ter no mínimo 3 caracteres")
#NotEmpty(message = "O nome deve ser preenchido")
private String nome;
private String telefone;
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getNome() {
return nome;
}
public void setNome(String nome) {
this.nome = nome;
}
public String getTelefone() {
return telefone;
}
public void setTelefone(String telefone) {
this.telefone = telefone;
}
public Contato withId(Long id) {
setId(id);
return this;
}
public Contato withTelefone(String telefone) {
setTelefone(telefone);
return this;
}
public Contato withNome(String nome) {
setNome(nome);
return this;
}
#Override
public String toString() {
return "Contato [id=" + id + ", nome=" + nome + ", telefone="
+ telefone + "]";
}
}
There are some keywords which should be defined:
path - EL-like path to an object or to a field of an object (e.g. foo, foo.bar or foo.bar.baz)
nested path - current path context stored as nestedPath request attribute (new paths are relative to this path)
object error - error connected with object itself (e.g. path is equal to foo)
field error - error connected with object field (e.g. path is foo.bar)
The tag <form:form commandName="foo"> defines nested path as nestedPath=foo. When you write <form:errors path="bar"> it tries to find errors defined for path foo.bar.
Lets say that you have errors connected with foo (object error), foo.bar and foo.bar.baz (nested field error). What this means:
if you enter <form:errors>, only errors bound to foo path are displayed => 1 message
if you enter <form:errors path="bar">, only errors bound to foo.bar path are displayed => 1 message
if you enter <form:errors path="*">, errors bound to foo and its child paths are displayed => 3 messages
if you enter <form:errors path="bar.*">, only child errors for foo.bar are diplayed => 1 message
if you enter <form:errors path="bar*">, errors bound to foo.bar and its child paths are diplayed => 2 messages
Checking on Errors class JavaDoc might give you additional insight.

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