I am creating a struts2 application. I want users to login to their
account. If the record is found, it should go to the success.jsp. If
the account is not found, it should default to to error.jsp. They can
then register. The problem I am having is that whether the records are
in the database or not, I get redirected to my error.jsp.
I would appreciate some help here with some like explanation to go with it
Here are my files:
StudentInfo
package org.comp.dto;
//import
public class StudentInfo implements Serializable{
private int studentId;
private String userName;
private String password;
private String password1;
private String firstName;
private String lastName;
private int age;
private String dateofBirth;
private Calendar dateCreated;
private GregorianCalendar lastLogin;
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getPassword1() {
return password1;
}
public void setPassword1(String password1) {
this.password1 = password1;
}
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 int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
public String getDateofBirth() {
return dateofBirth;
}
public void setDateofBirth(String dateofBirth) {
this.dateofBirth = dateofBirth;
}
public GregorianCalendar getLastLogin() {
return lastLogin;
}
public void setLastLogin(GregorianCalendar lastLogin) {
this.lastLogin = lastLogin;
}
public Calendar getDateCreated() {
return dateCreated;
}
public void setDateCreated(Calendar dateCreated) {
this.dateCreated = dateCreated;
}
}
StudentInfo.hbm.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd" >
<hibernate-mapping>
<class mutable="true" name="org.comp.dto.StudentInfo" table="studentinfo">
<id name="studentId" type="int">
<column name="studentId"/>
<generator class="native"/>
</id>
<property column="userName" name="userName" type="string" not-null="true"/>
<property column="password" name="password" type="string" not-null="true"/>
<property column="firstName" name="firstName" type="string" not-null="true"/>
<property column="lastName" name="lastName" type="string" not-null="true"/>
<property column="age" name="age" type="int" not-null="true"/>
<property column="dateofBirth" name="dateofBirth" type="string" not-null="true"/>
<property column="dateCreated" name="dateCreated" type="calendar" not-null="true"/>
<property column="lastLogin" name="lastLogin" type="timestamp" not-null="true"/>
</class>
</hibernate-mapping>
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="loginpackage" namespace="/" extends="struts-default">
<action name="login" class="org.action.LoginAction" method="login">
<result name="success">success.jsp</result>
<result name="input">login.jsp</result>
<result name="error">error.jsp</result>
</action>
<action name="accountSetUpAction" class="org.action.LoginAction" method="accountSetUp">
<result name="success">success.jsp</result>
</action>
</package>
</struts>
success.jsp
<%# 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>Success page</title>
</head>
<body>
Login successfully! <s:property value="firstName"/>
</body>
</html>
LoginAction class
package org.action;
//import
public class LoginAction extends ActionSupport implements ModelDriven{
private int studentId;
private String userName;
private String password;
private String firstName;
private StudentInfo studentUser = new StudentInfo();
private Session session;
private String message;
PreparedStatement sQry;
ResultSet rs;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public int getStudentId() {
return studentId;
}
public void setStudentId(int studentId) {
this.studentId = studentId;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public StudentInfo getStudentUser() {
return studentUser;
}
public void setStudentUser(StudentInfo studentUser) {
this.studentUser = studentUser;
}
public LoginAction() {
this.session = HibernateUtil.getSessionFactory().getCurrentSession();
}
public void validate() {
if (StringUtils.isEmpty(studentUser.getUserName())){
addFieldError("userName", "Username cannot be blank");
}
if (StringUtils.isEmpty(studentUser.getPassword())){
addFieldError("password", "Password cannot be blank");
}
}
#Override
public String execute() throws Exception {
return SUCCESS;
}
public String login(){
String ret = ERROR;
Connection conn = null;
try {
SessionImplementor impl = (SessionImplementor)session;
conn = impl.getJdbcConnectionAccess().obtainConnection();
org.hibernate.Transaction tx = session.beginTransaction();
String sQry = "SELECT firstName FROM StudentInfo WHERE studentinfo.studentId=? AND studentinfo.userName=? AND studentinfo.password=?";
PreparedStatement q = conn.prepareStatement(sQry);
q.setInt(1, studentId);
q.setString(2, userName);
q.setString(3, password);
rs = q.executeQuery();
while (rs.next()){
rs.getString(2);
ret = SUCCESS;
}
}
catch(Exception ex){
ret = ERROR;
}
finally
{
if (conn !=null){
try {
session.getTransaction().rollback();
conn.close();
}
catch (Exception ex){
}
}
}
return ret;
}
public String accountSetUp() throws Exception{
Transaction tx = null;
try {
tx = session.beginTransaction();
Calendar dateCreated = new GregorianCalendar();
studentUser.setDateCreated(dateCreated);
session.save(studentUser);
session.getTransaction().commit();
return SUCCESS;
}
catch (HibernateException ex){
if(tx != null) tx.rollback();
ex.printStackTrace();
return null;
}
finally
{
session.close();
}
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
#Override
public Object getModel() {
return studentUser;
}
}
The login.jsp
<%# 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>Login Page</title>
</head>
<body>
<s:form action="login" method="get">
<s:textfield label="Please StudentID:" key="studentId"/>
<s:textfield label="Please Enter User Name:" key="userName"/>
<s:password label="Please Enter Password:" key="password"/>
<s:submit/>
</s:form>
</body>
</html>
In your LoginAction class:
String sQry = "SELECT firstName FROM StudentInfo WHERE studentinfo.userName=? AND studentinfo.password=?";
PreparedStatement q = conn.prepareStatement(sQry);
q.setInt(1, studentId);
q.setString(2, userName);
q.setString(3, password);
In the query you have two parameters (userName, password). But you are trying to set three after (studentId, userName, password).
To see the error in console, write ex.printStackTrace(); in your catch blocks (ex is your Exception name).
Related
this My Login.hbm.xml file
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN" "http://www.hibernate.org/dtd/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
<class name="Login1" table="Login1">
<id name="id" column="LID" type="integer">
<generator class="increment"></generator>
</id>
<property name="email" column="EMAIL" type="string"></property>
<property name="password" column="PASS" type="string"></property>
</class>
</hibernate-mapping>
Could not get constructor for
org.hibernate.persister.entity.SingleTableEntityPersister
This is my class file:
public class Login1 implements Serializable {
private int id;
private String email;
private String password;
private String name;
private String amount;
private String date;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getAmount() {
return amount;
}
public void setAmount(String amount) {
this.amount = amount;
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
}
My Login1 has more property but i want add only email and password
please check your constructor,set and get methods of your login class.Check if there are some mis spelling or if they are missing
refer https://forum.hibernate.org/viewtopic.php?p=2453286
I want to display an instance of the company pojo from the database. All I am able to display is the CompanyId the rest of the details are not getting displayed.
viewCompany.jsp
`<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-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 action="ViewCompany">
<s:textfield name="companyId" label="Enter Company ID">
<s:param name="companyId" value="company.companyId"></s:param>
</s:textfield>
<s:submit/>
</s:form>
</body>
</html>
`
I am trying to enter the companyId and the values corresponding to the id should be displayed to the display page.
CompanyBean:
`package com.buhin.POJO;
public class Company {
private int companyId;
public String companyName;
public String contactPerson;
public String mobileNumber;
public String officeNumber;
public String mail;
public String addressLine1;
public String addressLine2;
public String cityName;
public String stateName;
public String zipcode;
//public Address address;
public Company(){}
public Company(int companyId){
this.companyId = companyId;
}
public int getCompanyId() {
return companyId;
}
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
public String getCompanyName() {
return companyName;
}
public String getContactPerson() {
return contactPerson;
}
public String getMobileNumber() {
return mobileNumber;
}
public String getOfficeNumber() {
return officeNumber;
}
public String getMail() {
return mail;
}
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public String getCityName() {
return cityName;
}
public String getStateName() {
return stateName;
}
public String getZipcode() {
return zipcode;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public void setOfficeNumber(String officeNumber) {
this.officeNumber = officeNumber;
}
public void setMail(String mail) {
this.mail = mail;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
#Override
public String toString() {
return "Company [CompanyName=" + getCompanyName()
+ ", ContactPerson=" + getContactPerson()
+ ", MobileNumber=" + getMobileNumber()
+ ", OfficeNumber=" + getOfficeNumber() + ", Mail="
+ getMail() + ", AddressLine1=" + getAddressLine1()
+ ", AddressLine2()=" + getAddressLine2()
+ ", CityName()=" + getCityName() + ", StateName="
+ getStateName() + ", Zipcode=" + getZipcode()
+ "]";
}
}
ViewCompany.java(ActionClass)
`
package com.buhin.Action;
import com.buhin.POJO.*;
import com.buhin.DAO.*;
import com.opensymphony.xwork2.ActionSupport;
public class ViewCompany extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private int companyId;
Company company;
public Company getCompany(){
return company;
}
public void setCompany(Company company){
this.company = company;
}
public int getCompanyId(){
return companyId;
}
public void setCompanyId(int companyId){
this.companyId = companyId;
}
public String execute(){
CompanyDAO cdao = new CompanyDAO();
company = cdao.viewCompany(companyId);
//System.out.println(company.toString());
return "success";
}
}
CompanyDAO:
`package com.buhin.DAO;
import com.buhin.POJO.*;
import com.buhin.hibernate.*;
import com.opensymphony.xwork2.ActionSupport;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
public class CompanyDAO extends ActionSupport{
public CompanyDAO(){
}
/**
*
*/
private static final long serialVersionUID = 1L;
Company vCompany;
public String addCompany(Company company){
SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
Session session = sessionfactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(company);
transaction.commit();
session.close();
return "success";
}
public Company viewCompany(int companyId){
SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
Session session = sessionfactory.openSession();
vCompany = (Company) session.get(com.buhin.POJO.Company.class, companyId);
return vCompany;
}
}
`
companydetails.jsp:
`<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-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:property value="company.companyId"/>
<s:property value="company.companyName"/>
<s:property value="company.contactPerson"/>
<s:property value="company.mobileNumber"/>
<s:property value="company.officeNumber"/>
<s:property value="company.mail"/>
<s:property value="company.addressLine1"/>
<s:property value="company.addressLine2"/>
<s:property value="company.cityName"/>
<s:property value="company.stateName"/>
<s:property value="company.zipcode"/>
</body>
</html>`
`
Struts.xml:
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="com.buhin.POJO" extends="struts-default">
<!-- <action name="AddCompany" class="com.buhin.Action.AddCompany" method="execute">
<result name="success">/success.jsp</result>
</action>
--> <action name="ViewCompany" class="com.buhin.Action.ViewCompany" method="execute">
<result name="success">/companydetails.jsp</result>
</action>
</package>
</struts>
`
First of all I agree with #Aleksandr M, this is a very bizarre structure. But nevertheless, there are a few things wrong with this code.
1) You are returning 'success' result from action methods, so your result should be <result name="success">/companydetails.jsp</result>
2) You are storing Company object in local variable(Company viewCompany). This will not be available in your JSP.
What you should do is make a object variable. Add setter-getters for that variable and use it in your JSP as follows.
<s:property value="viewCompany.zipcode"/>
Hope this helps.
I am generating below page using Struts2. It is generating properly.
My question is how fetch the value from generated page when I click on delete button so I can further process for delete data from database and regenerate page with remaining data?
<%# 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>Insert title here</title>
</head>
<body>
<h3>All Records:</h3>
<table>
<s:form action="upload">
<s:iterator value="list">
<tr>
<td ><s:property value="id"/></td>
<td ><s:property value="name"/></td>
<td><s:property value="password"/></td>
<td><s:property value="email"/></td>
<td><s:property value="gender"/></td>
<td><s:checkbox name="checked" label="isChecked" theme="simple" /></td>
</tr>
</s:iterator>
<s:submit value="delete" name="delete" />
</s:form>
</table>
</body>
</html>
RegisterAction.java
package com.javatpoint;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
public class RegisterAction {
private String name,password,email,gender,country;
int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
ArrayList<User> list=new ArrayList<User>();
public ArrayList<User> getList() {
return list;
}
public void setList(ArrayList<User> list) {
this.list = list;
}
public String execute(){
int i=RegisterDao.save(this);
if(i>0){
Connection con=RegisterDao.con;
try {
PreparedStatement ps=con.prepareStatement("select * from STRUTSUSER");
ResultSet rs=ps.executeQuery();
// rs = ps.getGeneratedKeys();
while(rs.next()){
User user=new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(1));
user.setPassword(rs.getString(2));
user.setEmail(rs.getString(3));
user.setGender(rs.getString(4));
list.add(user);
// System.out.println("yo");
}
con.close();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return "success";
}
return "error";
}
you can try something as below:
public class RegisterAction {
....
public String execute(){
...
}
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
Connection con=RegisterDao.con;
try
{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from STRUTSUSER");
while (rs.next())
{
User user = new User();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setEmailID(rs.getString("emailid"));
users.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return users;
}
public String delete() {
HttpServletRequest request ServletActionContext.getRequest();
int userId = request.getParameter("id");
deleteUser(userId);
return SUCCESS;
}
private void deleteUser(int userId)
{
Connection con=RegisterDao.con;
try
{
PreparedStatement ps = conn.prepareStatement("delete from STRUTSUSER where id=?");
// Parameters start with 1
ps.setInt(1, userId);
ps.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
}
}
JSP page : view.jsp
<s:iterator value="list">
...
</s:iterator>
<s:hidden name="id" value="%{#list.id}" />
<s:submit value="delete" name ="delete" action="deleteUserAction"/>
In Struts.xml
<action name="deleteUserAction" class="example.RegisterAction" method="delete">
<result name="success">view.jsp</result>
</action>
After deleting user, you can call getAllUsers() from action
Hope this Helps
I am working on Struts 2 application where am trying to provide validation for mobile number of 10 digit number .
I am allowing only 10 digit number but even if i am entering 10 digit number it still showing validation error message AND also want to know is there any way buy which we can perform validation for date time picker DOJO tag.
Empaction-validation.xml
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator 1.0.2//EN"
"http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<field name ="firstname">
<field-validator type="requiredstring">
<message key="requiredstring"/>
</field-validator>
</field>
<field name ="email">
<field-validator type = "email">
<message>provide valid Email</message>
</field-validator>
</field>
<field name ="mobileno">
<field-validator type="long">
<param name="min">10</param>
<param name="max">10</param>
<message key="stringlength" />
</field-validator>
</field>
</validators>
registation form is
<%# page language ="java" contentType ="text/html; charset=ISO-8859-1" pageEncoding ="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<%# taglib uri="/struts-dojo-tags" prefix="sx" %>
<html>
<head>
<sx:head/>
<script type="text/javascript" src ="script.js"></script>
</head>
<body>
<div align="center"> <h1 style="color: red"> ENPLOYEE REGISTRATION FORM</h1>
<s:form action="emplogin" method="post" >
<s:textfield name="firstname" label="Employee Firstname"/>
<s:textfield name ="lastname" label ="Last name"/>
<s:textfield name ="id" label="Id"/>
<s:radio name ="gender" list="{'male', 'female'}" label = "Gender"/>
<sx:datetimepicker name="dob" displayFormat="dd-MMM-yyyy" label="DOB"></sx:datetimepicker>
<s:radio name ="maritalstatus" list="{'singale','married'}" label="Marital Status" />
<s:textfield name ="email" label ="Email"/>
<sx:datetimepicker name ="joiningdate" displayFormat="dd-MMM-yyyy" label="Joining Date"></sx:datetimepicker>
<s:textfield name= "designation" label = "Designation"/>
<s:textarea name ="address" label ="Address" />
<s:textfield name = "country" label ="Country" />
<s:textfield name ="state" label = "State" />
<s:textfield name ="city" label ="City"/>
<s:textfield name ="pincode" label ="Pincode"/>
<s:textfield name ="mobileno" label="Mobile No"/>
<s:select name ="groups" list="{'group 1', 'group 2', 'group 3'}" label ="Group" cssStyle="{width:184px"/>
<tr><td> </td></tr>
<tr>
<td> </td>
<s:submit align="center"></s:submit>
</s:form>
</div>
</body>
</html>
in my bean class it is of long type
package model;
public class Empmodel {
private String firstname;
private String lastname;
private String id;
private String gender;
private String dob;
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
private String maritalstatus;
private String email;
private String joiningdate;
private String designation;
private String address;
private String country;
private String state;
private String city;
private int pincode;
private long mobileno;
private String groups;
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 getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getMaritalstatus() {
return maritalstatus;
}
public void setMaritalstatus(String maritalstatus) {
this.maritalstatus = maritalstatus;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getJoiningdate() {
return joiningdate;
}
public void setJoiningdate(String joiningdate) {
this.joiningdate = joiningdate;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public long getMobileno() {
return mobileno;
}
public void setMobileno(long mobileno) {
this.mobileno = mobileno;
}
public String getGroups() {
return groups;
}
public void setGroups(String groups) {
this.groups = groups;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
}
That using the stringlenth validator you can validate the length of the string. Check the stringlength validator.
And using the date validator you can validate the date format. Check the date validator.
If you want to validate datetime picker using validate() you should use the logic that is to parse the value returned by the picker using SimpleDateFormat if you are not using other date time libraries like JODA and don't care about timezone then you should create ThreadLocal parser for datetimes.
EDIT:
validators.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC
"-//OpenSymphony Group//XWork Validator Config 1.0//EN"
"http://www.opensymphony.com/xwork/xwork-validator-config-1.0.dtd">
<validators>
<validator name="longlength" class="jspbean.struts.vaidators.LongLengthFieldValidator"/>
</validators>
LongLengthFieldValidator.java
public class LongLengthFieldValidator extends FieldValidatorSupport {
private boolean doTrim = true;
private int maxLength = -1;
private int minLength = -1;
public void setMaxLength(int maxLength) {
this.maxLength = maxLength;
}
public int getMaxLength() {
return maxLength;
}
public void setMinLength(int minLength) {
this.minLength = minLength;
}
public int getMinLength() {
return minLength;
}
public void setTrim(boolean trim) {
doTrim = trim;
}
public boolean getTrim() {
return doTrim;
}
public void validate(Object object) throws ValidationException {
String fieldName = getFieldName();
String val = getFieldValue(fieldName, object).toString();
if (val == null || val.length() <= 0) {
// use a required validator for these
return;
}
if (doTrim) {
val = val.trim();
if (val.length() <= 0) {
// use a required validator
return;
}
}
if ((minLength > -1) && (val.length() < minLength)) {
addFieldError(fieldName, object);
} else if ((maxLength > -1) && (val.length() > maxLength)) {
addFieldError(fieldName, object);
}
}
}
XXX-validation.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE validators PUBLIC "-//OpenSymphony Group//XWork Validator 1.0.2//EN" "http://www.opensymphony.com/xwork/xwork-validator-1.0.2.dtd">
<validators>
<validator type="longlength">
<param name="fieldName">mobileno</param>
<param name="minLength">10</param>
<param name="maxLength">10</param>
<param name="trim">true</param>
<message>Your mobileno number needs to be 10 characters long</message>
</validator>
</validators>
In my application I am trying to register a user by adding his details to the database and after success fully insert these values. I need to display form input page but on result page I am not getting any output.
My ACTION CLASS IS
package action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import dao.Empdao;
import model.Empmodel;
public class Empaction extends ActionSupport implements ModelDriven<Object>{
private static final long serialVersionUID = 1L;
Empmodel modelobj;
public Empmodel getModelobj() {
return modelobj;
}
public void setModelobj(Empmodel modelobj) {
this.modelobj = modelobj;
}
public String execute() throws Exception{
Empdao empdao = new Empdao();
int queryResult = empdao.registration(modelobj);
if (queryResult==0)
{
addActionError("it is a dublicate entry please enter anothe id");
return ERROR;
}
else{
return SUCCESS;
}
}
#Override
public Object getModel() {
modelobj = new Empmodel();
return null;
}
}
Success.jsp is
<body>
first name : <s:property value="modelobj.firstname"/> <br>
last name :<s:property value="modelobj.lastname" />
<s:property value="modelobj.id" />
<s:property value="modelobj.gender" />
<s:property value="modelobj.dob" />
<s:property value="modelobj.maritalstatus" />
<s:property value="modelobj.email" />
<s:property value="modelobj.joiningdate" />
<s:property value="modelobj.designation" />
<s:property value="modelobj.country" />
<s:property value="modelobj.state" />
<s:property value="modelobj.city" />
<s:property value="modelobj.pincode" />
<s:property value="modelobj.mobileno" />
<s:property value="modelobj.groups" />
</body>
</html>
Empmodel CLASS IS
package model;
public class Empmodel {
private String firstname;
private String lastname;
private String id;
private String gender;
private String dob;
private String maritalstatus;
private String email;
private String joiningdate;
private String designation;
private String address;
private String country;
private String state;
private String city;
private int pincode;
private long mobileno;
private String groups;
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 getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getGender() {
return gender;
}
public void setGender(String gender) {
this.gender = gender;
}
public String getDob() {
return dob;
}
public void setDob(String dob) {
this.dob = dob;
}
public String getMaritalstatus() {
return maritalstatus;
}
public void setMaritalstatus(String maritalstatus) {
this.maritalstatus = maritalstatus;
}
public String getEmail() {
return email;
}
public void setEmail(String email) {
this.email = email;
}
public String getJoiningdate() {
return joiningdate;
}
public void setJoiningdate(String joiningdate) {
this.joiningdate = joiningdate;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
public String getCountry() {
return country;
}
public void setCountry(String country) {
this.country = country;
}
public String getState() {
return state;
}
public void setState(String state) {
this.state = state;
}
public String getCity() {
return city;
}
public void setCity(String city) {
this.city = city;
}
public long getMobileno() {
return mobileno;
}
public void setMobileno(long mobileno) {
this.mobileno = mobileno;
}
public String getGroups() {
return groups;
}
public void setGroups(String groups) {
this.groups = groups;
}
public int getPincode() {
return pincode;
}
public void setPincode(int pincode) {
this.pincode = pincode;
}
}
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>
<constant name="struts.enable.DynamicMethodInvocation" value="true"/>
<constant name="struts.devmode" value="true"/>
<package name="loginmodel" extends ="struts-default">
<action name ="emplogin" class ="action.Empaction">
<result name= "wait">/Registration/wait.jsp</result>
<result name = "input">/Registration/empregistration.jsp</result>
<result name ="success" type="redirect" >/Registration/success.jsp</result>
<result name="error">/Registration/empregistration.jsp</result>
</action>
</package>
empregistration.jsp
<%# page language ="java" contentType ="text/html; charset=ISO-8859-1" pageEncoding ="ISO-8859-1"%>
<%# taglib uri="/struts-tags" prefix="s"%>
<%# taglib uri="/struts-dojo-tags" prefix="sx" %>
<html>
<head>
<sx:head/>
<script type="text/javascript" src ="script.js"></script>
</head>
<body>
<div align="center"> <h1 style="color: red"> ENPLOYEE REGISTRATION FORM</h1>
<s:form action="emplogin" method="post">
<s:textfield name="modelobj.firstname" label="Employee Firstname"/>
<s:textfield name ="modelobj.lastname" label ="Last name"/>
<s:textfield name ="modelobj.id" label="Id"/>
<s:radio name ="modelobj.gender" list="{'male', 'female'}" label = "Gender"/>
<sx:datetimepicker name="dob" displayFormat="dd-MMM-yyyy" label="DOB"></sx:datetimepicker>
<s:radio name ="modelobj.maritalstatus" list="{'singale','married'}" label="Marital Status" />
<s:textfield name ="modelobj.email" label ="Email"/>
<sx:datetimepicker name ="modelobj.joiningdate" displayFormat="dd-MMM-yyyy" label="Joining Date"></sx:datetimepicker>
<s:textfield name= "modelobj.designation" label = "Designation"/>
<s:textarea name ="modelobj.address" label ="Address" />
<s:textfield name = "modelobj.country" label ="Country" />
<s:textfield name ="modelobj.state" label = "State" />
<s:textfield name ="modelobj.city" label ="City"/>
<s:textfield name ="modelobj.pincode" label ="Pincode"/>
<s:textfield name ="modelobj.mobileno" label="Mobile No"/>
<s:select name ="modelobj.groups" list="{'group 1', 'group 2', 'group 3'}" label ="Group" cssStyle="{width:184px"/>
<tr><td> </td></tr>
<tr>
<td> </td>
<s:submit align="center"></s:submit>
</s:form>
</div>
</body>
</html>
You are redirecting the page on success that is wrong because you loose values needed to display results. Use
<result name ="success">/Registration/success.jsp</result>
or simply
<result>/Registration/success.jsp</result>
BTW, you only have getters & setters for firstname and lastname, so the only these properties will display. If you want to display other properties then you should add correcponding methods to fields.
You may read the servlet API javadoc to make clue what may cause result type="redirect".
For further compare the difference between forward and redirect results consider this thread.
If type=redirectAction then you have to mention the Action name without any extensions
if its only redirect then you have to mention including the action name and extension, For your Question it was because of redirect the problem happened.
Even after redirecting to some page and when you come back to the result page , and if you want to retain data then its better you better put in session .
Do not redirect you page remove it and use
<result name ="success">/Registration/success.jsp</result> in you struts.xml file