I am doing fileupload process in Struts2 application. When i display filename and contenttype in action class it showing null pointer exception.
I have included jar files and using the following codes.
In upload.jsp
<s:form action="saveBulkStores.action" method="POST" enctype="multipart/form-data">
<s:actionmessage name="message"/>
<s:label value="File Name : *" />
<s:file name="upload" label="File" size="40"/>
<br>
<br>
<s:submit name="ADD" value="UPLOAD"/>
<input type="button" onClick="cancelFunction()" name="Cancel" value="Cancel" tabindex="10">
</s:form>
In struts.xml
<action name="saveBulkStores" class="com.rewardz.action.FilesUploadAction" method="saveBulkStores">
<interceptor-ref name="fileUpload">
<param name="maximumSize">52428800</param>
</interceptor-ref>
<interceptor-ref name="basicStack"/>
<result name="input">/uploadfile.jsp</result>
<result name="viewFile">/viewfile.jsp</result>
<result name="Reload">/uploadfile.jsp</result>
</action>
In Action class:
private File file;
private String contentType;
private String filename;
public void setUpload(File file) {
this.file = file;
}
public void setUploadContentType(String contentType) {
this.contentType = contentType;
}
public void setUploadFileName(String filename) {
this.filename = filename;
}
public String saveBulkStores() throws IOException{
System.out.println("check Bulk upload file");
String filePath = request.getRealPath("/");
System.out.println("Server path:" + filePath);
System.out.println("UPLOADFILECONTENT TYPE:"+contentType);
System.out.println("UPLOADFILENAME:"+filename);
System.out.println("UPLOADFILE:"+file);
System.out.println("**********************************");
value = "viewFile";
System.out.println("Forward Value:"+value);
return value;
}
Output in Server.log:(Using GlassFish Server)
check Bulk upload file
C:\glassfish3_installer\glassfish\domains\domain1\applications\My_Application\
UPLOADFILECONTENT TYPE:null
UPLOADFILENAME:null
UPLOADFILE:null
So anybody please help me to get the filename,filepath in uploading process of Struts2.
Hi Shiva the problem is with the tag you are using in action class.
<s:file name="upload" label="File" size="40" />
where upload property is not existing in your action class there is a property File file you use file instead of upload so that will solve your problem
<s:file id="file" name="file" />
Related
I'm using Struts2 (version 2.5.14.1) with the Spring and Tiles plug-ins.
This is my (relevant) struts.xml configuration:
<package name="enrollment" namespace="/enrollment" extends="struts-bean-validation">
<result-types>
<result-type name="tiles" class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<action name="start" class="io.shido.struts.action.enrollment.StartAction">
<result name="success" type="tiles">enrollment.start.tiles</result>
</action>
<action name="personal-info" class="io.shido.struts.action.enrollment.PersonalInfoAction">
<result name="input" type="tiles">enrollment.personal-info.tiles</result>
<result name="success" type="tiles">enrollment.billing-info.tiles</result>
</action>
<action name="billing-info" class="io.shido.struts.action.enrollment.BillingInfoAction">
<result name="input" type="tiles">enrollment.billing-info.tiles</result>
<result name="success" type="tiles">enrollment.finish.tiles</result>
</action>
<action name="finish" class="io.shido.struts.action.enrollment.FinishAction">
<result name="success" type="tiles">enrollment.finish.tiles</result>
</action>
</package>
...the JSP file that holds one of the forms:
<%# taglib prefix="s" uri="/struts-tags" %>
<link rel="stylesheet" href="<s:url value='/resources/styles/enrollment.styles.css' />">
<s:form cssClass="form-input-info" action="personal-info" method="post">
<legend><s:text name="legend.text" /></legend>
<hr>
<s:textfield cssClass="form-control" key="textfield.first-name" name="personalInfo.firstName" />
<s:textfield cssClass="form-control" key="textfield.last-name" name="personalInfo.lastName" />
<s:textfield cssClass="form-control" key="textfield.email" name="personalInfo.email" />
<s:textfield cssClass="form-control" key="textfield.phone-number" name="personalInfo.phoneNumber" />
<s:textfield cssClass="form-control" key="textfield.age" name="personalInfo.age" />
<s:submit class="btn btn-primary btn-lg btn-block" key="submit.continue" />
</s:form>
...and finally the (super simple) Action class:
package io.shido.struts.action.enrollment;
// imports
public final class PersonalInfoAction extends ActionSupport {
private static final long serialVersionUID = 3560814234131884357L;
private final Logger logger = LogManager.getLogger(this.getClass());
private PersonalInfoHandler handler;
#Valid
private PersonalInfo personalInfo;
#Override
public String execute() {
// If personalInfo is not null is guaranteed to be valid due to Bean Validation contraints
if (null != personalInfo) {
logger.debug("Processing personal info...");
handler.save(personalInfo);
return Action.SUCCESS;
}
logger.info("Collecting personal info...");
return Action.INPUT;
}
public PersonalInfoHandler getHandler() { return handler; }
public void setHandler(final PersonalInfoHandler handler) { this.handler = handler; }
public PersonalInfo getPersonalInfo() { return personalInfo; }
public void setPersonalInfo(final PersonalInfo personalInfo) {
this.personalInfo = personalInfo;
this.personalInfo.normalize();
}
}
The issue is, whenever I submit that form, I'm expecting the Bean Validation to kick out and check all the annotated fields (check, this is happening) and when everything is fine, send the flow to /WEB-INF/content/enrollment/billing-info.jsp (defined in Tiles by enrollment.billing-info.tiles)...but all I see is (almost) the "billing info" form with the wrong labels. See the below picture:
The URL should have changed, as well as the labels. To put the cherry on top, if I click the Continue button again, the form is displayed then correctly.
Any clues?
I have no direct answer but you could try to use a redirect action instead of using the tiles several times.
So you could try this here:
<action name="personal-info" class="io.shido.struts.action.enrollment.PersonalInfoAction">
<result name="input" type="tiles">enrollment.personal-info.tiles</result>
<result name="success" type="redirectAction">
<param name="actionName">billing-info</param>
</result>
</action>
And if you need to transfer some kind of id to show the data you can use additional params in the struts.xml like this:
<!-- rest as above -->
<result>
<param name="param1">${value1}</param>
</result>
The param1 must have valid getter/setter-methods in both actions to transfer the information.
I am using struts2 for implementing my application. In my application I have to implement two drop downs, value of the second drop down is dependent on first drop down. I got reference from an example and implemented my code accordingly, but still not getting the result. Please give your suggestion to make this code work.
SupporterAction.java
package action;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import entityBean.TicketDataBean;
import entityBean.UserBean;
import entityListener.SupporterListener;
import entityManager.Application;
#SuppressWarnings("serial")
public class SupporterAction extends ActionSupport{
private String application;
private String number;
private List<String> applicationNames;
List<String> ticketNumber;
public String getNumber() {
return number;
}
public void setNumber(String number) {
this.number = number;
}
public List<String> getApplicationNames() {
return applicationNames;
}
public void setApplicationNames(List<String> applicationNames) {
this.applicationNames = applicationNames;
}
public List<String> getTicketNumber() {
return ticketNumber;
}
public void setTicketNumber(List<String> ticketNumber) {
this.ticketNumber = ticketNumber;
}
public String getApplication() {
return application;
}
public void setApplication(String application) {
this.application = application;
}
public String getJSON() {
return execute();
}
#SuppressWarnings("unchecked")
public String execute()
{
#SuppressWarnings("rawtypes")
Map session = ActionContext.getContext().getSession();
System.out.println(session.get("currentSessionUser"));
applicationNames = new ArrayList<String>();
UserBean userBean = (UserBean)session.get("currentSessionUser");
List<Application> applicationObj = userBean.getApplication();
for (Application obj : applicationObj)
{
System.out.println(obj.getApplicationName());
applicationNames.add(obj.getApplicationName());
}
session.put("ApplicationNames",applicationNames);
System.out.println("Hello");
System.out.println(application);
if(application != null)
{
ticketNumber=new ArrayList<String>();
System.out.println("Hello 1");
SupporterListener sl = new SupporterListener();
List<TicketDataBean> tdbList = sl.getPendingTickets(application);
if(!tdbList.isEmpty())
{
for(TicketDataBean td : tdbList)
{
ticketNumber.add(td.getNumber());
}
session.put("logined","true");
session.put("TicketNumber",ticketNumber);
}
}
return "success";
}
}
Supporter.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sj" uri="/struts-jquery-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 id="formSelectReload" theme="simple" cssClass="yform" action="getApplicationList">
<fieldset>
<div class="type-text">
<label for="application">Application : </label>
<s:url var="remoteurl" action="getApplicationList" namespace="/"/>
<sj:select href="%{remoteurl}" id="application" name="application"
list="applicationNames" onChange="reloadsecondlist" emptyOption="false"
headerKey="-1" headerValue="Please Select a Application" />
</div>
<s:property value="#session.ApplicationNames"/>
<div class="type-text">
<label for="number">Ticket Number: </label>
<s:url var="remoteurl" action="getApplicationList" namespace="/"/>
<sj:select href="%{remoteurl}" id="ticketNumber" formIds="formSelectReload"
reloadTopics="reloadsecondlist" name="number"
list="ticketNumber"
emptyOption="false"
headerKey="-1" headerValue="Please Select a Ticket Number"/>
</div>
<div class="type-button">
<sj:submit
id="submitFormSelectReload"
/>
</div>
</fieldset>
</s:form>
</body>
</html>
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN" "http://struts.apache.org/dtds/struts-2.3.dtd">
<struts>
<constant name="struts.enable.DynamicMethodInvocation" value="false" />
<constant name="struts.devMode" value="false" />
<constant name="struts.custom.i18n.resources" value="ApplicationResources" />
<package name="login" extends="struts-default">
<action name="login"
class="action.LoginAction"
method="execute">
<result name="success">/Home.jsp</result>
<result name="error">/InvalidLogin.jsp</result>
<result name="INVALID SESSION">/Home.jsp</result>
</action>
<action name="logout"
class="action.LoginAction"
method="logout">
<result name="success">/Login.jsp</result>
</action>
<action name="register">
<result>/Register.jsp</result></action>
<action name="importexcel">
<result>/ImportExcel.jsp</result></action>
<action name="supporter" class="action.SupporterAction"
method="execute">
<result name="success">/Supporter.jsp</result></action>
<action name="registeruser"
class="action.RegisterAction"
method="register">
<result name="success">/UserLogged.jsp</result>
<result name="error">/InvalidLogin.jsp</result>
<result name="INVALID SESSION">/Register.jsp</result>
</action>
<action name="importExcel"
class="action.ImportExcelAction"
method="importExcel">
<result name="success">/Home.jsp</result>
<result name="error">/InvalidLogin.jsp</result>
<result name="INVALID SESSION">/Home.jsp</result>
</action>
</package>
<package name="default" extends="struts-default,json-default" namespace="/">
<action name="getApplicationList"
class="action.SupporterAction" >
<result type="json" />
</action>
</package>
</struts>
jar files
Image of jar files
Result I am getting is
Image of result
As we can see in Image of result, list is being populated but I am not able to get it in drop down. Please suggest something.
Thank you in advance for your answers.
The prepare() interceptor is your friend.
https://struts.apache.org/docs/prepare-interceptor.html
I'm trying to set parameter value bulkID from form in ftl file to action class, but unable to set. Following is the code:
struts.xml file
<action name="bulk" class="com.action.BulkChangeMainAction">
<result name="input" type="freemarker">/resources/templates/bulk-changes.ftl</result>
</action>
BulkChangeMainAction.java
public class BulkChangeMainAction {
private int bulkID;
public int getBulkID() {
return bulkID;
}
public void setBulkID(int bulkID) {
this.bulkID = bulkID;
}
public String input() {
return INPUT;
}
}
bulk-changes.ftl
<form id='filter-form' action="<#s.url action='bulk' method='input'/>" method="post" name="filterForm">
<input type="text" id="bulkID" name="bulkID"/>
<input type="submit" value="Go"/>
</form>
Try using the struts2 form tag and sth like the following (I assume input is the action you want to call?):
<s:form action="bulk.input.action" method="post">
<s:textfield name="bulkId" label="Bulk Id" />
<s:submit value="Confirm" />
</s:form>
Here is a nice complete example too:
http://www.codejava.net/frameworks/struts/handling-form-data-in-struts2
if you need to keep the current format you have, please try changing int to String or Integer and see if it works.
Im using displaytable with tiles. Problem is in my crud application, when I search something its loading data into display table,
and when I click on 2nd page its load data to 2nd page as I give requestURI="searchorgs". All works fine upto that,
Then I call Edit template and after submitting edited data it should load data to table. Its also work fine but when I click 2nd page
Its goes to search page as I mention in requestURI="searchorgs". I need to keep in same page with out moving to search page. Same table is insert in to add,edit,search jsp pages in tiles.xml. I dont want to define 3 separate tables for this.
Application I struts2 tiles integration one.
action class search method :
public String search() {
organisationSearch = new OrganisationSearch();
organisationSearch.setAoName(aoName);
orglist = orgBo.searchOrg(organisationSearch);
return "search";
}
Struts xml :
<action name="*orgs" class="com.ast.action.admin.OraganisationAction"
method="{1}">
<result name="add" type="tiles">orgAddTemplate</result>
<result name="search" type="tiles">orgTemplate</result>
<result name="delete" type="tiles">orgTemplate</result>
<result name="edit" type="tiles">orgEditTemplate</result>
<r
</action>
table :
<s:form theme="simple" id="delete" action="deleteorgs">
<display:table id="studentTable" name="orglist" pagesize="5" cellpadding="5px;" id="row" cellspacing="5px;"
style="margin-left:50px;margin-top:20px;" requestURI="searchorgs">
<display:column style="width:5px;">
<s:checkbox name="chkBox" id="check%{#attr.row_rowNum - 1}" value="%{#attr.row.chkBox}" fieldValue="%{#attr.row.aoId}" />
</display:column>
<display:column title="Action" style="width:10px;" value="Edit" href="vieweditorgs" paramId="aoId" paramProperty="aoId" />
<display:column title="View" style="width:10px;" value="View" href="vieworgs" paramId="aoId" paramProperty="aoId" />
<display:column title="Dlt" style="width:10px;" value="Dlt" href="singledeleteorgs" paramId="aoId" paramProperty="aoId" />
<display:column property="aoId" title="ID" />
<display:column property="aoName" title="Name" />
</display:table>
You need to define action in requesturi programmatically.
Please see this
dispalay tag table pass value to requestURI
In action class
private String myActionName;
public String search() {
organisationSearch = new OrganisationSearch();
organisationSearch.setAoName(aoName);
orglist = orgBo.searchOrg(organisationSearch);
//set action name
myActionName="action1.action";
return "search";
}
//other methods
public void setMyActionName(String myActionName) {
this.myActionName = myActionName;
}
public String getMyActionName() {
return myActionName;
}
In jsp file
<display:table id="u" name="userlist" pagesize="10" requestURI="${myActionName}" >
...
</display:table>
If I misunderstood your question, Please let me know.
i am not able to get the value of the text entered in the textbox in jsp into my action class. below are my files. can anyone please help as this is very urgent.
my jsp is
<%# taglib uri="/struts-tags" prefix="s" %>
<html>
<body>
<s:form action="login" method="post">
<s:textfield name="userName" label="User Name" />
<s:submit type="button" id="submit" label="Submit"/>
<s:reset id="reset" label="Reset"></s:reset>
</s:form>
</body>
</html>
my action class is
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport {
private String userName;
public String getUserName() {
return userName;
}
public void setUsername(String username) {
this.userName = username;
}
public String execute(){
System.out.println("the userName is "+this.getUserName());
return SUCCESS;
}
}
and my struts.xml is
<?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="default" extends="struts-default">
<action name="login" class="core.login.LoginAction">
<result name="error">>/webpages/login/Error.jsp</result>
<result name="success">/webpages/home/Home.jsp</result>
</action>
</package>
</struts>
Case-sensitivity is important.
public void setUsername(String username) {
this.userName = username;
}
Should be:
public void setUserName(String username) {
this.userName = username;
}
In your struts.xml, you have written
class="core.login.LoginAction"
but you are not declaring any package in your Action class.
Also setter and getter method are of different names. Remember they are case-sensitive as said by Steven.
Try removing minor mistakes like an extra ">"
In your textfield add value attribute like this:
<s:textfield name="userName" label="User Name" value="${userName}" />
That directly maps it to member variable in action class.
In Eclipse,
to solve case sensitivity problem right click on code writing area and go to source -> Generate getter and setter method
It will add getter and setter method for selected member variables.