RichFaces fileupload and h:message problem - file-upload

I am using RichFaces 4. My problem is that the message does not appear at all. If I use rich:message the message appears briefly then dissapears.
This is the controller:
public void uploadListener(final FileUploadEvent event) throws IOException
{
final UploadedFile item = event.getUploadedFile();
final FacesContext context = FacesContext.getCurrentInstance();
final Application application = context.getApplication();
final String messageBundleName = application.getMessageBundle();
final Locale locale = context.getViewRoot().getLocale();
final ResourceBundle resourceBundle = ResourceBundle.getBundle(messageBundleName, locale);
final String msg = resourceBundle.getString("upload.failed");
final String detailMsgPattern = resourceBundle.getString("upload.failed_detail");
try
{
CSVImporter.doImport(item.getInputStream(), registry, item.getName());
}
catch (ParseException e)
{
final Object[] params = {item.getName(), e.getMessage()};
final String detailMsg = MessageFormat.format(detailMsgPattern, params);
final FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detailMsg);
context.addMessage("uploadForm:uploader", facesMsg);
}
catch (TokenMgrError e)
{
final Object[] params = {item.getName(), e.getMessage()};
final String detailMsg = MessageFormat.format(detailMsgPattern, params);
final FacesMessage facesMsg = new FacesMessage(FacesMessage.SEVERITY_ERROR, msg, detailMsg);
context.addMessage("uploadForm:uploader", facesMsg);
}
}
And this is the view:
<h:form id="uploadForm" enctype="multipart/form-data">
<h:message id="message" showDetail="true" for="uploader" errorClass="error" warnClass="warning" infoClass="info" fatalClass="fatal"/>
<rich:fileUpload id="uploader"
fileUploadListener="#{itemController.uploadListener}"
maxFilesQuantity="1"
acceptedTypes="csv">
<a4j:ajax event="uploadcomplete" execute="#none" render="items, message" />
</rich:fileUpload>
</h:form>
In both cases Firebug reports an empty message field being sent.
<?xml version='1.0' encoding='UTF-8'?>
<partial-response><changes><update id="uploadForm:message"><![CDATA[<span id="uploadForm:message"></span>]]></update><update id="j_idt16:items"><![CDATA[<table id="j_idt16:items">
<thead>
<tr>
<th scope="col">
Titles
</th>
</tr>
</thead>
<tbody>
<tr><td></td></tr></tbody>
</table>
]]></update><update id="javax.faces.ViewState"><![CDATA[8859542538952100446:6041172679113548382]]></update></changes></partial-response>

The problem was the a4j:ajax tag. It was sending a second request, and the messages were cleared. This works:
<h:form id="uploadForm" enctype="multipart/form-data">
<h:message id="message" showDetail="true" for="uploader" errorClass="error" warnClass="warning" infoClass="info" fatalClass="fatal"/>
<rich:fileUpload id="uploader"
fileUploadListener="#{itemController.uploadListener}"
maxFilesQuantity="1"
acceptedTypes="csv"
render="items, message" />
</h:form>

Rich upload doesn't rerender messages:
https://community.jboss.org/message/55888
https://issues.jboss.org/browse/RF-3566

Related

How to fix NullPointerException when uploading picture in database?

I want to upload a picture in database, and this is my jsp:
<body>
<form action="addbooka" method="POST" enctype="multipart/form-data">
Title:<input type="text" value="${title}" name="title"> <br>
Description: <input type="text" value="${description}" name="description"><br>
Price: <input type="text" value="${price}" name="price"><br>
Picture: <input type="file" name="myimg"><br>
<button type="submit">Add</button>
</form>
</body>
And this is method where i insert picture:
public static void insertImage(String myImage) throws Exception {
try {
String insertImage = ("insert into image(image) values(?)");
PreparedStatement ps = DataBaseConnection.get().prepareStatement(insertImage);
File file = new File(myImage);
InputStream in = new FileInputStream(file);
ps.setBlob(1, in);
ps.executeUpdate();
In servlet i just call this method and pass request.getParameter("myimg") as an argument(input tag).
After some research i think i get this error because i did't put boundary in form tag. But i can't wrap my head around what numbers to put, what to do next or is it really error because of boundary or something else?
In your servlet don't forget to put #MultipartConfig annotation.Also , you are passing string to your method instead that should be Part . i.e :
int row=0;
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("myimg");//get image
insertImage(filePart)//pass to method
public static void insertImage(Part filePart) throws Exception {
String insertImage = ("insert into image(image) values(?)");
PreparedStatement ps = DataBaseConnection.get().prepareStatement(insertImage);
if (filePart != null) {
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
ps.setBlob(1, inputStream);
}
row = ps.executeUpdate();
if (row > 0) {
out.println("done")
}
}

Why session.getAttribute() always returning null inside JSP page textbox?

I am always getting null value in jsp page textbox. I have defined name attribute in index.jsp page and fetching value using <%=session.getAttribute()%>.
Here is index.jsp
<tr>
<td>First Name</td>
<td>
<input type="text" required="" name="firstname" value="<%=session.getAttribute("firstname")%>"/>
</td>
</tr>
In below UploadServletClass.java, session is defined
public class UploadServletClass extends HttpServlet{
PrintWriter out = null;
Connection con = null;
PreparedStatement ps = null;
HttpSession session = null;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException{
response.setContentType("text/plain;charset=UTF-8");
try{
out = response.getWriter();
session = request.getSession();
...
}
}
}
This is loginScript.jsp
<%
String zfid = request.getParameter("zid");
String fname = request.getParameter("firstname");
...
if (rs.next()) {
session.setAttribute("zfid", zfid); //used ${sessionScope.zfid} to display value into textbox and it is successful.
session.setAttribute("firstname",fname); //failed to display value in textbox
//out.println("welcome " + userid);
//out.println("<a href='logout.jsp'>Log out</a>");
response.sendRedirect("home.jsp");
}

Java Program to View the file Diff

Result.jsp :
<%#page import="org.apache.commons.lang3.StringUtils"%>
<%#page import="java.util.ArrayList"%>
<%#page import="java.util.Iterator"%>
<%#page import="java.util.ArrayList"%>
<%#page import="util.Utility"%>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<table cellpadding="3" cellspacing="3" border="3">
<tr>
<th align="center"><b>Current BootConf</b></th>
<th><b>New BootConf</b></th>
</tr>
<%
ArrayList<String> currentHacks = (ArrayList<String>) request.getAttribute("currentHacks");
ArrayList<String> newHacks = (ArrayList<String>) request.getAttribute("newHacks");
int size = currentHacks.size() > newHacks.size() ? currentHacks.size() : newHacks.size();
Iterator<String> current = currentHacks.iterator();
/* String cur[]=new String[currentHacks.size()];
String newBootconf[]=new String[newHacks.size()]; */
String cur[]=new String[size];
String newBootconf[]=new String[size];
int count=0;
while (current.hasNext()) {
cur[count]=(String)current.next();
count++;
}
count=0;
Iterator<String> new_hacks = newHacks.iterator();
while (new_hacks.hasNext()) {
newBootconf[count]=(String)new_hacks.next();
count++;
}
for(int i=0;i<size;i++){ %>
<tr>
<%
if(!Utility.replaceNull(cur[i]).equalsIgnoreCase(Utility.replaceNull(newBootconf[i]))){
%>
<td bgcolor="red"><%= Utility.replaceNull(cur[i])%></td>
<td bgcolor="red"><%= Utility.replaceNull(newBootconf[i])%></td>
<%}else{ %>
<td><%= Utility.replaceNull(cur[i])%></td>
<td><%= Utility.replaceNull(newBootconf[i])%></td>
<%}%>
</tr>
<%}
%>
</table>
</body>
</html>
ServletDiff.java
DoGet Method:
ArrayList<String> currentHacks = readFile(currentFolderPath, hacks);
ArrayList<String> newHacks = readFile(newFolderPath, hacks);
request.setAttribute("currentHacks",currentHacks);
request.setAttribute("newHacks",newHacks);
RequestDispatcher requestDispatcher;
requestDispatcher = request.getRequestDispatcher("/result.jsp");
requestDispatcher.forward(request, response);
**Method to Read File**
public ArrayList<String> readFile(String folderPath, String fileName) {
File f =null;
FileInputStream fis = null;
String line = null;
ArrayList<String> result= new ArrayList<String>();
int count=0;
try {
f=new File(folderPath + "\\" + fileName);
fis = new FileInputStream(f);
BufferedReader br = new BufferedReader(new InputStreamReader(fis));
while ((line = br.readLine()) != null) {
result.add(StringEscapeUtils.escapeXml(line));
count++;
}
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return result;
}`
Utility Class
public static String replaceNull(String input) {
return input == null ? "" : input;
}

Handling multiple submit buttons with JSP and Servlets

I have a table that is generated from the database. This table will be enclosed in a form. Below is the result on a browser:
http://i.imgur.com/NLZzgwP.png (Low rep problems)
Below is the JSP/JSTL code:
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Issues</title>
<style type="text/css">
table {
border-collapse: collapse;
}
table, th, td {
border: 1px solid black;
}
td {
padding: 10px;
}
</style>
</head>
<body>
<sql:setDataSource
var="myDS"
driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/pdfdb"
user="user" password="*******"
/>
<sql:query var="listIssues" dataSource="${myDS}">
SELECT BookId from Book;
</sql:query>
<form method="get" action="fileDownload">
<div align="center">
<table>
<caption>List of Issues</caption>
<tr>
<th>Magazine Issue #</th>
<th>Download</th>
</tr>
<c:forEach var="issue" items="${listIssues.rows}">
<tr>
<td><c:out value="${issue.BookId}" /></td>
<td><input name='<c:out value="${issue.BookId}" />' type="submit" value="Download"></td>
</tr>
</c:forEach>
</table>
</div>
</form>
</body>
</html>
Now, what I want is for the download button to be kind of linked with the id/Issue number that is placed on the same row as the button such that, when the user clicks the download button, it passes the id/magazine issue number to the url telling the browser that the user wants to download the corresponding magazine issue number of that button clicked. Below is the servlet I use to implement this:
package com.mypackage.fileDownload;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class FileDownloadServlet
*/
#WebServlet("/fileDownload")
public class FileDownloadServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
//size of byte buffer to send file
private static final int BUFFER_SIZE = 4096;
//database connection settings
private String dbUrl = "jdbc:mysql://localhost:3306/pdfdb";
private String dbUser = "user";
private String dbPass = "******";
/**
* #see HttpServlet#doGet(HttpServletRequesrequest,HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//get upload id from URL's parameters
String uploadId = request.getParameter("name");
Connection con = null; //connects to the database
try {
//connects to the database
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection(dbUrl, dbUser, dbPass);
//queries the database
String sql = "SELECT * FROM Book WHERE BookId = ?";
PreparedStatement pstmt = con.prepareStatement(sql);
pstmt.setString(1, uploadId);
ResultSet result = pstmt.executeQuery();
if(result.next()) {
//gets file name and file blob data
String fileId = result.getString("BookId");
Blob blob = result.getBlob("BookContent");
InputStream inputStream = blob.getBinaryStream();
int fileLength = inputStream.available();
System.out.println("File length = " + fileLength);
ServletContext context = getServletContext();
//Sets MIME type for the file download
String mimeType = context.getMimeType(fileId);
if(mimeType == null) {
mimeType = "application/octet-stream";
}
//set content properties and header attributes for the response
response.setContentType(mimeType);
response.setContentLength(fileLength);
String headerKey = "Content-Disposition";
String headerValue = String.format("attachment; filename=\"%s\"", fileId);
response.setHeader(headerKey, headerValue);
//writes the file to the client
OutputStream outStream = response.getOutputStream();
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while((bytesRead = inputStream.read(buffer)) != -1) {
outStream.write(buffer, 0, bytesRead);
}
inputStream.close();
outStream.close();
} else {
//no file found
response.getWriter().print("File not found for the id: " + uploadId);
}
} catch(SQLException ex) {
ex.printStackTrace();
response.getWriter().print("SQL Error: " + ex.getMessage());
} catch(IOException ex) {
ex.printStackTrace();
response.getWriter().print("IO Error: " + ex.getMessage());
} catch(ClassNotFoundException ex) {
ex.printStackTrace();
response.getWriter().print("Class Missing Error: " + ex.getMessage());
}
finally {
if(con != null) {
//closes the database connection
try {
con.close();
} catch(SQLException ex) {
ex.printStackTrace();
}
}
}
}
}
Well, from the way I have done this, it is not working the way I wanted it to. For example, if you run this code on the server and click any of the download buttons, the url will be something like
issue.jsp?1=Download
which is weird.It will also display on the browser
File not found for the id: null
I expect something like(on the url)
issue.jsp?Download=1
where 1 is the issue being downloaded. My database has two columns: the IssueId and fileContent(content of file stored in BLOB).
I think I have explained enough and the concept is clear. Any help will be appreciated and this is as far as I could go with my code & research. Thanks!
The simplest way is to just move the form inside the table and do multiple forms:
<div align="center">
<table>
<caption>List of Issues</caption>
<tr>
<th>Magazine Issue #</th>
<th>Download</th>
</tr>
<c:forEach var="issue" items="${listIssues.rows}">
<tr>
<td><c:out value="${issue.BookId}" /></td>
<td>
<form method="get" action="fileDownload">
<input type='hidden' name='bookid' value='<c:out value="${issue.BookId}" />' />
<input type="submit" value="Download">
</form>
</td>
</tr>
</c:forEach>
</table>
</div>
You also need to move the value out of the name attribute of the button and into the value attribute of a hidden input. That hidden input needs a name you will use to get the value in the servlet: request.getParameter("bookid");

NullPointer Exception in jsp [closed]

This question is unlikely to help any future visitors; it is only relevant to a small geographic area, a specific moment in time, or an extraordinarily narrow situation that is not generally applicable to the worldwide audience of the internet. For help making this question more broadly applicable, visit the help center.
Closed 10 years ago.
org.apache.catalina.core.ApplicationDispatcher invoke
SEVERE: Servlet.service() for servlet UserController threw exception
java.lang.NullPointerException
at com.nic.sample.dao.UserDAO.getAllUsers(UserDAO.java:69)
at com.nic.sample.controller.UserController.doGet(UserController.java:44)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.ApplicationDispatcher.invoke(ApplicationDispatcher.java:646)
at org.apache.catalina.core.ApplicationDispatcher.processRequest(ApplicationDispatcher.java:436)
at org.apache.catalina.core.ApplicationDispatcher.doForward(ApplicationDispatcher.java:374)
at org.apache.catalina.core.ApplicationDispatcher.forward(ApplicationDispatcher.java:302)
at org.apache.jasper.runtime.PageContextImpl.doForward(PageContextImpl.java:709)
at org.apache.jasper.runtime.PageContextImpl.forward(PageContextImpl.java:680)
at org.apache.jsp.index_jsp._jspService(index_jsp.java:64)
at org.apache.jasper.runtime.HttpJspBase.service(HttpJspBase.java:70)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.jasper.servlet.JspServletWrapper.service(JspServletWrapper.java:388)
at org.apache.jasper.servlet.JspServlet.serviceJspFile(JspServlet.java:313)
at org.apache.jasper.servlet.JspServlet.service(JspServlet.java:260)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)
at org.apache.catalina.core.StandardWrapperValve.invoke(StandardWrapperValve.java:233)
at org.apache.catalina.core.StandardContextValve.invoke(StandardContextValve.java:191)
at org.apache.catalina.core.StandardHostValve.invoke(StandardHostValve.java:127)
at org.apache.catalina.valves.ErrorReportValve.invoke(ErrorReportValve.java:103)
at org.apache.catalina.core.StandardEngineValve.invoke(StandardEngineValve.java:109)
at org.apache.catalina.connector.CoyoteAdapter.service(CoyoteAdapter.java:293)
at org.apache.coyote.http11.Http11Processor.process(Http11Processor.java:861)
at org.apache.coyote.http11.Http11Protocol$Http11ConnectionHandler.process(Http11Protocol.java:606)
at org.apache.tomcat.util.net.JIoEndpoint$Worker.run(JIoEndpoint.java:489)
at java.lang.Thread.run(Thread.java:662)
I have the above error when I run the my application, am fetching data from database to jsp using dao, I don't know why am getting this error. Need help. My jsp and DAO code is below
My jsp file listuser.jsp
<%# page language="java" contentType="text/html; charset=EUC-KR" pageEncoding="EUC-KR"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%#page errorPage="error.jsp" %>
<!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=EUC-KR">
<title>Show All Users</title>
</head>
<body>
<table border=1>
<thead>
<tr>
<th>User Id</th>
<th>First Name</th>
<th>Last Name</th>
<th>DOB</th>
<th>Email</th>
<th colspan=2>Action</th>
</tr>
</thead>
<tbody>
<c:forEach items="${users}" var="user">
<tr>
<td><c:out value="${user.userid}" /></td>
<td><c:out value="${user.firstName}" /></td>
<td><c:out value="${user.lastName}" /></td>
<td><fmt:formatDate pattern="yyyy-MMM-dd" value="${user.dob}" /></td>
<td><c:out value="${user.email}" /></td>
<td>Update</td>
<td>Delete</td>
</tr>
</c:forEach>
</tbody>
</table>
<p>Add User</p>
My UserDAO.java
package com.nic.sample.dao;
public class UserDAO {
private Connection connection;
public UserDAO() {
connection = DbUtil.getConnection();
}
public void addUser(User user) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("insert into users(firstname,lastname,dob,email) values (?, ?, ?, ? )");
// Parameters start with 1
preparedStatement.setString(1, user.getFirstName());
preparedStatement.setString(2, user.getLastName());
preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
preparedStatement.setString(4, user.getEmail());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void deleteUser(int userId) {
try {
PreparedStatement preparedStatement = connection.prepareStatement("delete from users where userId=?");
// Parameters start with 1
preparedStatement.setInt(1, userId);
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public void updateUser(User user) {
try {
PreparedStatement preparedStatement = connection
.prepareStatement("update users set firstname=?, lastname=?, dob=?, email=?" +
"where userid=?");
// Parameters start with 1
preparedStatement.setString(1, user.getFirstName());
preparedStatement.setString(2, user.getLastName());
preparedStatement.setDate(3, new java.sql.Date(user.getDob().getTime()));
preparedStatement.setString(4, user.getEmail());
preparedStatement.setInt(5, user.getUserid());
preparedStatement.executeUpdate();
} catch (SQLException e) {
e.printStackTrace();
}
}
public List<User> getAllUsers() {
List<User> users = new ArrayList<User>();
try {
Statement statement = connection.createStatement();
ResultSet rs = statement.executeQuery("select * from users");
while (rs.next()) {
User user = new User();
user.setUserid(rs.getInt("userid"));
user.setFirstName(rs.getString("firstName"));
user.setLastName(rs.getString("lastName"));
user.setDob(rs.getDate("dob"));
user.setEmail(rs.getString("email"));
users.add(user);
}
} catch (SQLException e) {
e.printStackTrace();
}
return users;
}
public User getUserById(int userId) {
User user = new User();
try {
PreparedStatement preparedStatement = connection.
prepareStatement("select * from users where userid=?");
preparedStatement.setInt(1, userId);
ResultSet rs = preparedStatement.executeQuery();
if (rs.next()) {
user.setUserid(rs.getInt("userid"));
user.setFirstName(rs.getString("firstName"));
user.setLastName(rs.getString("lastName"));
user.setDob(rs.getDate("dob"));
user.setEmail(rs.getString("email"));
}
} catch (SQLException e) {
e.printStackTrace();
}
return user;
}
}
Please can anyone help me out, I am really stuck here...
In your getAllUsers method connection.createStatement(); may be connection is null.
Everything fine otherthan that .Debug it to make sure ..
And finally follow this link too
http://www.vogella.com/articles/EclipseDebugging/article.html