Could not access bean in action Struts2 - struts2

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.

Related

File upload not working with Struts2 Model-Driven Interface

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.

Input values from jsp are null in Struts action class. How to access the registration form input values in Action class

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>

Prepopulating form's textfields with bean default value in Struts2

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

JSF Initialize Map Object

I'm starting my first steps in JSF.
I've already read this link
http://docs.oracle.com/javaee/6/tutorial/doc/bnawq.html#bnaww
in regards to map initialization.
The problem is, I want to populate my map with values residing in a file.
How can I do that?
I've tried not using faces-config.xml and calling a support method in the bean's constructor, but my select list box isn't populated.
My bean class:
#ManagedBean
public class ADGroupListBean {
private static final String WITH_ACCESS = "D:\\workspace\\AccessControl\\permissions.txt";
private static final String WITHOUT_ACCESS = "D:\\workspace\\AccessControl\\noPermissions.txt";
private Map<String,String> withAccess, withoutAccess;
private LDAPQueries queries;
public ADGroupListBean(){
withAccess = new LinkedHashMap<String, String>();
withoutAccess = new LinkedHashMap<String, String>();
queries = new LDAPQueries();
initList(WITH_ACCESS, withAccess);
initList(WITHOUT_ACCESS, withoutAccess);
}
private void initList(String filename, Map<String,String> list) {
File f = new File(filename);
if ( !f.exists() && f.getAbsolutePath().equals(WITHOUT_ACCESS) )
{
queries.queryAllGroups(WITHOUT_ACCESS);
}
try
{
Scanner sc = new Scanner(f);
while (sc.hasNext())
{
String group = sc.nextLine();
list.put(group, group);
}
}catch (IOException e) {
e.printStackTrace();
}
}
// public void populateList() {
//
//
// }
public Map<String,String> getWithAccess() {
return withAccess;
}
public Map<String,String> getWithoutAccess() {
return withoutAccess;
}
public void setWithoutAccess(Map<String,String> withoutAccess) {
this.withoutAccess = withoutAccess;
}
public void setwithAccess(Map<String,String> withAccess) {
this.withAccess = withAccess;
}
public void test() {
System.out.println("workssssssssssssssssss");
}
}
As for my JSF file, it is like this:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:f="http://java.sun.com/jsf/core"
xmlns:h="http://java.sun.com/jsf/html">
<h:head><title>Your Title Here</title>
</h:head>
<h:body>
<h1>Your Heading Here</h1>
<h:form>
<h:selectOneMenu value="teste">
<f:selectItem itemLabel="" itemValue="" />
<f:selectItems value="#{ADGroupListBean.withoutAccess}" />
</h:selectOneMenu>
</h:form>
</h:body>
</html>
I've tested the bean's functions in a test application, and everything works fine.
So my guess is the bean isn't instantiated?
Regards,
Nuno.

Ajax jsf two values

I am working on a project where Administrator selects a movie from a list. Then the data of the movie are displayed in inputTexts, so the admin can change it and onblur with ajax updates the database.
I created a bean in order to select the right data and display them in the inputTexts.
Thats ok. Now, I dont know how to allow the inputText to refer to the second bean where i have the update queries..
UPDATED
The Select Bean.
package Beans;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.RequestScoped;
/**
*
* #author Vasilis
*/
#ManagedBean
#RequestScoped
public class Select {
Connection con;
Statement statement;
String query;
private List perInfoAll = new ArrayList();
public List getperInfoAll() {
int i = 0;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "Bill", "1989");
statement = con.createStatement();
query = "SELECT NAME,SURNAME FROM AJAX";
ResultSet resultset = statement.executeQuery(query);
while (resultset.next()) {
perInfoAll.add(i, new Select.perInfo(resultset.getString(1), resultset.getString(2)));
i++;
}
} catch (Exception e) {
System.out.println("Error Data : " + e.getMessage());
}
return perInfoAll;
}
public class perInfo {
String NAME;
String SURNAME;
public perInfo(String NAME, String SURNAME) {
this.NAME = NAME;
this.SURNAME = SURNAME;
}
public String getNAME() {
return NAME;
}
public String getSURNAME() {
return SURNAME;
}
}
}
The Update Bean
package Beans;
import java.sql.*;
import javax.faces.bean.*;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
/**
*
* #author Vasilis
*/
#ManagedBean
#RequestScoped
public class Update {
Statement statement;
Connection con;
String query1;
String query2;
ResultSet resultset1;
ResultSet resultset2;
String NewName;
String NewSurname;
public void setNewSurname(String NewSurname) {
this.NewSurname = NewSurname;
}
public void setNewName(String NewName) {
this.NewName = NewName;
}
public String getNewSurname() {
return NewSurname;
}
public String getNewName() {
return NewName;
}
public void DatabaseConnection(String NewName) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException error) {
System.err.println("Error:Unable to load");
}
try {
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "BILL", "1989");
statement = con.createStatement();
query1 = "UPDATE AJAX SET NAME = ('" + NewName + "')";
resultset1 = statement.executeQuery(query1);
resultset1.next();
} catch (SQLException error1) {
System.err.println("Mistake");
}
}
public String updateit() {
DatabaseConnection(NewName);
return "ok";
}
public void DatabaseConnection1(String NewSurname) {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException error) {
System.err.println("Error:Unable to load");
}
try {
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "BILL", "1989");
statement = con.createStatement();
query2 = "UPDATE AJAX SET SURNAME = ('" + NewSurname + "')";
resultset2 = statement.executeQuery(query2);
resultset2.next();
} catch (SQLException error1) {
System.err.println("Mistake");
}
}
public String updateit1() {
DatabaseConnection1(NewSurname);
return "ok";
}
}
The index.xhtml
<?xml version='1.0' encoding='UTF-8' ?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html"
xmlns:f="http://java.sun.com/jsf/core">
<h:head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8"></meta>
<link rel="stylesheet" type="text/css" href="my.css" />
</h:head>
<h:body>
<h:form>
<h:inputText value="#{update.newName}" required="true" >
<f:ajax event="blur" render="#this" listener="#{update.updateit}" />
</h:inputText>
<h:inputText value="#{update.newSurname}" required="true" >
<f:ajax event="blur" render="#this" listener="#{update.updateit1}" />
</h:inputText>
</h:form>
</h:body>
So i want in index.xhtml to get the values from the select bean and when updated the value will sent to update bean
You should do something like this...
assign the inputText to a variable name in the bean class as -
private String myData;
//getters and setters.
public void updateData(ActionEvent e)
{
//put your query here to update to the database.
}
and in your web file do like this -
<h:inputText value="#{bean.myData}">
<a4j:support event="onblur" actionListener="#{bean.updateData}"/>
</h:inputText>
Show your list as you were showing, and after onblur it will directly update this value to the database by calling a function described above.
Hope it clears your doubt.

Resources