Type of object returned by an input from a web page
I'm attempting to upload a file into a jsp and then use the file in some other code. My problem is that it comes into the servlet as an Object via the request.getAttribute() call so I don't know what to cast it to.
I have this code so far to try and test what it is but I'm getting a NullPointerException.
test.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Input Test</title>
</head>
<body>
<form action="InputServlet" method="POST">
<input type="file" name="file1">
<input type="submit" value="submit">
</form>
</body>
</html>
开发者_运维技巧
inputservlet.java
public class InputServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println(request.getAttribute("file1").getClass());
}
}
Is my understanding of whats going on flawed or am I just coding it up wrong?
Also I'm expecting the type to be Object so if anyone knows what I should cast it too that would be very helpful as well.
It's likely null because it concerns a brand new and different request
. You probably have sent a redirect to the servlet instead of a forward?
Regardless, you should not process the file upload in a JSP file, but in a real servlet class. It's otherwise recipe for trouble since it's a view technology.
See also:
- How to retrieve uploaded image and save to a file with JSP?
- Apache Commons FileUpload user guide
Update: as per your code update, this won't work. You need to set form's enctype
to multipart/form-data
and use Commons FileUpload to process it in servlet. Also see the given links.
To the point, the multipart/form-data
encoding is not supported by the Servlet API prior to 3.0 and the input values are not available by request.getParameter()
and consorts. The use of request.getAttribute()
here is a misconception. There it is not for. You would need to parse the request.getInputStream()
yourself as per RFC2388. You would however like to use Apache Commons FileUpload for this instead of reinventing and maintaining a wheel for years. Apache Commons already did it for you, take benefit of it.
If you're already on Servlet 3.0 (Glassfish v3), then you can use the builtin request.getParts()
to gather the items. Most servletcontainers will use Commons FileUpload under the hoods, you only don't see it in the /WEB-INF/lib
or the imports, if that disturbs you for some reason.
See also:
- How to get the file name for
<input type="file">
in jsp - How to upload an image using JSP -Servlet and EJB 3.0
精彩评论