When I am using Model driven interface, my file upload operation is not working.
It is not popping any error, nor it is generating any log.
My code is attached hereby,
I want to know for file, do we have to generate its getters/setters in Model or Action with Model-Driven interface.
Atleast it should get uploaded to temp folder, as with struts by default uploads to temp.
Action
ProductAction.java
package com.fileupload.action;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import com.fileupload.model.FileUploadModel;
/**
* Action class to requests
* #package com.fileupload.action
*/
public class FileUploadAction extends ActionSupport implements ModelDriven<Object>{
FileUploadModel fileModel = new FileUploadModel();
#Override
public Object getModel() {
return fileModel;
}
}
Model ProductModel.java
package com.fileupload.model;
import java.io.File;
/**
* Model class to handle data
* #package com.fileupload.model
*/
public class FileUploadModel {
private String employeeName;
private File image;
private String imageFileName;
private String imageFileCotentType;
public File getImage() {
return image;
}
public void setImage(File image) {
this.image = image;
}
public String getImageFileName() {
return imageFileName;
}
public void setImageFileName(String imageFileName) {
this.imageFileName = imageFileName;
}
public String getImageFileCotentType() {
return imageFileCotentType;
}
public void setImageFileCotentType(String imageFileCotentType) {
this.imageFileCotentType = imageFileCotentType;
}
public String getEmployeeName() {
return employeeName;
}
public void setEmployeeName(String employeeName) {
this.employeeName = employeeName;
}
}
Configuration 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>
<constant name="struts.devMode" value="true"/>
<package name="FileUploadStruts" extends="struts-default">
<action name="index">
<result>/index.jsp</result>
</action>
<action name="submitForm" class="com.fileupload.action.FileUploadAction">
<result name="success">/result.jsp</result>
</action>
</package>
</struts>
View CreateProduct.jsp
<%--
Document : index
Created on : Nov 26, 2017, 12:50:38 PM
Author : owner
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>File upload example</title>
</head>
<body>
<h1>Fill the form below</h1>
<s:form action="submitForm" enctype="multipart/form-data" name="employeeform">
<s:textfield name="employeeName"/>
<s:file name="image"/>
<s:submit value="Submit"/>
</s:form>
</body>
</html>
Of,course,your file upload operation can working When you using Model
driven interface but you made a few mistake:
public class FileUploadModel {
private String employeeName;
private File image;
private String imageFileName;
// YourCode was wrong : private String imageFileCotentType;
private String imageFileContentType;
(get set)...
And then,you need to add a piece of code to your code for upload like
this:
#Namespace("/")
#ParentPackage("struts-default")
public class FileUploadAction extends ActionSupport implements ModelDriven<FileUploadModel> {
private static final long serialVersionUID = 1L;
FileUploadModel fileModel = new FileUploadModel();
#Override
public FileUploadModel getModel() {
return fileModel;
}
#Action(value = "submitForm", results = {
#Result(name = "success", location = "/result.jsp") })
public String submitForm() {
HttpServletRequest request = ServletActionContext.getRequest();
String tomcatPath = ServletActionContext.getServletContext().getRealPath("/");
String projectName = request.getContextPath();
projectName = projectName.substring(1);
String filePath = tomcatPath.substring(0, tomcatPath.indexOf(projectName)) + "uploadFile";
File dest = new File(filePath, fileModel.getImageFileName());
try {
FileUtils.copyFile(fileModel.getImage(), dest);
} catch (IOException e) {
e.printStackTrace();
}
return "success";
}
}
if you implements the function based on my answer,please reply to
me,smile.
Related
Is there any way to map json payload to Model bean.? If possible, please provide me an example.
Following are the classes I am using.
package com.sample;
import java.io.Serializable;
public class Employee implements Serializable{
private String firstName;
private String lastName;
private int id;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
#Override
public String toString() {
StringBuilder builder = new StringBuilder();
builder.append("Employee [firstName=").append(firstName)
.append(", lastName=").append(lastName).append(", id=")
.append(id).append("]");
return builder.toString();
}
}
Following is my action class.
package com.sample.controller;
import com.opensymphony.xwork2.ModelDriven;
import com.sample.Employee;
public class EmployeeController implements ModelDriven<Employee> {
private String name = "Hari krishna";
Employee emp = new Employee();
public String addEmployee() {
System.out.println(emp);
return "success";
}
#Override
public Employee getModel() {
return emp;
}
}
Following is 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>
<package name="default" extends="json-default">
<interceptors>
<interceptor-stack name="jsonStack">
<interceptor-ref name="json">
<param name="enableSMD">true</param>
</interceptor-ref>
</interceptor-stack>
</interceptors>
<action name="addEmployee" class = "com.sample.controller.EmployeeController" method = "addEmployee">
<interceptor-ref name="jsonStack"></interceptor-ref>
<result type="json" />
</action>
</package>
</struts>
When I call the action "addEmployee", with json data "{"firstName":"Hari","id":123,"lastName":"assds"}" I am getting following response. I set content type to text/json.
{
"model": {
"firstName": null
"id": 0
"lastName": null
}-
}
I am posting data using Advanced Rest Client.
when you send the json data from client to server, send them as string and in action class create a normal String variable to receive and hold the json's string.
Then, you can manually populate your bean from string using json parser,
or use a lib like google gson that has a build in features for this purposes.
Google Gson is a Java serialization/deserialization library that can convert Java Objects into JSON and back.
You can create your own struts Interceptor to wrap this process or implements it directly inside your action class.
I have index.jsp where I have one link,on clicking on that link that page specific action gets called.Now as on the click of this link,I need to display a page with already populated multiselect list along with few input text fields,in the constructor of the action I populated the TransactionBean which will be bound with fields on next page i.e transactionData.jsp.
The transactionData.jsp page is getting displayed correctly with populated multiselected list.Now user can select values from multiselect list and can enter dates in text field and will click on click button,so that a bar chart is displayed.
On click on Click button ,I am calling another action ,which also has TransactionBean as its property.In the execute method of this action, I am trying to access transactionbean with its getter but it gives me NullPointerException. I got to know that, if we are submitting a page which has fields of bean binded ,then on calling action,bean will be instantiated automatically through interceptors but seems like something is not correct here.
index.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>
<title>Hello World</title>
</head>
<body>
<s:form action="displayAction.action">
<h1>Hello World</h1>
Transaction Chart
</s:form>
</body>
</html>
DisplayAction.java
package com.tutorialspoint.struts2;
import java.util.ArrayList;
import java.util.List;
import com.opensymphony.xwork2.ActionSupport;
public class DisplayAction extends ActionSupport {
TransactionBean transactionBean;
public TransactionBean getTransactionBean() {
return transactionBean;
}
public void setTransactionBean(TransactionBean transactionBean) {
this.transactionBean = transactionBean;
}
public String execute() {
return SUCCESS;
}
public DisplayAction() {
System.out.println("Inside Constructor");
List<String> leftChannelsList = new ArrayList<String>();
leftChannelsList.add("Channel1");
leftChannelsList.add("Channel2");
//TransactionBean transactionBean = new TransactionBean();
setTransactionBean(new TransactionBean());
getTransactionBean().setLeftChannelsList(leftChannelsList);
//Transaction Type Dta
List<String> leftTransTypesList = new ArrayList<String>();
leftTransTypesList.add("TransType1");
leftTransTypesList.add("TransType2");
getTransactionBean().setLeftTransTypesList(leftTransTypesList);
}
}
transactionData.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>
<s:head theme="ajax" debug="true"/>
<title>Hello World</title>
</head>
<body bgcolor="grey">
<s:form action="displayChart.action">
<s:datetimepicker label="Select From" name="transactionBean.fromDate" displayFormat="MM-dd-yy" required="true" /> <s:datetimepicker label="Select To" name="transactionBean.toDate" displayFormat="MM-dd-yy" required="true" />
<s:optiontransferselect
label="Channels"
name="transactionBean.leftChannels"
leftTitle="Unselected Channels"
rightTitle="Selected Channels"
list="transactionBean.leftChannelsList"
multiple="true"
headerKey="-1"
doubleList="transactionBean.rightChannelsList"
doubleName="transactionBean.rightChannels"
doubleHeaderKey="-1"
doubleHeaderValue="Please Select"/>
<!-- Transaction Types -->
<s:optiontransferselect
label="transaction Types"
name="transactionBean.leftTransTypes"
leftTitle="Unselected Transaction Type"
rightTitle="Selected Transaction Type"
list="transactionBean.leftTransTypesList"
multiple="true"
headerKey="-1"
doubleList="transactionBean.rightTransTypesList"
doubleName="transactionBean.rightTransTypes"
doubleHeaderKey="-1"
doubleHeaderValue="Please Select"/>
<s:submit value="click" align="center"/>
</s:form>
</body>
</html>
JfreeChartAction.java
public class JfreeChartAction extends ActionSupport {
private JFreeChart chart;
private TransactionBean transactionBean;
private TransactionDao transactionDao;
public TransactionDao getTransactionDao() {
return transactionDao;
}
public void setTransactionDao(TransactionDao transactionDao) {
this.transactionDao = transactionDao;
}
public TransactionBean getTransactionBean() {
return transactionBean;
}
public void setTransactionBean(TransactionBean transactionBean) {
this.transactionBean = transactionBean;
}
// This method will get called if we specify <param name="value">chart</param>
public JFreeChart getChart() {
return chart;
}
public void setChart(JFreeChart chart) {
this.chart = chart;
}
public JfreeChartAction() {}
public String execute() throws Exception {
System.out.println("Inside Execute: Start");
System.out.println("From date:" + getTransactionBean().getFromDate());
System.out.println("From date:" + getTransactionBean().getToDate());
System.out.println("leftChannelsList:" + getTransactionBean().getLeftChannelsList());
System.out.println("Left Trans type List" + getTransactionBean().getLeftTransTypesList());
DefaultCategoryDataset dataSet = new DefaultCategoryDataset();
dataSet.setValue(0, "01-04-2014", "Channel1");
dataSet.setValue(15000, "01-04-2014", "Channel2");
dataSet.setValue(9000, "01-05-2014", "Channel1");
dataSet.setValue(1500, "01-05-2014", "Channel2");
dataSet.setValue(10000, "01-06-2014", "Channel1");
dataSet.setValue(8000, "01-06-2014", "Channel2");
chart = ChartFactory.createBarChart(
"Demo Bar Chart", //Chart title
"Mobile Manufacturer", //Domain axis label
"TRANSACTIONS", //Range axis label
dataSet, //Chart Data
PlotOrientation.VERTICAL, // orientation
true, // include legend?
true, // include tooltips?
false // include URLs?
);
chart.setBorderVisible(true);
System.out.println("Inside Execute: End");
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" namespace="/" extends="struts-default">
<action name="displayAction"
class="com.tutorialspoint.struts2.DisplayAction"
method="execute">
<result name="success">transactionsData.jsp</result>
</action>
</package>
<package name="defaultJfreeChart" namespace="/" extends="jfreechart-default">
<action name="displayChart"
class="com.tutorialspoint.struts2.JfreeChartAction"
method="execute">
<result name="success" type="chart">
<param name="value">chart</param>
<param name="type">jpeg</param>
<param name="width">600</param>
<param name="height">400</param>
</result>
</action>
</package>
</struts>
TransactionBean.java
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import org.jfree.chart.JFreeChart;
public class TransactionBean {
private Date dateTime;
private Integer volume;
private String leftChannels;
private String rightChannels;
private String toDate;
private String fromDate;
private List<String> leftChannelsList;
private List<String> rightChannelsList;
//Transaction type data
private String leftTransTypes;
private List<String> leftTransTypesList;
private String rightTransTypes;
private List<String> rightTransTypesList;
public Date getDateTime() {
return dateTime;
}
public void setDateTime(Date dateTime) {
this.dateTime = dateTime;
}
public Integer getVolume() {
return volume;
}
public void setVolume(Integer volume) {
this.volume = volume;
}
public TransactionBean(){
//System.out.println("Inside TransactionBean constructor");
}
public String getLeftTransTypes() {
return leftTransTypes;
}
public void setLeftTransTypes(String leftTransTypes) {
this.leftTransTypes = leftTransTypes;
}
public List<String> getLeftTransTypesList() {
return leftTransTypesList;
}
public void setLeftTransTypesList(List<String> leftTransTypesList) {
this.leftTransTypesList = leftTransTypesList;
}
public String getRightTransTypes() {
return rightTransTypes;
}
public void setRightTransTypes(String rightTransTypes) {
this.rightTransTypes = rightTransTypes;
}
public List<String> getRightTransTypesList() {
return rightTransTypesList;
}
public void setRightTransTypesList(List<String> rightTransTypesList) {
this.rightTransTypesList = rightTransTypesList;
}
public String getToDate() {
return toDate;
}
public void setToDate(String toDate) {
this.toDate = toDate;
}
public String getFromDate() {
return fromDate;
}
public void setFromDate(String fromDate) {
this.fromDate = fromDate;
}
public String getLeftChannels() {
return leftChannels;
}
public void setLeftChannels(String leftChannels) {
this.leftChannels = leftChannels;
}
public String getRightChannels() {
return rightChannels;
}
public void setRightChannels(String rightChannels) {
this.rightChannels = rightChannels;
}
public List<String> getRightChannelsList() {
return rightChannelsList;
}
public void setRightChannelsList(List<String> rightChannelsList) {
this.rightChannelsList = rightChannelsList;
}
public List<String> getLeftChannelsList() {
return leftChannelsList;
}
public void setLeftChannelsList(List<String> leftChannelsList) {
this.leftChannelsList = leftChannelsList;
}
}
can you please let me know which version should be used.
Always use the latest version. At the moment it's Struts 2.3.16.3 GA. You can also see Version Notes and Migration Guide.
Registration.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>
<center>
<%# taglib uri="/struts-tags" prefix="s"%>
<s:form action="getRegistered.action" method="post" validate="true">
<div>
<table>
<s:textfield label="First Name" key="firstname" />
<s:textfield label="Last Name" key="lastname" />
<s:password label="Create your password" key="regpassword" />
<s:password label="Confirm your password" key="conpassword" />
<s:textfield label="Email" key="regemail1" />
<s:textfield label="Re-Type Email" key="conemail" />
<s:textfield label="Phone" key="phone" />
<tr>
<td><s:submit value="Register" theme="simple"/></td>
<td><s:submit value="Cancel" theme="simple" onclick="document.forms[0].action='login.jsp';" /></td>
</tr>
</table>
</div>
</s:form>
</center>
</body>
</html>
I'm passing the register input values to Action class.
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="getLogin" class="login.action.LoginAction"
method="login">
<result name="success">/Success.jsp</result>
<result name="input">/LoginError.jsp</result>
</action>
<action name="getRegistered" class="login.action.LoginAction"
method="register">
<interceptor-ref name="validation">
<param name="excludeMethods">register</param>
</interceptor-ref>
<result name="success">/Success.jsp</result>
<result name="input">/login.jsp</result>
</action>
</package>
</struts>
This is the struts xml
LoginAction.java:
package login.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts2.interceptor.ServletRequestAware;
import org.apache.struts2.interceptor.ServletResponseAware;
import com.opensymphony.xwork2.ActionSupport;
import login.service.LoginDao;
import login.service.RegisterDao;
#SuppressWarnings("serial")
public class LoginAction extends ActionSupport implements ServletRequestAware,
ServletResponseAware {
private String username;
private String password;
private HttpServletRequest httpServletRequest;
private String firstname;
private String lastname;
private String regpassword;
private String conpassword;
private String regemail;
private String conemail;
private String phone;
public String register(){
RegisterDao rdao = new RegisterDao();
System.out.println("firstname action::: "+firstname);
rdao.registerdao(firstname,lastname,regpassword,conpassword,regemail,conemail,phone);
return SUCCESS;
}
public String login() {
httpServletRequest.getSession().setAttribute("key", username);
httpServletRequest.getSession().setAttribute("key", password);
LoginDao db = new LoginDao();
Boolean validate = db.loginresult(username, password);
if (validate == true) {
return SUCCESS;
} else {
return INPUT;
}
}
public HttpServletRequest getHttpServletRequest() {
return httpServletRequest;
}
public void setHttpServletRequest(HttpServletRequest httpServletRequest) {
this.httpServletRequest = httpServletRequest;
}
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 getRegpassword() {
return regpassword;
}
public void setRegpassword(String regpassword) {
this.regpassword = regpassword;
}
public String getConpassword() {
return conpassword;
}
public void setConpassword(String conpassword) {
this.conpassword = conpassword;
}
public String getRegemail() {
return regemail;
}
public void setRegemail(String regemail) {
this.regemail = regemail;
}
public String getConemail() {
return conemail;
}
public void setConemail(String conemail) {
this.conemail = conemail;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
public void setServletRequest(HttpServletRequest request) {
this.httpServletRequest = request;
}
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;
}
#Override
public void setServletResponse(HttpServletResponse arg0) {
// TODO Auto-generated method stub
}
}
When i submit the registration form , the input values pass to Action class is null. How can i access the registration values in action class under register() method.
The above issue is resolved .
Now i'm facing another strange issue .. When i submit the form action = getLogin.action , its always returning INPUT from the interceptor . I dont wish to exclude the method login from the validator.
How could i resolve it ?
When i change the struts xml like below , its redirecting to success jsp . But i dont want to exclude the login method from validation
<action name="getLogin" class="login.action.LoginAction"
method="login">
<interceptor-ref name="defaultStack">
<param name="validation.excludeMethods">login</param>
</interceptor-ref>
<result name="success">/Success.jsp</result>
<result name="input">/LoginError.jsp</result>
</action>
You are using only one Interceptor, you need to use the whole Stack:
Change this:
<interceptor-ref name="validation">
<param name="excludeMethods">register</param>
</interceptor-ref>
to this
<interceptor-ref name="defaultStack">
<param name="validation.excludeMethods">register</param>
</interceptor-ref>
I am developing a simple HelloWorld struts application. I am doing the configuration using struts.xml file. the welcome page is displayed but when I click on the form submit button, it gives 404 error.
Kindly provide some pointers.
action class:
package client;
public class Hello {
public String name;
public String message;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
public String execute() {
message = "Hello " + name;
return "success";
}
}
namecollect.jsp
<s:form action="hello" method="post">
<s:textfield name="name">Enter name</s:textfield>
<s:submit></s:submit>
</s:form>
struts.xml
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="client.Hello">
<result name="success">hello.jsp</result>
</action>
</package>
This is the package structure:
Your config file is in the wrong place.
By default struts.xml is expected to be at the root of your classpath.
In Struts 1.x , I have prepopulated the forms text fields using form bean's with default values as follows,
<html:form action="/actions/signup1">
First name: <html:text property="firstName"/><BR>
And in form bean, I have default value as follows...
public class ContactFormBean {
private String firstName = "First name";
But in Struts 2.x , when I tried with struts-tags textfield as follows, its not prepopulating the default value from the bean,
<s:form action="signup1">
<s:textfield name="formBean.firstName" label = "First Name" />
I have the formBean declared in my Action class as follows with appropriate getter and setter methods...
public class SignupAction1 extends ActionSupport {
private ContactFormBean formBean;
#Override
public String execute() throws Exception {
....
}
public ContactFormBean getFormBean(){
return formBean;
}
public void setFormBean(ContactFormBean fb){
formBean = fb;
}
}
Please let me know if this can be accomplished at Request level and not at session level.
Thanks in advance.
<--Edited-->
struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<package name="basicstruts2" extends="struts-default">
<action name="index">
<result>/index.jsp</result>
</action>
<action name="signup">
<result>/SignUp.jsp</result>
</action>
<action name="signup1" class="coreservlets.action.SignupAction1" method="execute">
<result name="success">/SignUp-Confirmation.jsp</result>
<result name="error">/SignUp.jsp</result>
</action>
</package>
</struts>
SignUp.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Sign UP</title>
</head>
<body>
<H1 ALIGN="CENTER">Sign Up</H1>
<s:form>
<s:textfield name="formBean.firstName" label = "First Name" />
<s:textfield name="formBean.lastName" label = "Last Name" />
<s:textfield name="formBean.email" label = "Email Address" />
<s:textfield name="formBean.faxNumber" label = "Fax Number" />
<s:submit action="signup1" method="loginAfterSubmit" value="Click here to Submit"/>
</s:form>
</body>
</html>
ContactFormBean.java
public class ContactFormBean {
private String firstName = "First name";
private String lastName = "Last name";
private String email = "user#host";
private String faxNumber = "xxx-yyy-zzzz";
public String getFirstName() {
return this.firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return(lastName);
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
public String getEmail() {
return(email);
}
public void setEmail(String email) {
this.email = email;
}
public String getFaxNumber() {
return(faxNumber);
}
public void setFaxNumber(String faxNumber) {
this.faxNumber = faxNumber;
}
public boolean isMissing(String value) {
if ((value == null) || (value.trim().equals(""))) {
return(true);
} else {
for(int i=0; i<defaultValues.length; i++) {
if (value.equals(defaultValues[i])) {
return(true);
}
}
return(false);
}
}
}
SignupAction1.java
public class SignupAction1 extends ActionSupport {
/**
*
*/
private static final long serialVersionUID = 1L;
private ContactFormBean formBean;
#Override
public String execute() throws Exception {
this.formBean = new ContactFormBean();
return SUCCESS;
}
public String loginAfterSubmit() {
String firstName = formBean.getFirstName();
String lastName = formBean.getLastName();
String email = formBean.getEmail();
String faxNumber = formBean.getFaxNumber();
if (formBean.isMissing(firstName)) {
return ERROR;
} else if (formBean.isMissing(lastName)) {
return ERROR;
} else if ((formBean.isMissing(email)) ||
(email.indexOf("#") == -1)) {
return ERROR;
} else if (formBean.isMissing(faxNumber)) {
return ERROR;
} else {
return SUCCESS;
}
}
public ContactFormBean getFormBean(){
return this.formBean;
}
public void setFormBean(ContactFormBean fb){
formBean = fb;
}
}
Change your signup action declaration to
<action name="signup" class="coreservlets.action.SignupAction1">
<result>/SignUp.jsp</result>
</action>
and signup1 to
<action name="signup1" class="coreservlets.action.SignupAction1" method="signup1">
create method signup1 in your SignupAction1 action class and move your logic from execute to it. In execute then create new instance of your ContactFormBean.
put your default value to the constructor:
public class ContactFormBean {
private String firstname;
public ContactFormBean (){
this.firstName = "First name";
}
}
You are returning a null formBean object with the getFormBean method,
then the constructor is never called and the attempt to acces the formBean attribute firstName is giving an error (that is not showed because it is wrapped by the Struts2 tag on the JSP.
You can
1) instantiate it on your execute method:
public String execute() throws Exception {
this.formBean = new ContactFormBean();
}
2) instantiate it lazily on your getter:
public ContactFormBean getFormBean(){
if (formBean==null)
this.formBean = new ContactFormBean();
return this.formBean;
}
EDIT (due to your comments):
I don't know how you've structured your web application;
But if you are on a JSP, an Action (and its execute() method, or another method if specified) was called BEFORE rendering the JSP.
So, regardless if you have ActionOne loading stuff and ActionTwo called after submit, or ActionOne loading stuff and another method of ActionOne called after submit, you can know if you are in a "pre-JSP" state or in a "post-submit" state...
That said, if you are exposing an Object, and you want its value or its attributes to be different from null, you have to instantiate it in one of the way described above.
Obviously, your object should contain getters and setters for its attributes, and they must have been bound to your JSP objects.
In your example, you could have:
ContactFormBean:
public class ContactFormBean {
private String firstName = "First name";
public String getFirstName(){
return this.firstName;
}
public String setFirstName(String firstName){
this.firstName = firstName;
}
}
Your Action:
public class SignupAction1 extends ActionSupport {
private ContactFormBean formBean;
public ContactFormBean getFormBean(){
return formBean;
}
public void setFormBean(ContactFormBean fb){
formBean = fb;
}
#Override
public String execute() throws Exception {
/* this method is executed before showing the JSP */
/* first time initialization */
this.formBean = new ContactFormBean();
return SUCCESS;
}
public String loginAfterSubmit() throws Exception {
/* this method is executed after the submit button was pressed */
/* i don't initialize nothing here,
ContactFormBean is coming from the page */
System.out.println("ContactFormBean's firstName value is: " +
this.formBean.getFirstName());
return "goSomewhereElse";
}
}
and in Your JSP:
<s:form>
<s:textfield name="formBean.firstName" label = "First Name" />
<s:submit action="signup1" method="loginAfterSubmit" value="Press here to submit" />
</s:form>
You can do this with two Action by splitting the execute() and the loginAfterSubmit() methods into two execute() methods of two different Actions;
Then you must have your formBean in BOTH the Actions, with at least the getter in the first, and the setter in the second.
You can also set the Name value in your bean in execute method, it will populate it in your JSP page. Example is :
public String execute() throws Exception {
this.formBean = new ContactFormBean();
//Set your Name value here
formBean.setName("John Doe");
return SUCCESS;
}
Once JSP is populated you will find this value in Name text box.
Hope this will help.
Tapan