I have problem when upload image in Struts2.
I am trying to upload an image from jsp page to action class in struts2
My code is successfully run but executes up to System.out.println("2") and the image is not copied to the specified location.
Please help me to solve this problem
My Action class is below:
import java.io.File;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.apache.struts2.ServletActionContext;
import org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.tomcat.util.http.fileupload.disk.DiskFileItemFactory;
import org.apache.tomcat.util.http.fileupload.servlet.ServletFileUpload;
import com.opensymphony.xwork2.ActionSupport;
public class upload extends ActionSupport {
public String execute()throws Exception
{
try{
HttpServletRequest request = ServletActionContext.getRequest();
System.out.println("1");
List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
System.out.println("2");
for (FileItem item : items)
{
System.out.println("3");
if (!item.isFormField()){
String fieldname = item.getFieldName();
System.out.println(fieldname);
System.out.println("4");
File file = new File("F:/www/test/Rohit/workspace_Rohit/uploadWithStruts2/WebContent/uploadimage","hi.jpg");
item.write(file);
}
}
}
catch (Exception e) {
System.out.println(e);
}
return SUCCESS;
}
}
My jsp page is:
<form action="test.action" method="post" enctype="multipart/form-data">
<input type="file" name="image">
<input type="submit" value="upload"/>
</form>
// For upload Image in Struts2
// Jsp Page is:
<s:form method="post" action="test.action" enctype="multipart/form-data">
<s:file name="imageFile" label="User Image" />
<s:submit value="submit"></s:submit>
//Struts.xml
<struts>
<package name="default" extends="struts-default">
<action name="test" class="Test">
<result name="success">welcome.jsp</result>
</action>
</package>
</struts>
//Test.java
import java.io.File;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.StringTokenizer;
import com.opensymphony.xwork2.ActionSupport;
import org.apache.commons.io.FileUtils;
public class test extends ActionSupport{
private static final long serialVersionUID = 1L;
private File imageFile;
public File getImageFile() {
return imageFile;
}
public void setImageFile(File imageFile) {
this.imageFile = imageFile;
}
public String execute()throws Exception
{
try{
//code for image random name
// start from here to
DateFormat format = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
Date date = new Date();
String dt = format.format(date);
String name = "";
StringTokenizer str = new StringTokenizer(dt);
while (str.hasMoreElements())
{
String nm=(String) str.nextElement();
name+=nm;
}
String name1="";
StringTokenizer strg = new StringTokenizer(name,"/");
while (strg.hasMoreElements())
{
String nam=(String) strg.nextElement();
name1+=nam;
}
String imgname="";
StringTokenizer strge = new StringTokenizer(name1,":");
while (strge.hasMoreElements())
{
String na=(String) strge.nextElement();
imgname+=na;
}
//code for copy image to specific path
String sourceFilePath=imageFile.getAbsolutePath();
//System.out.println(sourceFilePath);
File sourceFile=new File(sourceFilePath);
File destnationFile=new File("E:/Jaydip_Baldha/workspace_new/Struts2Upload/WebContent/upload_image/"+imgname+".jpg");
FileUtils.copyFile(sourceFile, destnationFile);
}
catch(Exception e)
{
e.printStackTrace();
}
return SUCCESS;
}
}
Related
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.
This question already has answers here:
h:commandButton/h:commandLink does not work on first click, works only on second click
(2 answers)
have to press command button twice
(5 answers)
Closed 7 years ago.
I have a bunch of html files on my server that get loaded into my JSF view when a menu button is clicked.
Many of those files have an action button in them, like so:
<?xml version="1.0" encoding="utf-8"?>
<div xmlns:h="http://java.sun.com/jsf/html" xmlns:f="http://java.sun.com/jsf/core" xmlns="http://www.w3.org/1999/xhtml" id="d10e780" class="content">
<h:form id="publicationForm">
<h:panelGrid columns="2" width="45%">
<h:commandButton id="addToCart" value="Add to publishing Cart" actionListener="#{cartController.addToCart('d10e780.html')}">
<f:ajax execute="#form" render="#none"/>
</h:commandButton>
<h:commandButton id="viewCart" value="View publishing cart" action="#{cartController.viewCart()}"/>
</h:panelGrid>
</h:form>
<div id="d10e780" class="content">
<ul class="level_two">
<li class="level_two">SomeStuff</li>
</ul>
</div>
</div>
when the button is clicked, the name of the file is added to that shopping cart for subsequent publication.
The backing beans look like this:
package controllers;
import java.io.IOException;
import java.io.Serializable;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import javax.enterprise.context.SessionScoped;
import javax.inject.Named;
import org.xml.sax.SAXException;
import utils.PDFCreator;
#Named
#SessionScoped
public class Publication implements Serializable {
private static final long serialVersionUID = -2404153211000142338L;
private List<String> documents = new ArrayList<>();
private Map<Long, Boolean> selected = new HashMap<Long, Boolean>();
public Publication() {
}
public Map<Long, Boolean> getSelected() {
return selected;
}
public void setSelected(Map<Long, Boolean> selected) {
this.selected = selected;
}
public List<String> getDocuments() {
return documents;
}
public void setDocuments(List<String> documents) {
this.documents = documents;
}
public void addDocument(String dokumentId) {
if (!documents.contains(dokumentId)) {
documents.add(dokumentId);
}
}
public void publishPDF() {
List<String> checkedItems = new ArrayList<>();
for (String doc : documents) {
if (selected.get(doc)) {
checkedItems.add(doc);
System.out.println("BEING PUBLISHED " + doc);
}
}
selected.clear();
for (String item : checkedItems) {
try {
PDFCreator.makePDF(Paths.get(item));
} catch (SAXException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
and
package controllers;
import java.io.Serializable;
import javax.enterprise.context.SessionScoped;
import javax.inject.Inject;
import javax.inject.Named;
import views.Pages;
#SessionScoped
#Named
public class CartController implements Serializable {
#Inject
private Publication publication;
private static final long serialVersionUID = 7768738867325966926L;
public CartController() {
}
public void addToCart(String dokumentId) {
System.out.println("CARTCONTROLLER: ADDTOCART: " + dokumentId);
if (getPublication() == null) {
publication = new Publication();
getPublication().addDocument(dokumentId);
} else {
getPublication().addDocument(dokumentId);
}
}
public String viewCart() {
return Pages.PUBLICATION + "?faces-redirect=true";
}
public void editItem(String title) {
}
public void updateCart(String title) {
}
public Publication getPublication() {
return publication;
}
public void setPublication(Publication publication) {
this.publication = publication;
}
}
Now here's the problem: I have to click the button twice for the file name to be added to the list. Why is that? I'd like, of course, to just click the button once and have it work.
Thanks for help and tips!!
In my Struts Application, there is a Register form in a Jsp. The values enterd in it are then stored to mysql Db by means of an action class.
The action class (Register.java) for inserting values to mysql Db is:
package com.login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import com.opensymphony.xwork2.ActionSupport;
public class Register extends ActionSupport {
String regname;
String regpass;
String regmail;
public String getRegname() {
return regname;
}
public void setRegname(String regname) {
this.regname = regname;
}
public String getRegpass() {
return regpass;
}
public void setRegpass(String regpass) {
this.regpass = regpass;
}
public String getRegmail() {
return regmail;
}
public void setRegmail(String regmail) {
this.regmail = regmail;
}
Connection con;
Statement st;
ResultSet rs;
public void connect(){
try {
Class.forName("com.mysql.jdbc.Driver");
con=DriverManager.getConnection("jdbc:mysql://localhost:3306/vijay","root", "pwd");
//*.getConnection("jdbc:mysql://localhost:3307/shoppingmall","root", "vijay");
st=con.createStatement();*
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void queree(){
try {
//*st.executeUpdate("insert into prodet (name,password,email) values('"+this.getRegname()+"','"+this.getRegpass()+"','"+this.getRegmail()+"');");*
st.executeUpdate("insert into prodet (name,caty) values('"+this.getRegname()+"','"+this.getRegpass()+"');");
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public String execute() throws Exception {
this.connect();
this.queree();
return SUCCESS;
}
}
The Jsp:
<s:form action="/loginns/register" cssStyle="float:right; background-color:lightgreen" method="POST">
<h5 align="center">Register here</h5> <br>
<s:textfield name="regname" label="UserName"></s:textfield>
<s:textfield name="regpass" label="Password"></s:textfield>
<s:textfield name="regmail" label="email"></s:textfield>
<s:submit align="center" value="Register"></s:submit>
</s:form>
Struts.xml:
<package name="Login" namespace="/loginns" extends="struts-default">
<action name="register" class="com.login.Register">
<result name="error">/index.jsp</result>
<result name="success">/Registered.jsp</result>
</action>
</package>
Everything works fine. On clicking the Register button, it succesfully displays the resultant page. No Exceptions are thrown.
But on Db the values are not updated. Tried in 2 Dbs but the same result. (The code in italics are for the Db in Mysql workbench 6.0) What do i miss?
You must call executeUpdate for updates and inserts, executeQuery only for selects.
http://docs.oracle.com/javase/7/docs/api/java/sql/Statement.html
I tried to capture data from a master-detail form return an JSON object as follows my form is mimilar this http://www.vitarara.org/cms/struts_2_cookbook/creating_a_theme I followed this guide http://struts.apache.org/2.1.6/docs/tabular-inputs.html I can capture master data but how i can access to details? the result I get at this moment is
{"codigo":"RQ-201000-1210-00001","fecha":"Oct 25, 2012 12:00:00 AM","dreqproductos":[]}
my form is:
how i can obtain dreqproductos?
<input name="reqproducto.codigo" />
<input name="reqproducto.fecha" />
<input name="reqproducto.dreqproductos[1].masterproducto" />
<input name="reqproducto.dreqproductos[1].cantidad" />
<input name="reqproducto.dreqproductos[2].masterproducto" />
<input name="reqproducto.dreqproductos[2].cantidad" />
my class is
public class Reqproducto implements java.io.Serializable {
private Integer id;
private String codigo;
private Date fecha;
private Set dreqproductos = new HashSet(0);
}
and
public class Dreqproducto implements java.io.Serializable {
private Integer id;
private Masterproducto masterproducto;
private Reqproducto reqproducto;
private BigDecimal cantidad;
}
and my action is
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package actions;
import com.google.gson.Gson;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import hibernate.domain.Centrocosto;
import hibernate.domain.Dreqproducto;
import hibernate.domain.Reqproducto;
import hibernate.util.hibernateUtil;
import java.io.ByteArrayInputStream;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;
import java.util.*;
import model.dao.impl.DaoReqproductoImpl;
import org.hibernate.HibernateException;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.Transaction;
/**
*
* #author DEV11
*/
public class ActionReqProducto extends ActionSupport{
private InputStream inputStream;
public InputStream getInputStream() {
return inputStream;
}
public Reqproducto reqproducto;
public void setReqproducto(Reqproducto reqproducto) {
this.reqproducto = reqproducto;
}
public String ReqproductoIns() throws UnsupportedEncodingException {
//CAPTURA
String msg = "VOID";
Session session = hibernateUtil.getSessionFactory().getCurrentSession();
//Session session = HibernateUtil.getSessionFactory().openSession();
Transaction transaction = null;
try {
transaction = session.beginTransaction();
//////////////////////////////////////////////////////////////
if (reqproducto.getId() == null) {//INSERTAR
//CABECERA INSERTAR GERISTRO
session.save(reqproducto);
msg = "INSERT ";
} else {//ACTUALIZAR
//CABECERA ACTUALIZAR REGISTRO
String queryString = "from Reqproducto where id = :id";
Query query = session.createQuery(queryString);
query.setInteger("id", reqproducto.getId());
session.update(reqproducto);
msg = "UPDATE ";
}
//////////////////////////////////////////////////////////////
//session.getTransaction().commit();
transaction.commit();
msg += "OK" + reqproducto.getId();//+session.getIdentifier(reqproducto);;
} catch (HibernateException e) {
transaction.rollback();
//e.printStackTrace();
msg = "ERROR: " + e.getMessage();
} finally {
//session.close();
}
//RESPUESTA
Gson gson = new Gson();
//String json = "{cabecera:{'id':'"+id+"','codigo':'"+codigo+"','descripcion':'"+descripcion+"','abreviatura':'"+abreviatura+"','visible':'"+visible+"'}, msg:'Devolviendo Resultado via Ajax en \"EspaƱol\"'}";
String json = gson.toJson(this.reqproducto);
inputStream = new ByteArrayInputStream(json.getBytes("UTF-8"));
return SUCCESS;
}
}
I am using Primefaces 3.2 and developing the file download functionality and I am getting list of file names from my local which i wanted to display them in jsf datatable with clickable option(h:commandlink).
When I excute my Code I am getting following exception.
javax.el.PropertyNotFoundException: /faces/fileDownload.xhtml at line
33 and column 115 value="#{x.fileName}": Property 'fileName' not found
on type java.io.File
My Code looks like this Java File
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import org.primefaces.model.DefaultStreamedContent;
import org.primefaces.model.StreamedContent;
#ManagedBean(name="fileDownloadController")
#SessionScoped
public class FileDownloadController {
private StreamedContent file;
private List<File> listfiles=new ArrayList<File>();
private String fileName;
public FileDownloadController() {
File filestream=new File("C:/temp.pdf");
InputStream stream=null;
try {
stream = new FileInputStream(filestream);
file = new DefaultStreamedContent(stream, "application/pdf", "temp.pdf");
stream.close();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public List<File> getListfiles() {
File folder = new File("c:\\");
File[] listOfFiles = folder.listFiles();
listfiles=Arrays.asList(listOfFiles);
int i;
for(i=0;i<listfiles.size();i++){
System.out.println("The List of file are"+listfiles.get(i));
listfiles.get(i);
}
return listfiles;
}
public void setListfiles(List<File> listfiles) {
this.listfiles = listfiles;
}
public String getFileName() {
getListfiles();
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
public StreamedContent getFile() {
return this. file;
}
}
My XHTML looks like this.
<h:form id="form">
<h:dataTable value="#{fileDownloadController.listfiles}" var="x"
bgcolor="#F1F1F1" border="10" cellpadding="5"
cellspacing="3" first="0" rows="4" width="50%"
summary="This is a JSF code to create dataTable.">
<h:column>
<f:facet name="header">
<h:outputText value="File Names"></h:outputText>
</f:facet>
<h:commandLink value="#{x.fileName}" onclick="PrimeFaces.monitorDownload(showStatus, hideStatus)">
<p:fileDownload value="#{fileDownloadController.file}" />
</h:commandLink>
</h:column>
</h:dataTable>
</h:form>
I am not able to figure out where i went Wrong.Please help me.
How did you come to using #{x.fileName}? Look carefully in the javadoc of the java.io.File class. Right, there's no such method like getFileName(). That's exactly what the exception is trying to tell you.
value="#{x.fileName}": Property 'fileName' not found on type java.io.File
Most likely you meant to use the getName() method instead.
#{x.name}
Unrelated to the concrete problem, your code would be more self-documenting if you used var="file" instead of the nonsensicial var="x".