How to validate file upload in Struts 2 - java

UploadvideoAction.java
private File id;
private String title;
private String url;
private String name="";
private String message="";
private String idContentType;
private String idFileName;
public String getIdContentType() {
return idContentType;
}
public void setIdContentType(String idContentType) {
this.idContentType = idContentType;
}
public String getIdFileName() {
return idFileName;
}
public void setIdFileName(String idFileName) {
this.idFileName = idFileName;
}
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
public String getMessage() {
return message;
}
public void setMessage(String message1) {
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getId() {
return id;
}
public void setId(File id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
struts.xml:
<action name="uploadvideo" class="com.myapp.ysrcptv.UploadvideoAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">video/mp4,video/ogg,video/webm</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>${url}</result>
<result name="login">adminlogin.jsp</result>
<result name="input">${url}</result>
</action>
uploadvideos.jsp:
<s:form cssClass="form" action="uploadvideo" method="post" validate="false" enctype="multipart/form-data">
<s:file cssClass="input" name="id" value="" placeholder="Video"></s:file>
<s:textfield cssClass="input" name="title" value="" placeholder="Video Title"></s:textfield>
<input type="hidden" name="name" value="gellery pic"/>
<input type="hidden" name="url" value="uploadvideos.jsp"/>
<s:submit cssClass="btn" value="Upload"></s:submit>
<div class="formdiv"><s:property value="message"/></div>
</s:form>
UploadvideoAction-validation.xml:
<!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="id">
<field-validator type="requiredstring">
<message>File is required.</message>
</field-validator>
</field>
Problem: Only server side file id validation is not working. Even if I selects a file its also showing validation message File is required. Remaining validations are working perfectly. Here I'm placing some stuff. Before its worked. After restarting my server this validation not working.

You have used wrong validator. "requiredstring" validator is used to validate textfields. You can use "required" validator that validates the field to be not null.
<field name="id">
<field-validator type="required">
<message>File is required.</message>
</field-validator>
</field>

Related

Why do I often get exceptions when uploading files using "multipart/form-data"? [duplicate]

UploadvideoAction.java
private File id;
private String title;
private String url;
private String name="";
private String message="";
private String idContentType;
private String idFileName;
public String getIdContentType() {
return idContentType;
}
public void setIdContentType(String idContentType) {
this.idContentType = idContentType;
}
public String getIdFileName() {
return idFileName;
}
public void setIdFileName(String idFileName) {
this.idFileName = idFileName;
}
public void setServletRequest(HttpServletRequest servletRequest) {
this.servletRequest = servletRequest;
}
public String getMessage() {
return message;
}
public void setMessage(String message1) {
this.message = message;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public File getId() {
return id;
}
public void setId(File id) {
this.id = id;
}
public String getTitle() {
return title;
}
public void setTitle(String title) {
this.title = title;
}
public String getUrl() {
return url;
}
public void setUrl(String url) {
this.url = url;
}
struts.xml:
<action name="uploadvideo" class="com.myapp.ysrcptv.UploadvideoAction">
<interceptor-ref name="fileUpload">
<param name="allowedTypes">video/mp4,video/ogg,video/webm</param>
</interceptor-ref>
<interceptor-ref name="defaultStack"></interceptor-ref>
<result>${url}</result>
<result name="login">adminlogin.jsp</result>
<result name="input">${url}</result>
</action>
uploadvideos.jsp:
<s:form cssClass="form" action="uploadvideo" method="post" validate="false" enctype="multipart/form-data">
<s:file cssClass="input" name="id" value="" placeholder="Video"></s:file>
<s:textfield cssClass="input" name="title" value="" placeholder="Video Title"></s:textfield>
<input type="hidden" name="name" value="gellery pic"/>
<input type="hidden" name="url" value="uploadvideos.jsp"/>
<s:submit cssClass="btn" value="Upload"></s:submit>
<div class="formdiv"><s:property value="message"/></div>
</s:form>
UploadvideoAction-validation.xml:
<!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="id">
<field-validator type="requiredstring">
<message>File is required.</message>
</field-validator>
</field>
Problem: Only server side file id validation is not working. Even if I selects a file its also showing validation message File is required. Remaining validations are working perfectly. Here I'm placing some stuff. Before its worked. After restarting my server this validation not working.
You have used wrong validator. "requiredstring" validator is used to validate textfields. You can use "required" validator that validates the field to be not null.
<field name="id">
<field-validator type="required">
<message>File is required.</message>
</field-validator>
</field>

Custom debugging interceptor with JSP in Struts 2

I'm using Struts 2.
I want to create a custom interceptor debug class to display in interceptor debugging mode browser all attributes field value when user click save button.
ProduitDto:
public class ProduitDto {
private String reference;
private String designation;
private double prix;
private int quantite;
private boolean promo;
public ProduitDto(String reference, String designation, double prix, int quantite, boolean promo) {
this.reference = reference;
this.designation = designation;
this.prix = prix;
this.quantite = quantite;
this.promo = promo;
}
public ProduitDto() {
}
public String getReference() {
return reference;
}
public void setReference(String reference) {
this.reference = reference;
}
public String getDesignation() {
return designation;
}
public void setDesignation(String designation) {
this.designation = designation;
}
public double getPrix() {
return prix;
}
public void setPrix(double prix) {
this.prix = prix;
}
public int getQuantite() {
return quantite;
}
public void setQuantite(int quantite) {
this.quantite = quantite;
}
public boolean isPromo() {
return promo;
}
public void setPromo(boolean promo) {
this.promo = promo;
}
}
ProduitAction:
import com.id.dto.ProduitDto;
import com.id.entites.Produit;
import com.id.service.ICatalogueService;
import com.id.service.SingletonService;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class ProduitAction extends ActionSupport implements ModelDriven<Produit> {
private ProduitDto produitDto = new ProduitDto();
private Produit produit = new Produit();
private List<Produit> produits;
private String ref;
private boolean editMode = false;
private ICatalogueService service = SingletonService.getService();
public String index( ) {
produits = service.listProduit();
return SUCCESS;
}
public String save() {
if (!editMode)
service.ajouterProduit(produit);
else
service.miseAjourProduit(produit);
produits = service.listProduit();
return SUCCESS;
}
public String delete() {
service.supprimerProduit(ref);
produits = service.listProduit();
return SUCCESS;
}
public String edit() {
editMode = true;
produit = service.recupererProduit(ref);
service.miseAjourProduit(produit);
produits = service.listProduit();
return SUCCESS;
}
public Produit getProduit() {
return produit;
}
public String getRef() {
return ref;
}
public void setRef(String ref) {
this.ref = ref;
}
public void setProduit(Produit produit) {
this.produit = produit;
}
public List<Produit> getProduits() {
return produits;
}
public void setProduits(List<Produit> produits) {
this.produits = produits;
}
public ProduitDto getProduitDto() {
return produitDto;
}
public void setProduitDto(ProduitDto produitDto) {
this.produitDto = produitDto;
}
public boolean isEditMode() {
return editMode;
}
public void setEditMode(boolean editMode) {
this.editMode = editMode;
}
#Override
public Produit getModel() {
return produit;
}
}
JSP:
<%#taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Produits</title>
<link rel="stylesheet" type="text/css" href="css/style.css"/>
</head>
<body>
<div>
<s:form action="save" method="post">
<s:textfield label="REF" name="produit.reference"></s:textfield>
<s:textfield label="Designation" name="produit.designation"></s:textfield>
<s:textfield label="Prix" name="produit.prix"></s:textfield>
<s:textfield label="Quantite" name="produit.quantite"></s:textfield>
<s:checkbox label="Promo" name="produit.promo"></s:checkbox>
<!-- <s:textfield name="editMode"></s:textfield> permet de voir une valeur du model -->
<s:hidden name="editMode"></s:hidden>
<s:submit value="Save"></s:submit>
</s:form>
</div>
<div>
<table class="table1">
<tr>
<th>REF</th>
<th>DES</th>
<th>PRIX</th>
<th>QUANTITE</th>
<th>PROMO</th>
</tr>
<s:iterator value="produits">
<tr>
<td><s:property value="reference"/></td>
<td><s:property value="designation"/></td>
<td><s:property value="prix"/></td>
<td><s:property value="quantite"/></td>
<td><s:property value="promo"/></td>
<s:url namespace="/" action="delete" var="lien1">
<s:param name="ref">
<s:property value="reference"/>
</s:param>
</s:url>
<s:url namespace="/" action="edit" var="lien2">
<s:param name="ref">
<s:property value="reference"/>
</s:param>
</s:url>
<td><s:a href="%{lien1}">Suppr</s:a></td>
<td><s:a href="%{lien2}">Edit</s:a></td>
</tr>
</s:iterator>
</table>
</div>
</body>
</html>
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.5//EN"
"http://struts.apache.org/dtds/struts-2.5.dtd">
<struts>
<package name="default" namespace="/" extends="struts-default">
<default-action-ref name="index"></default-action-ref>
<action name="index">
<result>views/index.jsp</result>
</action>
<action name="produits" class="com.id.web.ProduitAction" method="index">
<result name="success">views/Produits.jsp</result>
</action>
<action name="save" class="com.id.web.ProduitAction" method="save">
<result name="success">views/Produits.jsp</result>
<result name="input">views/Produits.jsp</result>
</action>
<action name="delete" class="com.id.web.ProduitAction" method="delete">
<result name="success">views/Produits.jsp</result>
</action>
<action name="edit" class="com.id.web.ProduitAction" method="edit">
<result name="success">views/Produits.jsp</result>
</action>
</package>
</struts>
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="struts_blank" version="2.4"
xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>Struts Blank</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Interceptor product :
public class ProductCustomInterceptor implements Interceptor
{
private static final long serialVersionUID = 1L;
#Override
public String intercept(ActionInvocation invocation) throws Exception
{
System.out.println("ProductCustomInterceptor intercept() is called...");
System.out.println(invocation.getAction().getClass().getName());
return invocation.invoke();
}
}
How can I intercept all filed value of my class product when I click save button in my jsp page by using interceptor class with debugging mode browser?

HIbernate saveorUpdate() inserting new records while updating

I am using struts2 and hibernate Integration by following this link http://www.tutorials4u.net/struts2-tutorial/struts2_crud_example.html and trying to update the records but instead of updating it is inserting new records , I have seen all the hibernate update questions before posting this post but none of them worked for me so Please I am requesting to read my question before marking it as duplicate, as I had tried a lot from the already posted questions and answers...
AddStudentAction.java
public class AddStudentAction extends ActionSupport implements
ModelDriven<Student> {
public AddStudentAction() {
// TODO Auto-generated constructor stub
}
Student student = new Student();
private String firstName;
private int id;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getFirstName() {
return firstName;
}
public void setFirstNameSearch(String firstName) {
this.firstName = firstName;
}
List<Student> students = new ArrayList<Student>();
List<Student> studentFirstNames = new ArrayList<Student>();
public List<Student> getStudentFirstNames() {
return studentFirstNames;
}
public void setStudentFirstNames(List<Student> studentFirstNames) {
this.studentFirstNames = studentFirstNames;
}
StudentDAO dao = new StudentDAO();
public Student getStudent() {
return student;
}
public void setStudent(Student student) {
this.student = student;
}
public List<Student> getStudents() {
return students;
}
public void setStudents(List<Student> students) {
this.students = students;
}
public StudentDAO getDao() {
return dao;
}
public void setDao(StudentDAO dao) {
this.dao = dao;
}
#Override
public Student getModel() {
// TODO Auto-generated method stub
return student;
}
#Override
public String execute() {
// TODO Auto-generated method stub
dao.addStudent(student);
String f = student.getFirstName();
String l = student.getLastName();
int m = student.getMarks();
System.out.println(f + l + m + "Inside execute method");
return "success";
}
public String updateStudent() {
dao.addStudent(student);
return "success";
}
public String listStudents() {
students = dao.getStudents();
return "success";
}
public String editStudent() {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(ServletActionContext.HTTP_REQUEST);
student = dao.listStudentById(Integer.parseInt((request
.getParameter("id"))));
student.setId(Integer.parseInt((request.getParameter("id"))));
System.out.println(request.getParameter("id") + "id in editStudent");
dao.updateStudent(student);
return SUCCESS;
}
StudentDAO.java
public class StudentDAO {
#SessionTarget
Session session;
#TransactionTarget
Transaction transaction;
public void addStudent(Student student) {
try {
session.saveOrUpdate(student);
} catch (Exception e) {
e.printStackTrace();
}
}
public void updateStudent(Student student) {
try {
session.saveOrUpdate(student);
session.flush();
} catch (Exception e) {
e.printStackTrace();
}
}
public Student listStudentById(int Id) {
Student student = null;
try {
student = (Student) session.get(Student.class, Id);
} catch (Exception e) {
}
return student;
}
}
Student.java
package com.struts2hibernatepagination.hibernate;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name = "student")
public class Student {
#Id
#GeneratedValue
#Column(name = "id")
private int id;
#Column(name = "last_name")
private String lastName;
#Column(name = "first_name")
private String firstName;
private int marks;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public int getMarks() {
return marks;
}
public void setMarks(int marks) {
this.marks = marks;
}
}
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<package name="default" extends="hibernate-default">
<action name="addStudent" method="execute"
class="com.struts2hibernatepagination.action.AddStudentAction">
<interceptor-ref name="defaultStackHibernateStrutsValidation">
<param name="validation.excludeMethods">listStudents</param>
<param name="validation.excludeMethods">fetchStudentList</param>
</interceptor-ref>
<result name="success" type="redirect">
listStudents
</result>
<result name="input">/student.jsp</result>
</action>
<action name="editStudent"
class="com.struts2hibernatepagination.action.AddStudentAction"
method="editStudent">
<interceptor-ref name="basicStackHibernate" />
<result name="success">/student.jsp</result>
</action>
</package>
hibernate.cfg.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE hibernate-configuration PUBLIC
"-//Hibernate/Hibernate Configuration DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-configuration-3.0.dtd">
<hibernate-configuration>
<session-factory>
<property name="hibernate.connection.driver_class">com.mysql.jdbc.Driver</property>
<property name="hibernate.connection.password">admin12345</property>
<property name="hibernate.connection.url">jdbc:mysql://192.168.1.3:3306/nupur</property>
<property name="hibernate.connection.username">root</property>
<property name="hibernate.dialect">org.hibernate.dialect.MySQLDialect</property>
<property name="show_sql">true</property>
<property name="hibernate.hbm2ddl.auto">update</property>
<mapping class="com.struts2hibernatepagination.hibernate.Student" />
</session-factory>
</hibernate-configuration>
student.jsp
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Hello World</title>
<s:head />
</head>
<body>
Search
<s:form action="addStudent">
<s:actionerror />
<s:textfield name="firstName" label="First Name" />
<s:textfield name="lastName" label="Last Name" />
<s:textfield name="marks" label="Marks" />
<s:submit value="Save" />
<hr />
<table border="2">
<tr bgcolor="cyan">
<th><u>First Name</u></th>
<th><u>Last Name</u></th>
<th><u>Marks</u></th>
<th><u>Edit</u></th>
<th><u>Delete</u></th>
</tr>
<s:iterator value="students">
<tr>
<td><s:property value="firstName" /></td>
<td><s:property value="lastName" /></td>
<td><s:property value="marks" /></td>
<td><s:url id="editURL" action="editStudent">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{editURL}">Edit</s:a></td>
<td><s:url id="deleteURL" action="deleteStudent">
<s:param name="id" value="%{id}"></s:param>
</s:url> <s:a href="%{deleteURL}">Delete</s:a></td>
</tr>
</s:iterator>
</table>
</s:form>
<s:form action="fetchStudentList">
<s:submit value="Show"></s:submit>
</s:form>
</body>
</html>
Please help Me... As I tried all ways whether it is of using session.flush() or deleting #GeneratedValue annotation
Id not coming in addStudent()
public String editStudent() {
HttpServletRequest request = (HttpServletRequest) ActionContext
.getContext().get(ServletActionContext.HTTP_REQUEST);
dao.listStudentById(Integer.parseInt((request.getParameter("id")))); return SUCCESS;
} //AddStudetnAction class method
public void addStudent(Student student) {
try {
System.out.println(student.getId() + "In DAO addStudent");// returning null
session.saveOrUpdate(student);
} catch (Exception e) {
e.printStackTrace();
}
//StudentDAO class method
The addStudent() of StudentDAOis getting null value for id, how can I set the id for addStudent() so that it calls update method instead of save
After spending nearly 2-3 days, I got the solution, I mentioned the <s:hidden> tag in my JSP from where I am passing the id as
<s:hidden name="id" /> , in order to update the Hibernate should get the id and if it fails to do so it will call save method.
if you want to update record you need to have it's id, SaveOrUpdate looks for the id if it is in your table then it updates , if it is not then its add a new record.
I am not sure how you create your Student but if you want to update you need to get the object from the database to have the id ( or if you know the id just set it) then update what you want while the object is in the persistance context and flush.
Here is my edit method.
StudentAction.java
public String edit()
{
HttpServletRequest request = (HttpServletRequest) ActionContext.getContext().get(ServletActionContext.HTTP_REQUEST);
student = studentDAO.listStudentsById(Long.parseLong(request.getParameter("id")));
return SUCCESS;
}
StudentList.jsp
<s:url id="editURL" action="edit">
<s:param name="id" value="%{id}"></s:param>
</s:url>
<s:a href="%{editURL}">Edit</s:a>
The s:form tag doesn't let you to use any parameter in the URL, but you can use hidden input field. s:form tag defaults to POST method.
<s:form action="addStudent">
<s:actionerror />
<s:textfield name="firstName" label="First Name" />
<s:textfield name="lastName" label="Last Name" />
<s:textfield name="marks" label="Marks" />
<s:hidden name="id"/>
<s:submit value="Save" />
...
</s:form>

MobileNo validation Error and datetime validation technique

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 Struts2 I am not getting form value on success.jsp page

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

Categories