Struts2 action always returning success - java

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>

Related

How to get Array of Objects values from one Action Class to another Action Class in Struts 2?

I'm working an a project where I need the Array of Objects values from One Action Class to another.
The flow goes something like this:
Try1.java --> first.jsp --> Try2.java
I'm not able to get the Array of Objects values in Try2.java.
It's always null.
User.java
package com.sham;
public class User {
private int id;
private String name;
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;
}
}
Try1.java
package com.sham;
import java.util.ArrayList;
import com.opensymphony.xwork2.ActionSupport;
public class Try1 extends ActionSupport{
ArrayList<User> list=new ArrayList<User>();
public ArrayList<User> getList() {
return list;
}
public void setList(ArrayList<User> list) {
this.list = list;
}
public String execute(){
User user1=new User();
user1.setId(123);
user1.setName("John");
list.add(user1);
User user2=new User();
user2.setId(345);
user2.setName("Jen");
list.add(user2);
System.out.println("List " + list);
return "success";
}
}
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>
<package name="default" extends="struts-default">
<action name="click" class="com.sham.Try1" >
<result name="success">first.jsp</result>
</action>
<action name="next" class="com.sham.Try2" >
<result name="success">second.jsp</result>
</action>
</package>
</struts>
first.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="next">
Hello
<s:submit value="submit"/>
</s:form>
</body>
</html>
Try2.java
package com.sham;
import java.util.ArrayList;
import com.opensymphony.xwork2.ActionSupport;
public class Try2 extends ActionSupport {
ArrayList<User> list;
public ArrayList<User> getList() {
return list;
}
public void setList(ArrayList<User> list) {
this.list = list;
}
public String execute(){
System.out.println("List from Action class 2 " + getList());
return "success";
}
}
On clicking the submit button in first.jsp, the control goes to the Try2.java action class.
In Try2.java, I get null in getList().
I mean to say that, generally having getters and setters would work to get the values from one Action Class to another using hidden properties. But, in case of Array of Objects, it does not work the same, and the values are null.
In this case I want to get the Array of Object values for user 1 and user 2 in Try2.java.
I want to know how to get the same Array of Objects in the Try2.java from Try1.java action class.

Unable to set jsp form values to class variables

When I try to fetch the values from class, which were set in jsp, null is shown.
Following error is observed in dev mode:
ERROR ParametersInterceptor Developer Notification (set struts.devMode to false to disable this message):
Unexpected Exception caught setting 'name' on 'class org.ravi.EmployeeAction: Error setting expression 'name' with value 't'
Below are my various pages
struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<package name="default" extends="struts-default">
<action name="addEmployeeAction" class="org.ravi.EmployeeAction">
<interceptor-ref name="params" />
<interceptor-ref name="modelDriven"/>
<result name="success">/Add.jsp</result>
</action>
<action name="EmployeeAction" class="org.ravi.EmployeeAction" method="execute">
<interceptor-ref name="params" />
<interceptor-ref name="modelDriven"/>
<result name="success">/index.jsp</result>
</action>
</package>
</struts>
index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.util.*,java.io.*"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%#taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<s:form action="Add.jsp" name="addForm">
<table border="1" cellpadding="5">
<tr>
<th>Select</th>
<th>EmpID</th>
<th>Name</th>
<th>City</th>
<th>DoB</th>
</tr>
<tr>
<th><input type="radio" name="record"
onClick="radioValidate(this, 'record')" value="%{var}">
</th>
<th><s:property value="empid"/></th>
<th><s:property value="name"/></th>
<th><s:property value="city"/></th>
<th><s:property value="dob"/></th>
</s:form>
</body>
</html>
Add.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">
<%#taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<h1>Add New User</h1>
<s:form action="EmployeeAction" >
<s:textfield label="Emp Id" name="empid" />
<s:textfield label="Name" name="name" />
<s:textfield label="City" name="city" />
<s:textfield label="DoB" name="dob" />
<s:submit />
</s:form>
</body>
</html>
EmployeeAction.java
package org.ravi;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
public class EmployeeAction extends ActionSupport implements ModelDriven<Employee> {
private static final long serialVersionUID = -8136507522861159378L;
private Employee employee=new Employee();
public Employee getEmployee()
{
return employee;
}
public void setEmployee(Employee employee)
{
this.employee=employee;
}
public String execute() throws Exception
{
return SUCCESS;
}
#Override
public Employee getModel()
{
return employee;
}
}
Employee.java
package org.ravi;
import java.io.Serializable;
public class Employee implements Serializable{
static final long serialVersionUID = 1L;
private String empid;
private String name;
private String city;
private String dob;
public void setempid(String empid) {
this.empid = empid;
}
public void setname(String name) {
this.name = name;
}
public void setcity(String city) {
this.city = city;
}
public void setdob(String dob) {
this.dob = dob;
}
public String getempid() {
return this.empid;
}
public String getname() {
return this.name;
}
public String getcity() {
return this.city;
}
public String getdob() {
return this.dob;
}
}
public void setname(String name) {
this.name = name;
}
You need to name all of these properly, ie setName(String name)
same for setEmpId and so on. Struts cannot find your getters/setters because they don't follow naming conventions.
You're committing several errors, the worst is that
you're generating getters and setters manually (a lot of useless work), and you're also doing it wrongly: the first letter of the variable name must be capitalized:
setName( instead of setname( for variable name.
You should (for simplicity and consistency) also do it for every word of your variables with more than one word:
setEmpId( for variable empId.
You should also consider avoiding the redundancy when possible. If you have an ID field on a class Employee, just call it id, not empId... if it's inside Emp, it's obvious it's emp id and not something else id.
Use ModelDriven only if you enjoy pain. For any other purpose, it is as useful as a sausage in your pocket when facing a pack of hungry stray dogs.
Use the HTML5 DTD <!DOCTYPE html> also if you're targeting old browsers, there's no need to use 4.01 nowadays.
Never call JSPs directly like you do in your first form, always pass through actions first.
Start with this. There's plenty more.
Must read
Camel Case
Java Beans specifications

How to retrieve an instance from the database and display it using struts2 and hibernate?

I want to display an instance of the company pojo from the database. All I am able to display is the CompanyId the rest of the details are not getting displayed.
viewCompany.jsp
`<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:form action="ViewCompany">
<s:textfield name="companyId" label="Enter Company ID">
<s:param name="companyId" value="company.companyId"></s:param>
</s:textfield>
<s:submit/>
</s:form>
</body>
</html>
`
I am trying to enter the companyId and the values corresponding to the id should be displayed to the display page.
CompanyBean:
`package com.buhin.POJO;
public class Company {
private int companyId;
public String companyName;
public String contactPerson;
public String mobileNumber;
public String officeNumber;
public String mail;
public String addressLine1;
public String addressLine2;
public String cityName;
public String stateName;
public String zipcode;
//public Address address;
public Company(){}
public Company(int companyId){
this.companyId = companyId;
}
public int getCompanyId() {
return companyId;
}
public void setCompanyId(int companyId) {
this.companyId = companyId;
}
public String getCompanyName() {
return companyName;
}
public String getContactPerson() {
return contactPerson;
}
public String getMobileNumber() {
return mobileNumber;
}
public String getOfficeNumber() {
return officeNumber;
}
public String getMail() {
return mail;
}
public String getAddressLine1() {
return addressLine1;
}
public String getAddressLine2() {
return addressLine2;
}
public String getCityName() {
return cityName;
}
public String getStateName() {
return stateName;
}
public String getZipcode() {
return zipcode;
}
public void setCompanyName(String companyName) {
this.companyName = companyName;
}
public void setContactPerson(String contactPerson) {
this.contactPerson = contactPerson;
}
public void setMobileNumber(String mobileNumber) {
this.mobileNumber = mobileNumber;
}
public void setOfficeNumber(String officeNumber) {
this.officeNumber = officeNumber;
}
public void setMail(String mail) {
this.mail = mail;
}
public void setAddressLine1(String addressLine1) {
this.addressLine1 = addressLine1;
}
public void setAddressLine2(String addressLine2) {
this.addressLine2 = addressLine2;
}
public void setCityName(String cityName) {
this.cityName = cityName;
}
public void setStateName(String stateName) {
this.stateName = stateName;
}
public void setZipcode(String zipcode) {
this.zipcode = zipcode;
}
#Override
public String toString() {
return "Company [CompanyName=" + getCompanyName()
+ ", ContactPerson=" + getContactPerson()
+ ", MobileNumber=" + getMobileNumber()
+ ", OfficeNumber=" + getOfficeNumber() + ", Mail="
+ getMail() + ", AddressLine1=" + getAddressLine1()
+ ", AddressLine2()=" + getAddressLine2()
+ ", CityName()=" + getCityName() + ", StateName="
+ getStateName() + ", Zipcode=" + getZipcode()
+ "]";
}
}
ViewCompany.java(ActionClass)
`
package com.buhin.Action;
import com.buhin.POJO.*;
import com.buhin.DAO.*;
import com.opensymphony.xwork2.ActionSupport;
public class ViewCompany extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private int companyId;
Company company;
public Company getCompany(){
return company;
}
public void setCompany(Company company){
this.company = company;
}
public int getCompanyId(){
return companyId;
}
public void setCompanyId(int companyId){
this.companyId = companyId;
}
public String execute(){
CompanyDAO cdao = new CompanyDAO();
company = cdao.viewCompany(companyId);
//System.out.println(company.toString());
return "success";
}
}
CompanyDAO:
`package com.buhin.DAO;
import com.buhin.POJO.*;
import com.buhin.hibernate.*;
import com.opensymphony.xwork2.ActionSupport;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.SessionFactory;
public class CompanyDAO extends ActionSupport{
public CompanyDAO(){
}
/**
*
*/
private static final long serialVersionUID = 1L;
Company vCompany;
public String addCompany(Company company){
SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
Session session = sessionfactory.openSession();
Transaction transaction = session.beginTransaction();
session.save(company);
transaction.commit();
session.close();
return "success";
}
public Company viewCompany(int companyId){
SessionFactory sessionfactory = HibernateUtil.getSessionFactory();
Session session = sessionfactory.openSession();
vCompany = (Company) session.get(com.buhin.POJO.Company.class, companyId);
return vCompany;
}
}
`
companydetails.jsp:
`<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<s:property value="company.companyId"/>
<s:property value="company.companyName"/>
<s:property value="company.contactPerson"/>
<s:property value="company.mobileNumber"/>
<s:property value="company.officeNumber"/>
<s:property value="company.mail"/>
<s:property value="company.addressLine1"/>
<s:property value="company.addressLine2"/>
<s:property value="company.cityName"/>
<s:property value="company.stateName"/>
<s:property value="company.zipcode"/>
</body>
</html>`
`
Struts.xml:
`<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.devMode" value="true"></constant>
<package name="com.buhin.POJO" extends="struts-default">
<!-- <action name="AddCompany" class="com.buhin.Action.AddCompany" method="execute">
<result name="success">/success.jsp</result>
</action>
--> <action name="ViewCompany" class="com.buhin.Action.ViewCompany" method="execute">
<result name="success">/companydetails.jsp</result>
</action>
</package>
</struts>
`
First of all I agree with #Aleksandr M, this is a very bizarre structure. But nevertheless, there are a few things wrong with this code.
1) You are returning 'success' result from action methods, so your result should be <result name="success">/companydetails.jsp</result>
2) You are storing Company object in local variable(Company viewCompany). This will not be available in your JSP.
What you should do is make a object variable. Add setter-getters for that variable and use it in your JSP as follows.
<s:property value="viewCompany.zipcode"/>
Hope this helps.

404 page when running project through eclipse on Tomcat

Using Struts2 , I have set up a very simplistic webapp but when i run it in eclipese i got 404 error.. here is my all codes and jarfiles
URL : localhost:8985/firststruts/index.jsp
Jar files
commons-fileupload-1.3.1
commons-io-2.2
commons-lang-2.4
commons-logging-1.1.3
commons-logging-api-1.1
freemarker-2.3.19
javassist-3.11.0.GA
ognl-3.0.6
struts2-core-2.3.16.3
xwork-core-2.3.16.3
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>
<package name="default" extends="struts-default">
<action name="Product" class="com.javatpoint.Product">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>firstjsp</display-name>
<filter>
<filter-name>struts2</filter-name>
<filter-class>
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*</url-pattern>
</filter-mapping>
</web-app>
product.java
public class Product {
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() {
return "success";
}
}
welcome.jsp
<%# taglib uri="/struts-tags" prefix="s" %>
Product Id:<s:property value="id"/><br/>
Product Name:<s:property value="name"/><br/>
Product Price:<s:property value="price"/><br/>
index.java
<%# taglib uri="/struts-tags" prefix="s" %>
<s:form action="product">
<s:textfield name="id" label="Product Id"></s:textfield>
<s:textfield name="name" label="Product Name"></s:textfield>
<s:textfield name="price" label="Product Price"></s:textfield>
<s:submit value="save"></s:submit>
</s:form>
im new to struts2 so please help me to solve this.

Struts 2 Login Form Problems

I want to create a simple login form in Struts 2 but I'm having problems at seeing the input fields for some reason and after I submit the name of the user doesn't appear.
Here is the code:
Struts redirects to my struts.xml.
my struts.xml
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false"/>
<!-- devMode equals mode debug information and reload everything for every request -->
<constant name="struts.devMode" value="true" />
<package name="user" namespace="/User" extends="struts-default">
<action name="Login">
<result>Login.jsp</result>
</action>
<action name="DashboardAction" class="action.DashboardAction">
<result name="success">Dashboard.jsp</result>
</action>
</package>
</struts>
The Bean class
DashboardAction.java:
package action;
public class DashboardAction {
private String username;
public String execute(){
return "success";
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
The JSPs
Login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login</title>
</head>
<body>
<h1>Struts 2 Login Test</h1>
<form action="DashboardAction" id="form1" method="post" autocomplete="off">
<div class="input placeholder">
<s:textfield name="username" label="Utilizador"/>
</div>
<div class="input placeholder">
<s:password name="password" label="Password"/>
</div>
<div class="submit">
<s:submit value="Entrar" method="execute"/>
</div>
</form>
</body>
</html>
Dashboard.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Welcome User</title>
</head>
<body>
<h1>Hello
<s:property value="username"/>
</h1>
</body>
</html>
Why doesn't this work after I press submit? It's supposed to go to Dashboard.jsp?
Here you go :
<result name="success">/Dashboard.jsp</result>
You need to specify the full-path to the JSPs in your results. Notice the /. You need to do the same to your other result pages including Login.jsp
You should map the form to the action that accept data submitted. Use Struts tags
<%# taglib prefix="s" uri="/struts-tags" %>
<s:form action="Welcome" ...
<s:textfield name="username" ...
<s:password name="unknown" ...
couldn't map the password field because in your action there's not a property. May be if you create it
private String unknown;
public String getUnknown() {
return unknown;
}
public void setUnknown(String unknown) {
this.unknown = unknown;
}
Define property password in your action class like below.
DashboardAction.java
package action;
public class DashboardAction {
private String username;
private String password; // you don't have this line in your action class.
public String execute(){
return "success";
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}

Categories