I've configured my sturts2 application to use the validation xml for my actions. I also have fieldexpression working.
Would it be possible to call a method from my action in the expression.
eg:
<field name="myField">
<field-validator type="fieldexpression">
<param name="expression"><![CDATA[
#com.test.MyClass#isCaptchaOk(keyString, userResponce)
]]></param>
<message>My credit limit should be MORE than my girlfriend's</message>
</field-validator>
</field>
Here is my actual test code, the simple fieldexpression works, but function call one does not (see the tbox1).
I'm not sure if the #class#method path is ok or not, but is not working
coz, I've added log in the functions but nothing comes up, so i presume the validator can't reach the functions.
Also, Is this possible, ie is it allowed or am i being too ambitious.
Thanks
PS I've corrected the message, I'm not trading my girlfriend ;-)
**** validation.xml
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
<field name="tbox1">
<field-validator type="fieldexpression">
<param name="expression"><![CDATA[#uk.co.nhbc.userRegistration.action.Test2Action#getString()]]></param>
<message>function call message here</message>
</field-validator>
<field-validator type="fieldexpression">
<param name="expression"><![CDATA[#uk.co.nhbc.userRegistration.action.Test2Action#isCaptchaOk(tbox1, user.username)]]></param>
<message>function call message here</message>
</field-validator>
</field>
<field name="tbox2">
<field-validator type="stringlength">
<param name="maxLength">5</param>
<message>length messssage here</message>
</field-validator>
</field>
<field name="user.username">
<field-validator type="fieldexpression">
<param name="expression"><![CDATA[(!(tbox2 == "aa" && user.username.equals("")))]]></param>
<message>tbox2 eq aa and username is empty messssage2 here</message>
</field-validator>
</field>
</validators>
******* java class
package uk.co.nhbc.userRegistration.action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import uk.co.nhbc.common.action.BaseAction;
import uk.co.nhbc.userRegistration.model.Users;
public class Test2Action extends BaseAction {
private String tbox1;
private String tbox2;
private Users user;
private static final Log log = LogFactory.getLog(Test2Action.class);
public String execute() {
return SUCCESS;
}
public String getTbox2() {
return tbox2;
}
public void setTbox2(String tbox2) {
this.tbox2 = tbox2;
}
public String getTbox1() {
return tbox1;
}
public void setTbox1(String tbox1) {
this.tbox1 = tbox1;
}
public Users getUser() {
log.debug("get user called");
return user;
}
public void setUser(Users user) {
log.debug("set user called");
this.user = user;
}
public boolean isCaptchaOk(String challenge, String response) {
//dummy test function
log.debug("captcha function called");
if (response.equals("true"))
return true;
return false;
}
public String getString (){
log.debug("getString function called");
return "hello";
}
}
*********and jsp page
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<%# taglib prefix="sj" uri="/struts-jquery-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=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form name="formtest" action="Test2Action">
<s:actionerror/>
<s:fielderror></s:fielderror>
<s:textfield name="tbox1" label="box1"></s:textfield>
<s:textfield name="tbox2" label="box1"></s:textfield>
<s:textfield name="user.username" label="boxuser"></s:textfield>
<s:submit></s:submit>
</s:form>
</body>
</html>
In order to calling a static method in expression, which must be OGNL, you should enable struts.ognl.allowStaticMethodAccess by adding below constant to struts.xml file:
< constant name="struts.ognl.allowStaticMethodAccess" value="true"/>
See my updated working validator file. for field tbox1 in the fieldexpression I'm referring to the method directly as it is my action, which would be on the VS.
tbox1 and user.username are items on the jsp page (and also exist in the action)
I tried to experiment with a static method, but that didn't work, (no time to investigate now).
Hope this helps
and thanks dave for the input.
***updated validation xml
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.2.dtd">
<validators>
<field name="tbox1">
<field-validator type="fieldexpression">
<param name="expression"><![CDATA[isCaptchaOk(tbox1, user.username)]]></param>
<message>function call message here</message>
</field-validator>
</field>
<field name="tbox2">
<field-validator type="fieldexpression">
<param name="expression"><![CDATA[(#uk.co.nhbc.userRegistration.action.Test2Action#isFuncOk(tbox2))]]></param>
<message>func okk function call message here</message>
</field-validator>
</field>
<field name="user.username">
<field-validator type="fieldexpression">
<param name="expression"><![CDATA[(!(tbox2 == "aa" && user.username.equals("")))]]></param>
<message>tbox2 eq aa and username is empty messssage2 here</message>
</field-validator>
</field>
</validators>
***updated java class
package uk.co.nhbc.userRegistration.action;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import uk.co.nhbc.common.action.BaseAction;
import uk.co.nhbc.userRegistration.model.Users;
public class Test2Action extends BaseAction {
private String tbox1;
private String tbox2;
private Users user;
private static final Log log = LogFactory.getLog(Test2Action.class);
public String execute() {
return SUCCESS;
}
public String getTbox2() {
return tbox2;
}
public void setTbox2(String tbox2) {
this.tbox2 = tbox2;
}
public String getTbox1() {
return tbox1;
}
public void setTbox1(String tbox1) {
this.tbox1 = tbox1;
}
public Users getUser() {
log.debug("get user called");
return user;
}
public void setUser(Users user) {
log.debug("set user called");
this.user = user;
}
public boolean isCaptchaOk(String challenge, String response) {
//dummy test function
log.debug("captcha function called");
log.debug("captcha function called"+challenge+response);
if (response.equals("true"))
return true;
return false;
}
public String getString (){
log.debug("getString function called");
return "hello";
}
public static boolean isFuncOk (String response){
log.debug("isFuncOk function called"+response);
if (response.equals("true"))
return true;
return false;
}
}
Related
This is my controller Login.java
import com.opensymphony.xwork2.ActionSupport;
public class Login extends ActionSupport {
private String userName;
private String password;
public Login() {
}
public String execute() {
return SUCCESS;
}
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;
}
}
This is my Login-Validation.xml
<?xml version="1.0"?>
<!DOCTYPE validators PUBLIC
"-//Apache Struts//XWork Validator 1.0.3//EN"
"http://struts.apache.org/dtds/xwork-validator-1.0.3.dtd">
<validators>
<field name="userName">
<field-validator type="requiredstring">
<message>User Name is required.</message>
</field-validator>
</field>
<field name="password">
<field-validator type="requiredstring">
<message key="password.required" />
</field-validator>
</field>
</validators>
This is my struts.xml
<action name="NewLogin">
<result>login.jsp</result>
</action>
<action name="LoginAction" class="com.strut.Login">
<result name="success">success.jsp</result>
<result name="input">fail.jsp</result>
</action>
I am using struts2-core 2.5.16 as the maven plugin.
The issue is the controller is not considering my validation.xml. It directly passes to the execute method and goes to the success page.
I have placed the controller and validation xml within the same package.
Could someone help me with it? Thanks in advance.
Your file that named "Login-Validation.xml" is error.
Solution:
1. The validation xml file should be named the "Login-validation.xml".
2. The <result name="input" >fail.jsp</result> had been changed to <result name="input" >login.jsp</result>. This will be better and logical.
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>
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>
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;
}
Im trying some ajax call with Struts2 and the JQuery library. This is the code of the jsp :
<s:div id="my_result" >
Nothing
</s:div>
<s:form action="UserManager" theme="simple">
<s:textfield name="nickname" />
<s:password name="password" />
<s:label cssClass="menu_span">
<sj:submit targets="my_result" value="Login" />
</s:label>
</s:form>
this is the code of the bean/action with the xml :
public class UserManager extends ActionSupport {
private String nickname;
private String password;
#Override
public String execute() throws Exception {
String output="i have insered "+this.getNickname()+" and "+this.getPassword();
System.out.println(output);
return output;
}
public String getNickname() { return nickname; }
public void setNickname(String newValue) { nickname=newValue; }
public String getPassword() { return password; }
public void setPassword(String newValue) { password=newValue; }
}
<package name="model" extends="struts-default">
<action name="UserManager" class="model.UserManager">
<result>index.jsp</result>
</action>
</package>
If i return SUCCESS on the UserManager bean, it load on my_result the same calling page. Else, if i return output i get Messages:
No result defined for action model.UserManager and result i have insered aaa and bbb
messagge (with nickname=aaa and password=bbb).
What's happened? How can i return that string? I think it's a struts.xml fault
Cheers
UPDATE
public class UserManager extends ActionSupport {
private String nickname;
private String password;
private String error;
#Override
public String execute() throws Exception {
error="i have insered "+this.getNickname()+" and "+this.getPassword();
return SUCCESS;
}
public String getNickname() { return nickname; }
public void setNickname(String newValue) { nickname=newValue; }
public String getPassword() { return password; }
public void setPassword(String newValue) { password=newValue; }
public String getError() { return error; }
public void setError(String newValue) { error=newValue; }
}
<s:div id="my_result" >
<s:property value="error" />
</s:div>
<s:form action="UserManager" theme="simple">
<s:textfield name="nickname" />
<s:password name="password" />
<s:label cssClass="menu_span">
<sj:submit targets="my_result" value="Login" />
</s:label>
</s:form>
UPDATE 2
<package name="model" extends="json-default">
<action name="UserManager" class="model.UserManager">
<result type="json" />
</action>
</package>
The return value that you return in the execute() method must be one of the mapped as values.
As you have not a result name like this:
<result name="resultName"></result>
It will use the default one: "success". You have to return "success" value in execute() method.
The result value of the execute method is the name of the result mapped. To send a message you have to add a String attribute in your Action (and a getter to obtain it), and in the execute method do something like
this.message = "my message";
Edit: how to get the message with ajax:
If you have set the message in your action in an attribute called "String message" and you have a getter for that attribute (public String getMessage()) you can get this information accesing this property in the object you get in the ajax call. If you do the ajax call for example with jquery you can get it in this way:
$.ajax({
url: '/yourAjaxUrl',
success: function(data) {
var message = data.message;
alert('The message is '+message);
$('#my_result').html(message);
}
});
Edit:
In the struts xml in your package tag you have to define the json type:
<result-types>
<result-type name="json" class="com.googlecode.jsonplugin.JSONResult">
...
</result-types>
and add the json-plugin.jar which can be downloaded here
more info in http://code.google.com/p/jsonplugin/wiki/Documentation