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>
Related
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>
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?
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>
I am new to struts and was trying to save some values to DB (mysql) from jsp page using struts and hibernate.
But, the application is saving null value every time and auto increment ID is increasing.
My Database structure. :
Table Name | osdetail
-------------------------
Columns | os_name,
| os_version,
| id,
| created,
| notes.
The index.jsp page
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>OS Manager - Struts2 Hibernate Example</title>
</head>
<body>
<h1>OS Manager</h1>
<s:actionerror/>
<s:form action="add" method="post">
<s:textfield name="osdetail.OSname" label="name"/>
<s:textfield name="osdetail.OSversion" label="version"/>
<s:textfield name="osdetail.OSnotes" label="notes"/>
<s:submit value="Add OS Details" align="center"/>
</s:form>
<h2>OS Details</h2>
<table>
<tr>
<th>OS Name</th>
<th>OS Version</th>
<th>OS Notes</th>
</tr>
<s:iterator value="osdetails_list" var="osdetail">
<tr>
<td><s:property value="OSname"/></td>
<td><s:property value="OSversion"/></td>
<td><s:property value="OSnotes"/></td>
</tr>
</s:iterator>
</table>
</body>
</html>
My View : OSAction.java
package net.ajeet.os.view;
import java.util.List;
import net.ajeet.os.controller.OSManager;
import net.ajeet.os.model.OSDetail;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class OSAction extends ActionSupport implements ModelDriven<OSDetail> {
private static final long serialVersionUID = 9149826260758390091L;
private OSDetail osdetail= new OSDetail();
private List<OSDetail> osdetails_list;
private Long id;
private OSManager linkController= new OSManager();
#Override
public OSDetail getModel() {
return osdetail;
}
public OSAction() {
linkController = new OSManager();
}
public String execute() {
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String add() {
System.out.println("this is oS detail get ID"+osdetail.getId());
try {
//linkController.add(getOSDetail());
linkController.add(osdetail);
System.out.println("this is oS detail after add "+getOSDetail());
} catch (Exception e) {
e.printStackTrace();
}
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String delete() {
linkController.delete(getId());
return SUCCESS;
}
public OSDetail getOSDetail() {
return osdetail;
}
public List<OSDetail> getOSDetail_list() {
return osdetails_list;
}
public void setOSDetail(OSDetail osdetail) {
this.osdetail = osdetail;
}
public void setOSDetail_list(List<OSDetail> osdetails_list) {
this.osdetails_list = osdetails_list;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
}
My Model: OSDetail.java
package net.ajeet.os.model;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="osdetail")
public class OSDetail implements Serializable{
private static final long serialVersionUID = -8767337896773261247L;
private Long OSid;
private String OSname;
private String OSversion;
private String OSnotes;
private Date OScreated;
#Id
#GeneratedValue
#Column(name="id")
public Long getId() {
System.out.println("set os name is os id"+OSid);
return OSid;
}
#Column(name="os_name")
public String getOS_name() {
return OSname;
}
#Column(name="os_version")
public String getOS_version() {
return OSversion;
}
#Column(name="notes")
public String getNotes() {
return OSnotes;
}
#Column(name="created")
public Date getCreated() {
return OScreated;
}
public void setId(Long OSid) {
this.OSid = OSid;
}
public void setOS_name(String OSname) {
this.OSname = OSname;
}
public void setOS_version(String OSversion) {
this.OSversion = OSversion;
}
public void setNotes(String OSnotes) {
this.OSnotes = OSnotes;
}
public void setCreated(Date OScreated) {
this.OScreated = OScreated;
}
My Contoller :OSManager.java
import java.util.List;
import org.hibernate.HibernateException;
import org.hibernate.classic.Session;
import net.ajeet.os.model.OSDetail;
import net.ajeet.os.util.HibernateUtil;
public class OSManager extends HibernateUtil {
public OSDetail add(OSDetail osdetail) {
System.out.println("value of the os in OSManager"+osdetail.getId());
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
session.save(osdetail);
session.getTransaction().commit();
return osdetail;
}
public OSDetail delete(Long id) {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
OSDetail osdetail = (OSDetail) session.load(OSDetail.class, id);
if(null != osdetail) {
session.delete(osdetail);
}
session.getTransaction().commit();
return osdetail;
}
#SuppressWarnings("unchecked")
public List<OSDetail> list() {
Session session = HibernateUtil.getSessionFactory().getCurrentSession();
session.beginTransaction();
List<OSDetail> osdetails_list = null;
try {
osdetails_list = (List<OSDetail>)session.createQuery("from OSDetail").list();
} catch (HibernateException e) {
e.printStackTrace();
session.getTransaction().rollback();
}
session.getTransaction().commit();
return osdetails_list;
}
}
The values saved in DB are always null...except the ID..Please help
Changed the Action...updated getter/setter
package net.ajeet.os.view;
import java.util.List;
import net.ajeet.os.controller.OSManager;
import net.ajeet.os.model.OSDetail;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class OSAction extends ActionSupport {
private static final long serialVersionUID = 9149826260758390091L;
public OSDetail osdetail= new OSDetail();
private List<OSDetail> osdetails_list;
public OSDetail getOsdetail() {
return osdetail;
}
public void setOsdetail(OSDetail osdetail) {
this.osdetail = osdetail;
}
private Long id;
private OSManager linkController= new OSManager();
/* #Override
public OSDetail getModel() {
return osdetail;
}*/
public OSAction() {
linkController = new OSManager();
}
public String execute() {
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String add() {
try {
linkController.add(getOsdetail());
//linkController.add(osdetail);
} catch (Exception e) {
e.printStackTrace();
}
this.osdetails_list = linkController.list();
return SUCCESS;
}
public String delete() {
linkController.delete(getid());
return SUCCESS;
}
public List<OSDetail> getOsdetails_list() {
return osdetails_list;
}
public void setOsdetails_list(List<OSDetail> osdetails_list) {
this.osdetails_list = osdetails_list;
}
public Long getid() {
return id;
}
public void setid(Long id) {
this.id = id;
}
}
Corrected OSDetail.java, automatically created getter/setter.
package net.ajeet.os.model;
import java.io.Serializable;
import java.sql.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.Id;
import javax.persistence.Table;
#Entity
#Table(name="osdetail")
public class OSDetail implements Serializable{
private static final long serialVersionUID = -8767337896773261247L;
private Long OSid;
private String OSname;
private String OSversion;
private String OSnotes;
private Date OScreated;
#Id
#GeneratedValue
#Column(name="id")
public Long getOSid() {
return OSid;
}
public void setOSid(Long oSid) {
OSid = oSid;
}
#Column(name="os_name")
public String getOSname() {
return OSname;
}
public void setOSname(String oSname) {
OSname = oSname;
}
#Column(name="os_version")
public String getOSversion() {
return OSversion;
}
public void setOSversion(String oSversion) {
OSversion = oSversion;
System.out.println("value of the os in OSversion in setter"+OSversion);
}
#Column(name="notes")
public String getOSnotes() {
return OSnotes;
}
public void setOSnotes(String oSnotes) {
OSnotes = oSnotes;
}
#Column(name="created")
public Date getOScreated() {
return OScreated;
}
public void setOScreated(Date oScreated) {
OScreated = oScreated;
}
}
Adding struts.xml to
<?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.enable.DynamicMethodInvocation"
value="false" />
<constant name="struts.devMode" value="false" />
<package name="default" extends="struts-default" namespace="/">
<action name="add"
class="net.ajeet.os.view.OSAction" method="add">
<result name="success" type="chain">index</result>
<result name="input" type="chain">index</result>
</action>
<action name="index"
class="net.ajeet.os.view.OSAction">
<result name="success">index.jsp</result>
</action>
</package>
</struts>
And 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>
<!-- Database connection settings -->
<property name="connection.driver_class">
com.mysql.jdbc.Driver
</property>
<property name="connection.url">
jdbc:mysql://localhost:3306/test
</property>
<property name="connection.username">root</property>
<property name="connection.password">Asmita24</property>
<!-- JDBC connection pool (use the built-in) -->
<property name="connection.pool_size">1</property>
<!-- SQL dialect -->
<property name="dialect">
org.hibernate.dialect.MySQLDialect
</property>
<!-- Enable Hibernate's automatic session context management -->
<property name="current_session_context_class">thread</property>
<!-- Disable the second-level cache -->
<property name="cache.provider_class">
org.hibernate.cache.NoCacheProvider
</property>
<!-- Echo all executed SQL to stdout -->
<property name="show_sql">true</property>
<!-- Drop and re-create the database schema on startup -->
<property name="hbm2ddl.auto">update</property>
<mapping class="net.ajeet.os.model.OSDetail" />
</session-factory>
</hibernate-configuration>
Your getter function is wrongly named for the variable osdetail. It should be getOsdetail() instead of getOSDetail(). That is the reason your values from the form are not set and the variable osdetail has blank values. Try changing it. Same goes for the setter method, it should be setOsdetail(). Also, to prevent making such mistake in fututre, you can generate your getter and setter functions automatically from eclipse instead of manually creating it.
I don't see anywhere in your OSAction the code to read the values from the jsp. And that is the reason why I think the values are going in as null in the DB.
I suppose it'll work if you get the details from the jsp and set it to osdetail before calling linkController.add(osdetail);.
I am not too well versed with ActionSupport but I think you can read the values from the jsp using getText() method...
Try adding these lines before linkController.add(osdetail); line...
osdetail.setOS_name(getText("osdetail.OSname"));
osdetail.setOS_version(getText("osdetail.OSversion"));
osdetail.setNotes(getText("osdetail.OSnotes"));
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