Custom debugging interceptor with JSP in Struts 2 - java

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?

Related

Struts2 action always returning success

I'm a beginner in STRUTS2 and I want to test two Actions.
The first Action Product work correctly. When I enter "hello" return success otherwise error.
But the second Action CatererTyp return always success.
Can somebody please explain me why?
Here is Product.java
package com.javatpoint;
import com.opensymphony.xwork2.ActionSupport;
public class Product extends ActionSupport {
private int id;
private String name;
private float price;
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 float getPrice() {
return price;
}
public void setPrice(float price) {
this.price = price;
}
public String execute() {
if(name.equals("hallo")){
return SUCCESS;
}
else{
return ERROR;
}
}
}
CatererType.java
package com.javatpoint;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import com.opensymphony.xwork2.ActionSupport;
public class CatererType extends ActionSupport {
private String description;
public String getDescription() {
return description;
}
public void setDescription(String description) {
this.description = description;
}
public String excute() {
if (description.equals("hello")) {
return ERROR;
} else {
return SUCCESS;
}
}
}
accessdiened.jsp
<%# page contentType="text/html; charset=UTF-8" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>Access Denied</title>
</head>
<body>
You are not authorized to view this page.
</body>
</html>
welcome.jsp
<%# taglib uri="/struts-tags" prefix="s" %>
The Caterer Type: <s:property value="description"/> was inserted <br/>
adminpage.jsp
<%# taglib uri="/struts-tags" prefix="s" %>
<html>
<center>
<s:form action="caterertype">
<s:textfield name="description" label="Caterer Type"></s:textfield>
<s:submit value="save"></s:submit>
</s:form>
</center>
</html>
struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<package name="default" extends="struts-default">
<action name="product" class="com.javatpoint.Product" method="execute">
<result name="success">welcome.jsp</result>
<result name="error">/AccessDenied.jsp</result>
</action>
<action name="caterertype" class="com.javatpoint.CatererType" method="execute">
<result name="success">welcome.jsp</result>
<result name="error">AccessDenied.jsp</result>
</action>
</package>
</struts>

How to validate file upload in Struts 2

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>

How to forward result to another action in Struts2?

I have this action:
package com.test;
import com.opensymphony.xwork2.Action;
public class TestAction implements Action{
private String simpleParam;
public String getSimpleParam() {
return simpleParam;
}
public void setSimpleParam(String simpleParam) {
this.simpleParam = simpleParam;
}
#Override
public String execute() throws Exception {
return SUCCESS;
}
}
When it's executed I want to invoke another action inside struts(e.g. not redirect) and pass to it simpleParam. SecondAction is:
package com.test;
import com.opensymphony.xwork2.Action;
public class HelloAction implements Action {
private String id;
private String result;
public String getId() {
return id;
}
public void setId(String id) {
this.id = id;
}
public String getResult() {
return result;
}
#Override
public String execute() throws Exception {
result = "result" + getId();
return SUCCESS;
}
}
I saw working example when in struts.xml in result simply typed another action name and params and it worked. So I'm trying to do this:
<struts>
<package name="main" extends="struts-default">
<action name="test" class="com.test.TestAction">
<result name="success">hello.action?id=${simpleParam}</result>
</action>
<action name="hello" class="com.test.HelloAction">
<result>/hello.jsp</result>
</action>
</package>
</struts>
Idea totally sees this action but in browser I get 404 status. When I simply invoke hello.action from browser it works. Redirect also works. I also tried chain, but my param wasn't passed and it's not very convinient.
Am I doing it right? And if so what could be the cause of 404 status?
this could be helpful: http://struts.apache.org/docs/action-chaining.html
<struts>
<package name="main" extends="struts-default">
<action name="test" class="com.test.TestAction">
<result name="success" type="chain">hello</result>
</action>
<action name="hello" class="com.test.HelloAction">
<result>/hello.jsp</result>
</action>
</package>
</struts>
to pass a parameter from one action to another you could use the HttpServletRequest
(http://www.mkyong.com/struts2/how-to-get-the-httpservletrequest-in-struts-2):
TestAction.java:
package com.test;
import com.opensymphony.xwork2.Action;
public class TestAction implements Action{
private String simpleParam;
public String getSimpleParam() {
return simpleParam;
}
public void setSimpleParam(String simpleParam) {
this.simpleParam = simpleParam;
}
#Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
request.setAttribute("id", simpleParam);
return SUCCESS;
}
}
HelloAction.java:
package com.test;
import com.opensymphony.xwork2.Action;
public class HelloAction implements Action {
private String id;
private String result;
public String getId() {
return id;
}
public String getResult() {
return result;
}
#Override
public String execute() throws Exception {
HttpServletRequest request = ServletActionContext.getRequest();
id = (String)request.getAttribute("id");
result = "result" + getId();
return SUCCESS;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
<display-name>Struts2 Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
<display-name>Struts2 Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:javaee="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd" id="WebApp_9" version="2.4">
<display-name>Struts2 Application</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.FilterDispatcher
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
View Records all
</body>
</html>
edit.jsp
<%# taglib uri="/struts-tags" prefix="s" %>
<b>id :</b> <s:property value="id"/> <br>
<b>name :</b> <s:property value="name"/> <br>
<b>salary :</b> <s:property value="salary"/> <br>
<s:textfield name="userid" label="phoneno" value="id"/>
UserAction.java
package com.action;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import com.model.User;
import com.userservice.UserService;
public class UserAction {
private int id;
private String name;
private int salary;
private int phoneno;
ArrayList<User> list=new ArrayList<User>();
public ArrayList<User> getList() {
return list;
}
public void setList(ArrayList<User> list) {
this.list = list;
}
public String execute(){
UserService service= new UserService();
list=service.getdetails();
return "success";
}
public String delete() {
System.out.println("----------");
return "success";
}
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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getPhoneno() {
return phoneno;
}
public void setPhoneno(int phoneno) {
this.phoneno = phoneno;
}
}
UserService.java
package com.userservice;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import com.model.User;
public class UserService {
ArrayList<User> list=new ArrayList<User>();
public ArrayList<User> getdetails(){
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
Connection con=DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:xe","oracletest","oracle");
PreparedStatement ps=con.prepareStatement("select * from employee");
ResultSet rs=ps.executeQuery();
while(rs.next()){
User user=new User();
user.setId(rs.getInt(1));
user.setName(rs.getString(2));
user.setSalary(rs.getInt(3));
user.setPhoneno(rs.getInt(4));
list.add(user);
System.out.println(rs.getString(2));
}
con.close();
}catch(Exception e){e.printStackTrace();}
return list;
}
public ArrayList<User> getList() {
return list;
}
public void setList(ArrayList<User> list) {
this.list = list;
}
}
User.java
package com.model;
public class User {
private int id;
private String name;
private int salary;
private int phoneno;
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 int getSalary() {
return salary;
}
public void setSalary(int salary) {
this.salary = salary;
}
public int getPhoneno() {
return phoneno;
}
public void setPhoneno(int phoneno) {
this.phoneno = phoneno;
}
}
welcome.jsp
<%# page contentType="text/html; charset=UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Struts2 Example</title>
</head>
<body>
<table>
<tr>
<th>id</th>
<th>Name</th>
<th>salary</th>
<th>phoneno</th>
</tr>
<s:iterator value="list" var="user">
<tr>
<td><s:property value="id"/> </td>
<td><s:property value="name"/></td>
<td><s:property value="salary"/></td>
<td><s:property value="phoneno"/></td>
<td>edit</td>
<td>edit1</td>
</tr>
</s:iterator>
</table>
</body>
</html>
</html>

insert update delete in Struts 2 but showing NullPointerException

Here I come up with problem with Operation like update,delete and view so now insert is working but other operation like update, delete, view showing error like. Could some one can guide to go right direction? This what I have tried up to now
Error:
HTTP Status 500 - java.lang.NullPointerException
type Exception report
message java.lang.NullPointerException
description The server encountered an internal error that prevented it from fulfilling this request.
exception
javax.servlet.ServletException: java.lang.NullPointerException
org.apache.struts2.dispatcher.Dispatcher.serviceAction(Dispatcher.java:515)
org.apache.struts2.dispatcher.FilterDispatcher.doFilter(FilterDispatcher.java:419)
root cause
java.lang.NullPointerException
Action.Testiue.view(Testiue.java:115)
sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
java.lang.reflect.Method.invoke(Method.java:606)
com.opensymphony.xwork2.DefaultActionInvocation.invokeAction(DefaultActionInvocation.java:404)
com.opensymphony.xwork2.DefaultActionInvocation.invokeActionOnly(DefaultActionInvocation.java:267)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:229)
com.opensymphony.xwork2.interceptor.DefaultWorkflowInterceptor.doIntercept(DefaultWorkflowInterceptor.java:221)
com.opensymphony.xwork2.interceptor.MethodFilterInterceptor.intercept(MethodFilterInterceptor.java:86)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:224)
com.opensymphony.xwork2.DefaultActionInvocation$2.doProfiling(DefaultActionInvocation.java:223)
com.opensymphony.xwork2.util.profiling.UtilTimerStack.profile(UtilTimerStack.java:455)
com.opensymphony.xwork2.DefaultActionInvocation.invoke(DefaultActionInvocation.java:221)
com.opensymphony.xwork2.validator.ValidationInterceptor.doIntercept(ValidationInterceptor.java:150)
org.apache.struts2.interceptor.validation.AnnotationValidationInterceptor.doIntercept(AnnotationValidationInterceptor.java:48)
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>
<include file="struts-default.xml" />
<package name="a" extends="struts-default">
<action name="adduser" class="Action.Testiue" method="add">
<result name="success">/insert.jsp</result>
<result name="success">/ssuccess.jsp</result>
</action>
<action name="viewuser" class="Action.Testiue" method="view">
<result name="success">/view.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="updateuser" class="Action.Testiue" method="update">
<result name="success">/edit.jsp</result>
<result name="error">/error.jsp</result>
</action>
<action name="deleteuser" class="Action.Testiue" method="delete">
<result name="success">/dsuccess.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
TestIUE.java
package Action;
import com.opensymphony.xwork2.ActionSupport;
import dao.UserDao;
import dbBean.UseBean;
public class Testiue
{
private String Name;
private String Password;
private String EmailID;
private String Phoneo;
private int ID;
public String getName()
{
return Name;
}
public void setName(String name)
{
Name = name;
}
public String getPassword()
{
return Password;
}
public void setPassword(String password)
{
Password = password;
}
public String getEmailID()
{
return EmailID;
}
public void setEmailID(String emailID)
{
EmailID = emailID;
}
public String getPhoneo()
{
return Phoneo;
}
public void setPhoneo(String phoneo)
{
Phoneo = phoneo;
}
public int getID()
{
return ID;
}
public void setID(int i)
{
ID = i;
}
#Override
public String toString()
{
return "UseBean [id=" + ID + ", Name=" + Name+ ", Password=" + Password + ", EmailID=" + EmailID + ", Phoneo="+ Phoneo + "]";
}
private UserDao dao;
private UseBean bean;
public String add()
{
dao=new UserDao();
bean=new UseBean();
System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.addUser(bean);
return ActionSupport.SUCCESS;
}
public String update()
{
dao=new UserDao();
bean=new UseBean();
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
bean.setID(ID);
bean.setName(Name);
bean.setPassword(Password);
bean.setPhoneo(Phoneo);
bean.setEmailID(EmailID);
dao.updateUser(bean);
return ActionSupport.SUCCESS;
}
public String delete()
{
int userId =0;
dao.deleteUser(userId);
return ActionSupport.SUCCESS;
}
public String edit()
{
int userId =0;
bean = dao.getUserById(userId);
return ActionSupport.SUCCESS;
}
public String view()
{
dao.getAllUsers();
return ActionSupport.SUCCESS;
}
}
Index.jsp
<META HTTP-EQUIV="Refresh" CONTENT="0;URL=viewuser.action">
view.jsp;
<%# taglib prefix="s" uri="/struts-tags"%>
<%#page import="java.util.*,dbBean.*,Dbconnect.*,java.util.*"%>
Insert
<table border=1>
<thead>
<tr>
<th>Id</th>
<th>Name</th>
<th>password</th>
<th>phoneno</th>
<th>emailid</th>
<th colspan=2>Action</th>
</tr>
</thead>
<jsp:useBean id="users" class="java.util.ArrayList" scope="request" />
<% for(int i = 0; i < users.size(); i+=1)
{
UseBean user = (UseBean)users.get(i);
%>
<tbody>
<tr>
<td><%= user.getID() %></td>
<td><%= user.getName() %></td>
<td><%= user.getPassword() %></td>
<td><%= user.getEmailID() %></td>
<td><%= user.getPhoneo() %></td>
<td>Update</td>
<td>Delete</td>
</tr>
<%
}
%>
</tbody>
</table>
edit.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="updateuser">
id:<input type="text" name="ID" ><br/>
Name:<input type="text" name="Name" ><br/>
Password:<input type="text" name="password" ><br/>
phoneno:<input type="text" name="Phoneo" ><br/>
Emailid:<input type="text" name="Emailid" > <br/>
<input type="submit" value="Submit" />
</form>
</body>
</html>
UserDao.java
package dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import dbBean.UseBean;
import Dbconnect.*;
public class UserDao
{
private Connection conn;
public UserDao()
{
conn=Dbconnect.getConnection();
}
public void addUser(UseBean bean)
{
try
{
String sql="insert into senthil (name,pass,phoneno,emailid) values(?,?,?,?)";
PreparedStatement ps=conn.prepareStatement(sql);
ps.setString(1,bean.getName());
ps.setString(2,bean.getPassword());
ps.setString(3,bean.getPhoneo());
ps.setString(4,bean.getEmailID());
ps.executeUpdate();
}
catch (Exception e)
{
// TODO: handle exception
}
}
public void deleteUser(int userId)
{
try
{
PreparedStatement ps = conn.prepareStatement("delete from senthil where id=?");
// Parameters start with 1
ps.setInt(1, userId);
ps.executeUpdate();
} catch (SQLException e)
{
e.printStackTrace();
}
}
public void updateUser(UseBean bean)
{
try
{
PreparedStatement preparedStatement = conn.prepareStatement("update senthil set name=?, pass=?, phoneno=?, emailid=?"+ "where id=?");
// Parameters start with 1
preparedStatement.setString(1, bean.getName());
preparedStatement.setString(2, bean.getPassword());
preparedStatement.setString(3, bean.getPhoneo());
preparedStatement.setString(4, bean.getEmailID());
preparedStatement.setInt(5, bean.getID());
preparedStatement.executeUpdate();
}
catch (SQLException e)
{
e.printStackTrace();
}
}
public List<UseBean> getAllUsers()
{
List<UseBean> users = new ArrayList<UseBean>();
try
{
Statement statement = conn.createStatement();
ResultSet rs = statement.executeQuery("select * from senthil");
while (rs.next())
{
UseBean user = new UseBean();
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
users.add(user);
}
}
catch (SQLException e)
{
e.printStackTrace();
}
return users;
}
public UseBean getUserById(int userId)
{
UseBean user = new UseBean();
try
{
PreparedStatement preparedStatement = conn.prepareStatement("select * from senthil where id=?");
preparedStatement.setInt(1, userId);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next())
{
user.setID(rs.getInt("id"));
user.setName(rs.getString("name"));
user.setPassword(rs.getString("pass"));
user.setPhoneo(rs.getString("phoneno"));
user.setEmailID(rs.getString("emailid"));
}
} catch (SQLException e)
{
e.printStackTrace();
}
return user;
}
}
In the JSP the users should be available to the request scope.
public String view() {
UserDao userDao = new UserDao();
List<UseBean> users = userDao.getAllUsers();
ServletActionContext.getRequest().setAttribute("users", users);
return Action.SUCCESS;
}
public String update() {
UserDao dao = new UserDao();
UseBean bean=new UseBean();
HttpServletRequest request ServletActionContext.getRequest();
bean.setID(request.getParameter("ID");
bean.setName(request.getParameter("Name");
bean.setPassword(request.getParameter("Password");
bean.setPhoneo(request.getParameter("Phoneo");
bean.setEmailID(request.getParameter("EmailID");
//System.out.println(getName()+""+getPassword()+""+getPhoneo()+""+getEmailID());
dao.updateUser(bean);
return Action.SUCCESS;
}
public String delete() {
HttpServletRequest request ServletActionContext.getRequest();
int userId = request.getParameter("ID");
dao.deleteUser(userId);
return Action.SUCCESS;
}
for delete action
<s:param name='ID'><%=user.getID()%></s:param></s:url>">Delete
Inside view method you haven't initialized the dao object(i.e reference is null), add the following code :
In TestIUE.java add one more member variable :
List<UseBean> users = new ArrayList<UseBean>();
Also add Accessor method :
public List<UseBean> getUsers()
{
return users;
}
Now modify your view method as follows :
public String view()
{
dao = new UseDao();
users = dao.getAllUsers();
return ActionSupport.SUCCESS;
}

Struts2 validation message appearing twice

I am trying struts validation but the error messages are getting printed twice. my action class is as follow.OSAction.java . I am so using hibernate in it. I think the validate method is called twice,
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;
}
*/
public void validate()
{
if (osdetail.getOSname() == null || osdetail.getOSname().trim().equals(""))
{
addFieldError("osdetail.OSname","The OS Name is required");
}
if (osdetail.getOSversion() == null || osdetail.getOSversion().trim().equals(""))
{
addFieldError("osdetail.OSversion","The OS Version is required");
}
}
}
My Index.jsp is below
<%# 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:hidden name="OSid" value="%{id}" />
    <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:reset value="Reset" />
</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>
Struts.xml is below
![<?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>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>][2]
enter code here
This is because you are incorrectly using a "chain" result. Don't use it unless you know what are you doing. To fix error you should change the configuration like this
<action name="add" class="net.ajeet.os.view.OSAction" method="add">
<result type="redirectAction">index</result>
<result name="input">/index.jsp</result>
</action>
<action name="index" class="net.ajeet.os.view.OSAction">
<result>/index.jsp</result>
</action>
Just implement interceptor-ref name="defaultStack" before your action in struts.xml

Categories