I have a form with a p:fileUpload, and when I submit the form, all methods are not fired
This is my xhtml :
<h:form enctype="multipart/form-data">
<p:messages id="messages" showDetail="true"/>
<p:fileUpload value="#{uploadBean.file}" mode="simple" id="fileUploadId"/>
<p:commandButton value="Envoyer ce fichier" process="#form" update="messages fileUploadId" actionListener="#{uploadBean.upload}"/>
</h:form>
my bean :
public void setFile(final UploadedFile file)
{
System.out.println("Dans le setFile");
this.file = file;
}
public void upload()
{
System.out.println("Dans le upload");
System.out.println("Fichier : " + file.getFileName());
FacesContext.getCurrentInstance().addMessage(null, msg);
}
my web.xml :
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>
org.primefaces.webapp.filter.FileUploadFilter
</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
In the trace, I have just :
Infos: Dans le upload
Grave: Réception de «java.lang.NullPointerException» lors de l’invocation du listener d’action «#{uploadBean.upload}» du composant «j_idt11»
Grave: java.lang.NullPointerException
The method setFile() is not call...
Thanks
edit :
All the code of my bean :
import java.io.Serializable;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import javax.faces.context.FacesContext;
import org.primefaces.event.FileUploadEvent;
import org.primefaces.model.UploadedFile;
#ManagedBean
#ViewScoped
public class UploadBean implements Serializable
{
/**
*
*/
private static final long serialVersionUID = 556636819990963651L;
private UploadedFile file;
public UploadedFile getFile()
{
System.out.println("Dans le getFile");
return file;
}
public void setFile(final UploadedFile file)
{
System.out.println("Dans le setFile");
this.file = file;
}
public void upload()
{
System.out.println("Dans le upload");
// System.out.println("Fichier : " + file.getFileName());
FacesMessage msg;
if (file == null)
{
msg = new FacesMessage(FacesMessage.SEVERITY_WARN, "Raté ! ", "Le fichier vaut null.");
System.out.println("la variable file : null");
}
else
{
msg = new FacesMessage("Ouép ! ", file.getFileName() + " is uploaded.");
System.out.println("Le nom du fichier uploader est : " + file.getFileName());
}
FacesContext.getCurrentInstance().addMessage(null, msg);
}
}
From what you provided, I think you have done correctly so far. However, there are still 2 things you need to take care of:
You need to download common-io & common-fileupload and import the .jar file into your Library folder.
You also need to make sure that there are no other filters in web.xml or any classes that are annotated with #WebFilter which may read the HttpServletRequest#getInputStream() before PrimeFaces's filter, because it can be read only once.
You are using prettyfaces too? Then try it (set dispatcher):
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
<dispatcher>FORWARD</dispatcher>
</filter-mapping>
I had a similar issue, the form was not submitted and the setters methods were never called, add
<f:ajax event="change"/>
inside the component what u want to submit. also
"immediate=true"
on the component itself. Thought might be helpful to others..
Related
I'm getting this strange error when I try to use a scrollable TreeTable (but it does not happen using a non-scrollable TreeTable) component.
The component simply does not collapse or expand on click if I add
style="margin-top:0" scrollable="true" scrollHeight="150"
to the p:treeTable component.
If I remove this, it works like a charm.
Tried with both primefaces 4 and 5 community.
Running on tomcat 7, using mojarra 2.2.0. (added by eclipse), Oracle Java 7.
Trying to run on both firefox 30.0, chrome 35 and IE 11.
Looks like some deprecated JQuery method, but why primefaces 4 and 5 would distribute their single jar with the wrong JQuery?
Sounds like I am missing something here. What should I do to fix that?
I've created a Dynamic Web Project using Eclipse Kepler RC1, here goes the configuration info (pretty vanilla)
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>prime</display-name>
<welcome-file-list>
<welcome-file>index.xhtml</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>*.xhtml</url-pattern>
</servlet-mapping>
<context-param>
<description>State saving method: 'client' or 'server' (=default). See JSF Specification 2.5.2</description>
<param-name>javax.faces.STATE_SAVING_METHOD</param-name>
<param-value>client</param-value>
</context-param>
<context-param>
<param-name>javax.servlet.jsp.jstl.fmt.localizationContext</param-name>
<param-value>resources.application</param-value>
</context-param>
<listener>
<listener-class>com.sun.faces.config.ConfigureListener</listener-class>
</listener>
</web-app>
faces.config
<?xml version="1.0" encoding="UTF-8"?>
<faces-config
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-facesconfig_2_2.xsd"
version="2.2">
</faces-config>
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"
xmlns:ui="http://java.sun.com/jsf/facelets"
xmlns:p="http://primefaces.org/ui">
<h:head>
</h:head>
<h:body>
<h1>Hello World PrimeFaces</h1>
<h:form>
<p:treeTable value="#{tree.root}" var="document" style="margin-top:0" scrollable="true" scrollHeight="150">
<f:facet name="header">
Document Viewer
</f:facet>
<p:column headerText="Name">
<h:outputText value="#{document.name}" />
</p:column>
<p:column headerText="Size">
<h:outputText value="#{document.size}" />
</p:column>
<p:column headerText="Type">
<h:outputText value="#{document.type}" />
</p:column>
</p:treeTable>
</h:form>
</h:body>
</html>
managed bean
package prime;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.primefaces.model.DefaultTreeNode;
import org.primefaces.model.TreeNode;
#ManagedBean(name = "tree")
#ViewScoped
public class TreeBean implements Serializable{
/**
*
*/
private static final long serialVersionUID = 1L;
private TreeNode root;
#PostConstruct
public void init() {
root = createDocuments();
// root.getChildren().get(0).setExpanded(true);
}
public TreeNode getRoot() {
return root;
}
public TreeNode createDocuments() {
TreeNode root = new DefaultTreeNode(new Document("Files", "-", "Folder"), null);
TreeNode documents = new DefaultTreeNode(new Document("Documents", "-", "Folder"), root);
for(int i=0;i<100;i++){
new DefaultTreeNode("document", new Document("doc"+i, "40 KB", "Document"), documents);
}
return root;
}
}
entity bean
package prime;
import java.io.Serializable;
public class Document implements Serializable, Comparable<Document> {
/**
*
*/
private static final long serialVersionUID = 1L;
private String name;
private String size;
private String type;
public Document(String name, String size, String type) {
this.name = name;
this.size = size;
this.type = type;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSize() {
return size;
}
public void setSize(String size) {
this.size = size;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
//Eclipse Generated hashCode and equals
#Override
public int hashCode() {
final int prime = 31;
int result = 1;
result = prime * result + ((name == null) ? 0 : name.hashCode());
result = prime * result + ((size == null) ? 0 : size.hashCode());
result = prime * result + ((type == null) ? 0 : type.hashCode());
return result;
}
#Override
public boolean equals(Object obj) {
if (this == obj)
return true;
if (obj == null)
return false;
if (getClass() != obj.getClass())
return false;
Document other = (Document) obj;
if (name == null) {
if (other.name != null)
return false;
} else if (!name.equals(other.name))
return false;
if (size == null) {
if (other.size != null)
return false;
} else if (!size.equals(other.size))
return false;
if (type == null) {
if (other.type != null)
return false;
} else if (!type.equals(other.type))
return false;
return true;
}
#Override
public String toString() {
return name;
}
public int compareTo(Document document) {
return this.getName().compareTo(document.getName());
}
}
facets
$.browser is deprecated function in jquery latest. To use the deprecated function, use jquery migrate plugin
The plugin restores deprecated features and behaviors so that older
code will still run properly on jQuery 1.9 and later.
i'm having a problem to get the fullPath of a file which i upload using primefaces component . This is my code:
<h:form prependId="false" enctype="multipart/form-data">
<p:fileUpload update="#form" mode="advanced" auto="true"
fileUploadListener="#{myBean.myFileUpload}"/>
<h:outputText value="#{myBean.fileName}"/>
</h:form>
#ManagedBean
#SessionScoped
public class MyBean {
private String fileName;
public void myFileUpload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Succesful", event.getFile().getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
fileName = event.getFile().getFileName();
}
public String getFileName() {
return fileName;
}
public void setFileName(String fileName) {
this.fileName = fileName;
}
}
i only get the file's name but what i really want to get is the full path.
i already try this but it doesn't show anything.
fileName = FilenameUtils.getFullPath(event.getFile().getFileName());
What would you expect as fullPath of an uploaded file? The Browser sent you some bytes, they are in the memory of the servletcontainer and nowhere stored. There is no fullPath like /var/tmp/myfile.txt.
Try this:
String fileName = event.getFile().getFileName();
ServletContext servletContext = (ServletContext) FacesContext.getCurrentInstance().getExternalContext().getContext();
String newFileName = servletContext.getRealPath("") + File.separator + "upload" + File.separator+ fileName;
where "upload" must be replaced by name given in web.xml configuration for prime faces:
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
<init-param>
<param-name>uploadDirectory</param-name>
<param-value>/upload</param-value>
</init-param>
</filter>
I am working with JSF 2.0, tomcat 7.0, mojarra 2.0.3 and primefaces.
The problem is that I implemented unsuccessfully javax.servlet.Filter class to redirect to the login page if a user tries to enter a page without having logged in, but I am also using FileUpload to upload files to server, which I think is what is me and trigger conflict with the doFilter method, the server throws me the following exception:
javax.servlet.ServletException
javax.faces.webapp.FacesServlet.service (FacesServlet.java: 321)
org.primefaces.webapp.filter.FileUploadFilter.doFilter (FileUploadFilter.java: 98)
org.apache.tomcat.websocket.server.WsFilter.doFilter (WsFilter.java: 52)
I configured the web.xml file as follows:
<!--this may be the cause of the error--!>
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
<filter>
<filter-name>Login</filter-name>
<filter-class>controller.BeanFiltersession</filter-class>
</filter>
<filter-mapping>
<filter-name>Login</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
after that delete the class that implemented Filter and erased the lines in the web.xml file, but the error still persists
any idea how to fix it?
the problem is not the FileUpload problem is between primefaces, I think the problem is that as I indicated one filter to validate sessions using HttpSession and HttpServletRequest, upon login sends me this exception, it is clear that delete the class that implemented Filter, probe the FileUpload and works without problems, but I think the changes I made in that class were recorded at api.jar servlet-api having Tomcat 7.0 my code is as follows:
package validators;
import javax.faces.context.FacesContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
public class SessionValidator {
public static HttpSession getSesion(){
return (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
}
public static HttpServletRequest getRequest(){
return (HttpServletRequest) FacesContext.getCurrentInstance().getExternalContext().getRequest();
}
public static String getUser(){
HttpSession sesion= (HttpSession) FacesContext.getCurrentInstance().getExternalContext().getSession(false);
return sesion.getAttribute("usuario").toString();
}
public static String getNivel(){
HttpSession sesion=getSesion();
if(sesion !=null){
return sesion.getAttribute("nivel").toString();
}else{
return null;
}
}
}
The SessionValidator class called when I login in my code is this:
package controller;
import java.io.Serializable;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
import javax.faces.context.FacesContext;
import javax.faces.event.ActionEvent;
import javax.servlet.http.HttpSession;
import org.primefaces.context.RequestContext;
import validators.SessionValidator;
import model.csConexion;
import model.csSesion;
#ManagedBean
#SessionScoped
public class BeanSesion implements Serializable{
private static final long serialVersionUID = 1L;
private csSesion sesion;
private csConexion con;
HttpSession session;
private String usuario;
private String nivel;
public BeanSesion(){
sesion=new csSesion();
con=new csConexion();
}
public String getUsuario(){
return SessionValidator.getUser();
}
public void setUsuario(String usuario){
this.usuario=usuario;
}
public String getNivel(){
if(SessionValidator.getSesion().getAttribute("usuario")!=null){
return SessionValidator.getNivel();
}else{
return "";
}
}
public void setNivel(String nivel){
this.nivel=nivel;
}
public csSesion getSesion(){
return sesion;
}
public void setSesion(csSesion sesion){
this.sesion=sesion;
}
public String iniciarsesion(ActionEvent e){
RequestContext context= RequestContext.getCurrentInstance();
FacesContext fcontext= FacesContext.getCurrentInstance();
FacesMessage message=null;
boolean ok=false;
ResultSet rs;
try {
if(con.conectar()==true){
String sql="select*from usuario where usuario=? and contrasenia=?";
PreparedStatement comando= con.getConexion().prepareStatement(sql);
comando.setString(1,sesion.getUsuario());
comando.setString(2,sesion.getContrasenia());
rs=comando.executeQuery();
if(rs.next()){
nivel= rs.getString("nivel");
usuario= rs.getString("usuario");
ok=true;
session= SessionValidator.getSesion();
session.setAttribute("usuario", usuario);
session.setAttribute("nivel", nivel);
message= new FacesMessage(FacesMessage.SEVERITY_INFO,"¡Bienvenido!",sesion.getUsuario());
try {
if(nivel.equals("master")){
fcontext.getExternalContext().redirect("admin/admin.xhtml");
}else if(nivel.equals(null)){
fcontext.getExternalContext().redirect("index.xhtml");
}
} catch (Exception e2) {
e2.printStackTrace();
message= new FacesMessage(FacesMessage.SEVERITY_WARN,"Error","Error");
}
}else{
ok=false;
message= new FacesMessage(FacesMessage.SEVERITY_ERROR,"Error","Usuario o contraseña inválidos");
}
FacesContext.getCurrentInstance().addMessage(null,message);
context.addCallbackParam("Ok", ok);
}
} catch (Exception ex) {
ex.printStackTrace();
ok=false;
}
finally{
System.out.println(nivel);
con.desconectar();
}
return nivel;
}
}
and this is the exception send Tomcat:
excepción
javax.servlet.ServletException: null source
javax.faces.webapp.FacesServlet.service(FacesServlet.java:321)
org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:98)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
causa raíz
java.lang.IllegalArgumentException: null source
java.util.EventObject.<init>(Unknown Source)
javax.faces.event.SystemEvent.<init>(SystemEvent.java:67)
javax.faces.event.ComponentSystemEvent.<init>(ComponentSystemEvent.java:69)
javax.faces.event.PostRestoreStateEvent.<init>(PostRestoreStateEvent.java:69)
com.sun.faces.lifecycle.RestoreViewPhase.deliverPostRestoreStateEvent(RestoreViewPhase.java:256)
com.sun.faces.lifecycle.RestoreViewPhase.execute(RestoreViewPhase.java:245)
com.sun.faces.lifecycle.Phase.doPhase(Phase.java:97)
com.sun.faces.lifecycle.RestoreViewPhase.doPhase(RestoreViewPhase.java:107)
com.sun.faces.lifecycle.LifecycleImpl.execute(LifecycleImpl.java:114)
javax.faces.webapp.FacesServlet.service(FacesServlet.java:308)
org.primefaces.webapp.filter.FileUploadFilter.doFilter(FileUploadFilter.java:98)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
I am trying to navigate to error page if an exception occurred. For that I have defined:
<error-page>
<error-code>500</error-code>
<location>/error.jspx</location>
</error-page>
in the web.xml. Also I have tried to do this by Servlet:
<servlet>
<servlet-name>ErrorHandler</servlet-name>
<servlet-class>web.servlet.ErrorHandler</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ErrorHandler</servlet-name>
<url-pattern>/errorhandler</url-pattern>
</servlet-mapping>
<error-page>
<error-code>500</error-code>
<location>/errorhandler</location>
</error-page>
But neither it is navigating to the error.jspx nor the ErrorHandler Servlet get called.
To test the error handling I have tried to throw new Exception("Test"); from both of the constructor of managed bean and also from actionListener. But it is printing the exception in console but the redirection is not happening.
I have also tried with: <exception-type>java.lang.Exception</exception-type> instead of <error-code>500</error-code>, but no luck. How can I invoke the Servlet or navigate to the page whenever any exception is occurred from anywhere like the constructor or some action/actionListener?
I do not know if this will serve you.
I have a handler for any error defined as follows.
In "faces-config.xml"
<factory>
<exception-handler-factory>
com.mypackage.global.DatExceptionHandlerFactory
</exception-handler-factory>
</factory>
And two classes
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerFactory;
public class DatExceptionHandlerFactory extends ExceptionHandlerFactory {
private ExceptionHandlerFactory parent;
// this injection handles jsf
public DatExceptionHandlerFactory(ExceptionHandlerFactory parent) {
this.parent = parent;
}
//create your own ExceptionHandler
#Override
public ExceptionHandler getExceptionHandler() {
ExceptionHandler result =
new DatExceptionHandler(parent.getExceptionHandler());
return result;
}
}
Second class
import java.util.Iterator;
import javax.faces.FacesException;
import javax.faces.application.NavigationHandler;
import javax.faces.context.ExceptionHandler;
import javax.faces.context.ExceptionHandlerWrapper;
import javax.faces.context.FacesContext;
import javax.faces.context.Flash;
import javax.faces.event.ExceptionQueuedEvent;
import javax.faces.event.ExceptionQueuedEventContext;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class DatExceptionHandler extends ExceptionHandlerWrapper {
private static Log log = LogFactory.getLog(DatExceptionHandler.class);
private ExceptionHandler wrapped;
public String error = "n";
public String getError() {
return error;
}
public void setError(String error) {
this.error = error;
}
public DatExceptionHandler(ExceptionHandler wrapped) {
this.wrapped = wrapped;
}
#Override
public ExceptionHandler getWrapped() {
return wrapped;
}
#Override
public void handle() throws FacesException {
Iterator iterator = getUnhandledExceptionQueuedEvents().iterator();
while (iterator.hasNext()) {
ExceptionQueuedEvent event = (ExceptionQueuedEvent) iterator.next();
ExceptionQueuedEventContext context = (ExceptionQueuedEventContext)event.getSource();
Throwable throwable = context.getException();
FacesContext fc = FacesContext.getCurrentInstance();
try {
Flash flash = fc.getExternalContext().getFlash();
// Put the exception in the flash scope to be displayed in the error
// page if necessary ...
flash.put("errorDetails", throwable.getMessage());
System.out.println("the error is put in the flash: " + throwable.getMessage());
NavigationHandler navigationHandler = fc.getApplication().getNavigationHandler();
navigationHandler.handleNavigation(fc, null, "components/errorHandler.xhtml?faces-redirect=true");
fc.renderResponse();
} finally {
iterator.remove();
}
}
// Let the parent handle the rest
getWrapped().handle();
}
}
And errorHandler.xhtml to show error
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<link type="text/css" rel="stylesheet" href="#request.contextPath}/css/default.css" />
<title>#{bundle['guessNumber.error_page.title']}</title>
</h:head>
<h:body>
<div class="highlighted errorMessage">
<h:outputText escape="false"
value="#{bundle['guessNumber.error_page.content']}"/>
</div>
<br/><br/>
<div class="errorDetails">
Error details: <br/>
#{flash.keep.errorDetails}
</div>
</h:body>
</html>
I'm using PrimeFaces <p:fileUpload>. It does not invoke the listener method. If I add the FileUploadFilter, then I get an exception.
View:
<h:form enctype="multipart/form-data">
<p:fileUpload mode="advanced"
fileUploadListener="#{fileUploadController.upload()}"
allowTypes="/(\.|\/)(gif|jpg|jpeg|gif|png|PNG|GIF|JPG|JPEG)$/"
auto="false" />
</h:form>
Bean:
public class fileUploadController {
private String destination = "c:\test";
public void upload(FileUploadEvent event) {
FacesMessage msg = new FacesMessage("Success! ", event.getFile()
.getFileName() + " is uploaded.");
FacesContext.getCurrentInstance().addMessage(null, msg);
// Do what you want with the file
try {
copyFile(event.getFile().getFileName(), event.getFile()
.getInputstream());
} catch (IOException e) {
e.printStackTrace();
}
}
public void copyFile(String fileName, InputStream in) {
try {
// write the inputStream to a FileOutputStream
OutputStream out = new FileOutputStream(new File(destination
+ fileName));
int read = 0;
byte[] bytes = new byte[1024];
while ((read = in.read(bytes)) != -1) {
out.write(bytes, 0, read);
}
in.close();
out.flush();
out.close();
System.out.println("New file created!");
} catch (IOException e) {
System.out.println(e.getMessage());
}
}
}
web.xml
<filter>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<filter-class>org.primefaces.webapp.filter.FileUploadFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>PrimeFaces FileUpload Filter</filter-name>
<servlet-name>Faces Servlet</servlet-name>
</filter-mapping>
fileUploadListener="#{fileUploadController.upload()}" is problem here. I reproduced that and I also got an exception Method not found:
You should define fileUploadListener whithout parentheses. When you have added parentheses, expected method in your bean is upload() and not upload(FileUploadEvent event)