Saving form data in the database using Struts 2 - java

When we click the save button it must save the form data in the database but its doing nothing.
Below is the code:
BodyDaywise.jsp:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%# taglib uri="http://tiles.apache.org/tags-tiles" prefix="tiles" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sx" uri="/struts-dojo-tags" %>
<!DOCTYPE HTML>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Day Wise</title>
</head>
<body align="center">
<h1 align="center">Day Wise Form</h1>
<html:form action="daywise" class="BodyDaywiseAction" method="POST" >
LoginDate: <input type="date" name="LoginDate" displayformat="yyyy-mm-dd" label="Login Date(yyyy-mm-dd)"/><br><br>
LoginTime:<input id="start" type="time" name="LoginTime"/><br><br>
LogoutTime:<input id="end" type="time" name="LogoutTime"/><br><br>
Task:<input type="textarea" name="Task" label="Task" cols="20" rows="5"/><br><br>
<input type="submit" value="save" name="Save" onClick=""/>
<button type="submit" value="Clear" name="clear">Clear</button>
<input type="button" value="cancel" onClick="history.back();"/>
</html:form>
</body>
</html>
Action class: BodyDaywiseAction.java:
package com.timesheet.action;
import com.opensymphony.xwork2.ActionSupport;
import com.timesheet.db.DaywiseDBO;
import java.sql.Date;
import java.sql.Time;
public class BodyDaywiseAction extends ActionSupport {
public BodyDaywiseAction()
{
}
private Date LoginDate;
private Time LoginTime;
private Time LogoutTime;
private String Task;
public Date getLoginDate() {
return LoginDate;
}
public void setLoginDate(Date LoginDate) {
this.LoginDate = LoginDate;
}
public Time getLoginTime() {
return LoginTime;
}
public void setLoginTime(Time LoginTime) {
this.LoginTime = LoginTime;
}
public Time getLogoutTime() {
return LogoutTime;
}
public void setLogoutTime(Time LogoutTime) {
this.LogoutTime = LogoutTime;
}
public String getTask() {
return Task;
}
public void setTask(String Task) {
this.Task = Task;
}
private static final long serialVersionUID = 1L;
#Override
public String execute() throws Exception {
int i=DaywiseDBO.save(this);
if(i>0){
return "success";
}
return "error";
}
#Override
public void validate() {
if("".equals(getTask())){
addFieldError("Task", "Task must be filled !");
}
}
}
DaywiseDBO.java:
package com.timesheet.db;
import com.timesheet.action.BodyDaywiseAction;
import com.timesheet.dbutil.DBUtil;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class DaywiseDBO {
public static int save(BodyDaywiseAction BDA) throws Exception{
int status=0;
Connection conn = null;
ResultSet rs = null;
PreparedStatement ps = null;
DBUtil util = null;
try{
util = new DBUtil();
conn = util.getConnection();
ps = conn.prepareStatement("insert into logintable values(?,?,?,?)");
ps.setDate(1,BDA.getLoginDate());
ps.setTime(2,BDA.getLoginTime());
ps.setTime(3,BDA.getLogoutTime());
ps.setString(4,BDA.getTask());
status=ps.executeUpdate();
}catch(Exception e){
e.printStackTrace();}
return status;
}
}
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, tiles-default">
<result-types>
<result-type name="tiles"
class="org.apache.struts2.views.tiles.TilesResult" />
</result-types>
<action name="loginaction" class="com.timesheet.action.LoginAction" method="execute">
<result name="input" >/Login.jsp</result>
<result name="success" type="tiles">/bodydaywise.tiles</result>
<result name="error" type="tiles">/error.jsp</result>
</action>
<action name="daywise" class="com.timesheet.action.BodyDaywiseAction">
<result name="success" type="tiles">/bodydaywisesuccess.tiles</result>
<result name="error" type="tiles">/error.jsp</result>
</action>
</package>
</struts>
Please let me know if I'm missing something.

You are using wrong date/time type in the action class. Struts2 have not build-in converters for java.sql.* types. The date/time values should be converted to date if you use java.util.Date. objects of this type can contain both date and time values.
import java.util.Date;
import java.sql.Time;
Change the getters and setters accordingly to return the required. You can also set the date object to Calendar and do some calculations, after that you can create a Timestamp object from the calendar. For example
user.setCreateDate(new Timestamp(Calendar.getInstance().getTimeInMillis()));
sets the current date & time to the user object before the user is added to the database.
The example of using PreparedStatement: JDBC PreparedStatement example – Insert a record.
There's also an example to save only date part of the Date: Insert date value in PreparedStatement. (Don't use it, because it doesn't save a time portion of the Date).

Related

How to save file with its original name in Struts2 while uploading a file

I need to save uploaded file with its original name and type instead of temporary file name in separate folder.
By using below code i can get file name and type but how can i change temporary name with its original name.
private File file1;
private String file1ContentType;
private String file1FileName;
public File getFile1() {
return file1;
}
public void setFile1(File file1) {
this.file1 = file1;
}
public String getFile1ContentType() {
return file1ContentType;
}
public void setFile1ContentType(String file1ContentType) {
this.file1ContentType = file1ContentType;
}
public String getFile1FileName() {
return file1FileName;
}
public void setFile1FileName(String file1FileName) {
this.file1FileName = file1FileName;
}
public String upld() {
File dest = new File("/home/desktop/images/");
try {
System.out.println("file1FileName........"+file1FileName);
System.out.println("file1ContentType........"+file1ContentType);
System.out.println("file1........"+file1);
FileUtils.copyFileToDirectory(file1, dest);
} catch (Exception e) {
e.printStackTrace();
}
return "success";
}
By this code its possible to save video with its temporary file name but i want to save file with its original name and type....
or else is it possible to rename temporary file with its original name before saving in to the folder
Turn
File dest = new File("/home/desktop/images/");
/* ... */
FileUtils.copyFileToDirectory(file1, dest);
into
File dest = new File("/home/desktop/images/" + file1FileName);
/* ... */
FileUtils.copyFile(file1, dest);
Try below code.
jsp code:
<%# taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>
<body>
<h1>Struts 2 file upload example</h1>
<s:form action="resultAction" namespace="/"
method="POST" enctype="multipart/form-data">
<s:file name="upload" label="Select a File to upload" size="40" />
User file : <s:property value="uploadFileName"></s:property>
<s:submit value="submit" name="submit" />
</s:form>
</body>
</html>
Java Code:
import com.opensymphony.xwork2.ActionSupport;
import java.io.File;
import java.io.IOException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.io.FileUtils;
import org.apache.struts2.interceptor.ServletRequestAware;
public class FileUploadAction extends ActionSupport implements ServletRequestAware {
private File upload;
public File getUpload() {
return upload;
}
public void setUpload(File upload) {
this.upload = upload;
}
public String getUploadDocContentType() {
return uploadDocContentType;
}
public void setUploadDocContentType(String uploadDocContentType) {
this.uploadDocContentType = uploadDocContentType;
}
private String uploadDocContentType;
public HttpServletRequest request;
public HttpSession session;
public String uploadFileName;
public String getUploadFileName() {
return uploadFileName;
}
public void setUploadFileName(String uploadFileName) {
this.uploadFileName = uploadFileName;
}
public String uploadImg() throws IOException{
String targetPath ="/Desination path/";
session = request.getSession(true);
System.out.println("targetPath->"+uploadFileName);
File fileToCreate = new File(targetPath, uploadFileName);
try
{
FileUtils.copyFile(this.upload, fileToCreate);
}
catch (IOException e)
{
addActionError(e.getMessage());
}
return "success";
}
#Override
public void setServletRequest(HttpServletRequest request) {
// TODO Auto-generated method stub
this.request=request;
}
}
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.multipart.maxSize" value="20097152" />
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default ,json-default">
<action name="resultAction" class="FileUploadAction" method="uploadImg">
<interceptor-ref name="fileUpload">
<param name="maximumSize">1024000</param>
<param name="allowedTypes">image/png,image/gif,image/jpeg,image/pjpeg </param>
</interceptor-ref>
<interceptor-ref name="basicStack"/>
<result name="success">/index.jsp</result>
<result name="input">/index.jsp</result>
</action>
</package>
</struts>

How to: Select date, Press Button, Create File, Download File in Struts 2

What I want:
If someone visits the page, could select two dates and click a (single) button for downloading the data between the two dates selected.
What I already have working:
JSP/web development is new for me. This is my scenario, using datepicker and JSP have a page that make a query to the database, return certain data between two dates, and create a .txt file with this data which saves locally.
Once the file is created, another button can be pressed to download the file.
What I need to work:
I need only one button who made both actions, so once the file is saved locally, a prompt for download appear and the visitor could make the download.
Because of how common the words are, it's hard to find what I need on search engines.
I need a button. I don't want links or anchors that looks like a button, this could be an easy matter for some folks, but I already have lost two days in
Info:
Apache Tomcat: 8.0.27 && Netbeans 8.1 && Ubuntu 14.04
JSP:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<%#taglib prefix="sj" uri="/struts-jquery-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="resources/css/jtable.css" type="text/css">
<link rel="stylesheet" href="resources/css/style.css" type="text/css">
<link rel="stylesheet" href="resources/css/jquery-ui-1.10.3.custom.css" type="text/css">
<link href="resources/css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<script src="resources/js/jquery-1.11.3.js" type="text/javascript"></script>
<script src="resources/js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="resources/js/recuperacion-datos.js" type="text/javascript"></script>
<title></title>
<script>
$(document).ready(function(){
$("#datepicker1").datepicker({
maxDate: 0
});
$("#datepicker2").datepicker({
maxDate: 0,
onSelect: function(selected) {
$("#datepicker1").datepicker("option","maxDate", selected);
}
});
});
</script>
</head>
<body>
<center>
<div class="jtable-main-container" style="width: 60%;">
<div class="jtable-title">
<div class="jtable-title-text">
Recuperación de Datos
</div>
</div>
<div id="LecturasTableContainer" style="position: relative; text-align: center; font-size: 17px; top: 10px;">
Fecha Inicio: <input type="text" name="fechaInicio" id="datepicker1"> <span> </span><span> </span>
Fecha Fin: <input type="text" name="fechaFin" id="datepicker2">
<!-- Button who generate the file -->
<button type="submit" id="LoadRecordsButton" onclick="return confirm('Datos Recuperados');">Generar</button>
</div>
<br>
<!-- Button who download the file -->
<s:form action="download" method="POST">
<s:submit value="Descargar" type="button"/>
</s:form>
</div>
</center>
</body>
</html>
Action class for "Generar" Button:
package com.raspberry.struts.action;
import static com.opensymphony.xwork2.Action.SUCCESS;
import com.opensymphony.xwork2.ActionSupport;
import com.raspberry.dao.control.DBControl;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DataRecovery extends ActionSupport implements ServletRequestAware {
public HttpSession session;
public Connection c;
public String fechaFin;// = null;
public String fechaInicio; // = null;
public String goDataRecovery(){
session.setAttribute("mainopt", "dataRecovery");
return SUCCESS;
}
public String doDataRecovery() throws ParseException, FileNotFoundException{
DBControl dato = new DBControl();
fechaInicio = getFechaInicio();
fechaFin = getFechaFin();
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
String lectura = dato.selecAlltLecturasFecha(fechaInicio, fechaFin);
File archivo = new File ("/media/recovery"+fecha+".txt");
archivo.getParentFile().mkdirs();
PrintWriter printWriter;
printWriter = new PrintWriter(archivo);
printWriter.println (lectura);
printWriter.close ();
return SUCCESS;
}
public String getFechaFin() {
return fechaFin;
}
public String getFechaInicio() {
return fechaInicio;
}
#Override
public void setServletRequest(HttpServletRequest hsr) {
session = hsr.getSession();
}
}
Action Class for "Descargar" Button:
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
public class DownloadAction extends ActionSupport{
private InputStream fileInputStream;
public InputStream getFileInputStream() throws Exception {
return fileInputStream;
}
public String execute() throws Exception {
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
fileInputStream = new FileInputStream(new File ("/media/recovery"+fecha+".txt"));
return SUCCESS;
}
}
Struts.xml:
<action name="GetDataRecovery" class="com.raspberry.struts.action.DataRecovery"
method="doDataRecovery">
<interceptor-ref name="SessionValidationStack" />
<result name="success">main.jsp</result>
<result name="sessionexpired">index.jsp</result>
</action>
<action name="download" class="com.raspberry.struts.action.DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="recovery.txt"</param>
<param name="bufferSize">1024</param>
</result>
</action>
If you have followed the example, you should see that he was using two actions. One action is mapped to the JSP page, and another is used to download. First one is used to return an actionless result (class attribute is missing). It's needed to access JSP page through the action. If you follow this technique - first action, second JSP, then you can use Struts2.
You can also share the same JSP among different actions that return this JSP as a result. If you want to share the same JSP for two or more actions you should add a result that contains the name/path to the file.
You can use action class properties (not for actionless results) to hold the state of the action scope objects accessible in JSP via OGNL/JSTL or JSP EL.
Elements of type "submit" you should use inside the form, otherwise use type "button" and use javascript to submit the form (it doesn't concern s:submit tag though).
in the DataRecovery action class you should create a property for download link or some boolean to indicate that download is ready. Just keep the name of the action "download". If the property has a value then display the button for download.
<s:if test="downloadReady">
<s:form action="download" method="POST">
<s:submit type="button" cssClass="btn btn-primary" value="Descargar" />
</s:form>
</s:if>
private boolean isDownloadReady = false;
//getters and setters
and set this variable after saving a file.
First of all, thanks to #user3659052 #BalusC #Tiny and #Roman C , for your comments. All were very helpfull.
I was very confused, so after the comments enlightenment, decide to first start with some tutorials and yesterday get the web app working.
After fixing the struts action for the "Download Button", I tried to generate the file also in the Descargar Action Class, but the query to database was null.
The mistake was the form ID on the datepicker was pointing Generar Action Class, so the Descargar Action Class never get the data. So after change the pointer to the "correct" action, was able to get the dates, create the file (locally) and downloading in one action. (So Generar Action Class was deleted)
Struts .xml (fragment)
<action name="DataRecovery" class="com.raspberry.struts.action.DownloadAction" method="goDataRecovery">
<interceptor-ref name="SessionValidationStack" />
<result name="success">main.jsp</result>
<result name="sessionexpired">index.jsp</result>
</action>
<action name="GetRecovery" class="com.raspberry.struts.action.DownloadAction">
<result name="success" type="stream">
<param name="contentType">application/octet-stream</param>
<param name="inputName">fileInputStream</param>
<param name="contentDisposition">attachment;filename="recovery.txt"</param>
<param name="bufferSize">1024</param>
</result>
</action>
Descargar Action Class
package com.raspberry.struts.action;
import static com.opensymphony.xwork2.Action.SUCCESS;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import com.opensymphony.xwork2.ActionSupport;
import com.raspberry.dao.control.DBControl;
import java.io.FileNotFoundException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.struts2.interceptor.ServletRequestAware;
public class DownloadAction extends ActionSupport implements ServletRequestAware {
public InputStream fileInputStream;
public HttpSession session;
public Connection c;
public String fechaFin;// = null;
public String fechaInicio; // = null;
public String goDataRecovery(){
session.setAttribute("mainopt", "dataRecovery");
return SUCCESS;
}
public InputStream getFileInputStream() throws Exception {
return fileInputStream;
}
public String doDataRecovery() throws ParseException, FileNotFoundException{
DBControl dato = new DBControl();
fechaInicio = getFechaInicio();
fechaFin = getFechaFin();
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
String lectura = dato.selecAlltLecturasFecha(fechaInicio, fechaFin);
File archivo = new File ("/media/recovery"+fecha+".txt");
archivo.getParentFile().mkdirs();
PrintWriter printWriter;
printWriter = new PrintWriter(archivo);
printWriter.println (lectura);
printWriter.close();
return SUCCESS;
}
public String getFechaFin() {
return fechaFin;
}
public String getFechaInicio() {
return fechaInicio;
}
public String execute() throws Exception {
doDataRecovery();
DateFormat df = new SimpleDateFormat("yyyMMMddkkmm");
String fecha = df.format(Calendar.getInstance().getTime());
fileInputStream = new FileInputStream(new File ("/media/recovery"+fecha+".txt"));
return SUCCESS;
}
#Override
public void setServletRequest(HttpServletRequest hsr) {
session = hsr.getSession();
}
}
JSP
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<%#taglib prefix="sj" uri="/struts-jquery-tags"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" href="resources/css/jtable.css" type="text/css">
<link rel="stylesheet" href="resources/css/style.css" type="text/css">
<link rel="stylesheet" href="resources/css/jquery-ui-1.10.3.custom.css" type="text/css">
<link href="resources/css/jquery-ui-1.10.3.custom.css" rel="stylesheet" type="text/css" />
<script src="resources/js/jquery-1.11.3.js" type="text/javascript"></script>
<script src="resources/js/jquery-ui-1.10.3.custom.js" type="text/javascript"></script>
<script src="resources/js/recuperacion-datos.js" type="text/javascript"></script>
<title></title>
<script>
$(document).ready(function(){
$("#datepicker1").datepicker({
maxDate: 0
});
$("#datepicker2").datepicker({
maxDate: 0,
onSelect: function(selected) {
$("#datepicker1").datepicker("option","maxDate", selected);
}
});
});
</script>
</head>
<body>
<center>
<div class="jtable-main-container" style="width: 60%;">
<div class="jtable-title">
<div class="jtable-title-text">
Recuperación de Datos
</div>
</div>
<div style="position: relative; text-align: center; font-size: 17px; top: 10px;">
<s:form theme="simple" action="GetRecovery" method="POST" id="LecturasTableContainer">
Fecha Inicio: <input type="text" name="fechaInicio" id="datepicker1">
<span> </span><span> </span>
Fecha Fin: <input type="text" name="fechaFin" id="datepicker2">
<s:submit value="Descargar" id="LoadRecordsButton" type="button"/>
</s:form>
</div>
</div>
</center>
</body>
</html>
Once again thanks for the help.

two action method in an action class using the same stack in liferay struts2 [duplicate]

This question already exists:
action class do not passing objects to jsp class ,using struts2 in liferay
Closed 7 years ago.
i am using liferay with Struts2, i have two action method in one action class, i create an object from a class in first action method(execute()) and passing that to the view and showing it successfully, in view.jsp i'm using that object but when i submit the form and going to second action method(sendMessage()) an exception happened.
what should i do? what is the problem?
struts.xml
<struts>
<constant name="struts.devMode" value="true" />
<package namespace="/support" extends="struts-portlet-default,json-default"
name="subjectview">
<action name="index" class="com.xxx.actions.SupportFormAction"
method="execute">
<result>/html/support/view.jsp</result>
</action>
<action name="sendmsg" class="com.xxx.actions.SupportFormAction"
method="sendMessage">
<result name="success">/html/support/send-message-success-ajax.jsp</result>
<result name="error">/html/support/send-message-fail-ajax.jsp</result>
</action>
</package>
</struts>
SupportFormAction.java
package com.xxx.actions;
import com.iknito.model.SendEmail;
import com.opensymphony.xwork2.ActionSupport;
public class SupportFormAction extends ActionSupport {
private SendEmail sendEmail;
#Override
public String execute() throws Exception {
sendEmail = new SendEmail();
return "success";
}
public String sendMessage(){
try{
System.out.println(sendEmail.getName()); /* nullpointer exception happened here*/
return "success";
}
catch(Exception ex){
ex.printStackTrace();
return "error";
}
}
public SendEmail getSendEmail() {
return sendEmail;
}
public void setSendEmail(SendEmail sendEmail) {
this.sendEmail = sendEmail;
}
}
SendEmail.java
package iknito.com.actions;
public class SendEmail {
private String name;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
view.jsp
<%# include file="/html/init.jsp" %>
<%# taglib prefix="s" uri="/struts-tags" %>
<s:form id="form1" action="addsubjects" theme="simple">
<label for="name">Name:</label>
<s:textfield type="text" name="sendEmail.name" placeholder="Hamed Yousefi" required="required"/>
<s:submit value="enter name"/>
</s:form>
Your object is lost after it is rendered on JSP page.
You need to either
put it in the page, for example in hidden inputs, and re-trasmit it completely (in your case, one hidden parameter for each attribute of the object)
or (much better when there is an entire object and not a simple String) put it in the session, and retrieve it later.

Struts 2 file upload : File object being null

I am trying to use Struts 2 file upload but it seems to me that its not working. Below is my code.
UploadAction.java:
public class UploadAction extends ActionSupport{
private File file;
private String orgFileName;
private String orgContentType;
public void setUpload(File file){
this.file=file;
}
public void setUploadContentType(String contentType){
this.orgContentType=contentType;
}
public void setUploadFileName(String fileName){
this.orgFileName=fileName;
}
#Override
public String execute(){
if(file==null)
{
System.out.println("No file....");
}
System.out.println(orgContentType);
System.out.println(orgFileName);
return SUCCESS;
}
}
struts.xml:
<constant name="struts.multipart.maxSize" value="20971520" />
<constant name="struts2.multipart.saveDir" value="C:/users/sabertooth/desktop/upload" />
<include file="example.xml"/>
<!-- Configuration for the default package. -->
<package name="default" extends="struts-default">
<action name="upload" class="UploadAction">
<result name="success">/example/HelloWorld.jsp</result>
</action>
</package>
I am also trying to set struts2.multipart.saveDir property as you can see above but when I read the server logs I see this line
unable to find `struts.multipart.saveDir` defaulting to `javax.servlet.dir`
Also the file object is null as no file... gets printed out on console.
I can't figure out what is wrong here.
EDIT:
fileupload.jsp:
<%#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>JSP Page</title>
</head>
<body>
<h1>upload file below</h1>
<s:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="file" id="uploadfile" />
<input type="submit" id="submit" />
</s:form>
</body>
</html>
Apart from changing the saveDir (really not necessary, and dangerous), your are not following the conventions in the Action class: the name of an private variable must match the names of its Getters and Setters; and finally, in page you are mismatching the name by pointing to the private variable, not the setter. Change it to:
public class UploadAction extends ActionSupport{
private File upload;
private String uploadFileName;
private String uploadContentType;
public void setUpload(File upload){
this.upload=upload;
}
public void setUploadContentType(String uploadContentType){
this.uploadContentType=uploadContentType;
}
public void setUploadFileName(String uploadFileName){
this.uploadFileName=uploadFileName;
}
#Override
public String execute(){
if(upload==null)
{
System.out.println("No file....");
}
System.out.println(uploadContentType);
System.out.println(uploadFileName);
return SUCCESS;
}
}
JSP
<s:form action="upload" method="post" enctype="multipart/form-data">
<input type="file" name="upload" id="uploadfile" />
<input type="submit" id="submit" />
</s:form>
Change this
<input type="file" name="file" id="uploadfile" />
to
<input type="file" name="upload" id="uploadfile" />
Your setter in your action class is setUpload so it is looking for a request parameter called upload, not file. For the sake of convention you should also change
private File file;
public void setUpload(File file){
this.file=file;
}
to
private File upload;
public void setUpload(File file){
this.upload=file;
}

Struts 2 get result string in JSP

How to get the action result string in JSP?
I want to use the same JSP for all results.
public String doSth()
{
return a ? "ok" : "failed";
}
same.jsp:
<%--
Author : Prabhakar
--%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="s" uri="/struts-tags"%>
<html>
<body>
The Result is : <s:property value="a" />
</body>
</html>
ActionClass.java:
package com.prabhakar;
import com.opensymphony.xwork2.ActionSupport;
import java.util.Map;
import org.apache.struts2.interceptor.SessionAware;
/**
*
* #author Prabhakar
*/
public class ActionClass extends ActionSupport {
private String a;
public String getA() {
return this.a;
}
public void setA(String a) {
this.a = a;
}
public String doSth() {
if (some condition) {
a = "success";
} else {
a = "failed";
}
return a;
}
}
struts.xml
<struts>
<package name="somename" extends="struts-default">
<action name="resultName" method="doSth" class="com.prabhakar.ActionClass">
<result name="success">same.jsp</result>
<result name="failed">same.jsp</result>
</action>
</package>
</struts>
Only static access is available
<s:property value="#com.opensymphony.xwork2.ActionContext#getContext().getActionInvocation().getResultCode()"/>
For this code being able to work you need a configuration
<constant name="struts.ognl.allowStaticMethodAccess" value="true" />

Categories