Getting data from jsp to Servlet [duplicate] - java

public class Relay extends HttpServlet {
#Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String command = request.getParameter("command");
RequestDispatcher rd =request.getRequestDispatcher(command);
rd.forward(request, response);
System.out.println("Request forwarded to " + command + " servlet");
}
}
This is my Relay servlet, I'm sending data from this form
<form action="Relay" method="POST" enctype="multipart/form-data"> /
<input type="hidden" name="command" value="AddProduct" />
<input type="text" name="pname" value="" />
<input name="" type="submit" value="Add Product">
</form>
It is throwing a java.lang.NullPointerException.
But works fine when I remove this:
enctype="multipart/form-data"

Why do you need to add it then? Just keep it out.
If you need it in order to upload a file by <input type="file"> which you intend to add later on, then you should put #MultipartConfig annotation on your servlet, so that request.getParameter() will work and that all uploaded files can be retrieved by request.getPart().
#WebServlet("/Relay")
#MultipartConfig
public class Relay extends HttpServlet {
// ...
}
See also:
How to upload files to server using JSP/Servlet?

Parameters encoded with multipart/form-data are sent in POST body - not as regular request parameters, therefore can't be read using request.getParamter(...).
Check out Commons file upload package for multipart requests processing.

I am including this just for additional information for troubleshooting.
if you are stuck and want to know about what all parameters are coming through multipart request you can print all parameters using following code.
MultipartRequest multi = <Your code to retrieve multipart request goes here. Sorry but can not post code as I use proprietary APIs>
Enumeration en1 = multi.getParameterNames();
while (en1.hasMoreElements()) {
String strParamName = (String)en1.nextElement();
String[] strParamValues = multi.getParameterValues(strParamName);
for (int i = 0; i < strParamValues.length; i++) {
System.out.println(strParamName + "=" + strParamValues[i]);
}
}

remove the form tag and use
echo <?php form_open_multipart('Controller/function');
I got the same issue whenever I use enctype="multipart/form-data"
I didn't get the file name and when I remove that it was working fine
try it it worked for me

Related

Does JAX-RS Support Input Streaming?

Given the following HTML:
<form action="upload" method="post" enctype="multipart/form-data">
Select a file : <input type="file" name="file" size="45" />
<input type="submit" value="Upload" />
</form>
If I have a JAX-RS method that starts with:
#POST
#Path("upload")
#Consumes(MediaType.MULTIPART_FORM_DATA)
public Response upload(
#FormParam("file") InputStream uploadedInputStream) {
...
}
Is uploadedInputStream going to be streamed as part of the Java EE API Specification, not implementation specific? That is I can upload a 1TB file without blowing up the heap?
I can't seem to find anything that shows it is standard, even support for #Consumes(MediaType.MULTIPART_FORM_DATA) is implementation specific.
The only thing I can think of to make it work across app servers is to use a servlet like the following that will display the number of bytes uploaded.
#WebServlet("/upload")
#MultipartConfig
public class ImportServlet extends HttpServlet {
#Override
protected void doPost(final HttpServletRequest req,
final HttpServletResponse resp) throws ServletException,
IOException {
int c = 0;
InputStream cis = req.getPart("file").getInputStream();
int ch = cis.read();
while (ch != -1) {
++c;
ch = cis.read();
}
cis.close();
resp.getWriter().print(c);
}
}
As far as I know, multipart data streams are loaded off to disk and then wrapped for you. Can you rather user direct PUT requests? It will give you direct access to the input stream from the client. I tried this with gigabytes of data without problems.
If someone knows better, please correct me.

Send image to mySQL with servlet, ajax, jquery [duplicate]

This question already has answers here:
How can I upload files to a server using JSP/Servlet and Ajax?
(4 answers)
Closed 7 years ago.
Trying to upload a file to my servlet without page refresh with ajax.
Been stuck at this for some days now, and just can't let it go.
my form:
<form method="POST" id="changeImage2" enctype="multipart/form-data">
<input type="file" name="photo" /> <br>
<input type="button" value="Change Picture" id="changeImage1">
</form>
my servlet:
#MultipartConfig
public class changeImage extends HttpServlet{
/**
*
*/
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
Part filePart = req.getPart("photo");
Object email = req.getSession().getAttribute("email");
Object name = req.getSession().getAttribute("name");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection myConn = DriverManager.getConnection("", "", "");
PreparedStatement ps = myConn.prepareStatement("update user set profilePicture=? where email=? and name=?");
ps.setBlob(1, filePart.getInputStream());
ps.setString(2, (String) email);
ps.setString(3, (String) name);
ps.executeUpdate();
} catch (Exception e){
e.printStackTrace();
}
}
}
my ajax/jquery:
<script>
$(document).ready(function() {
$('#changeImage1').click(function() {
var dataForm = $('#changeImage2').serialize();
$.ajax({
type : 'POST',
url : 'changeImage',
data : dataForm,
success : function(data) {
$('#gg1').text(data);
},
error : function() {
$('#gg1').text("Fail");
},
});
});
});
</script>
When running this I get the error:
SEVERE: Servlet.service() for servlet [changeImage] in context with
path [/Event] threw exception
[org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException:
the request doesn't contain a multipart/form-data or
multipart/form-data stream, content type header is null] with root
cause
org.apache.tomcat.util.http.fileupload.FileUploadBase$InvalidContentTypeException:
the request doesn't contain a multipart/form-data or
multipart/form-data stream, content type header is null
I tried use another form and do without the ajax/jquery:
<form action="changeImage" method="post" enctype="multipart/form-data">
<input type="file" name="file" />
<input type="submit" value="Change Picture" />
</form>
With this it works. So I'm guessing the JDBC and Servlet is sat up properly. And that I'm not using Ajax/Jquery properly.
In your code you write:
ps.setBlob(5, (Blob) InputStream);
According to javadoc for PreparedStatement this int, 5 is the parameter index. As the error is stating you only have 3 parameters.
You need to change this to 3? - looking at your SQL statement I think you may have forgotten you have copied and pasted from somewhere and haven't yet edited it.
These lines are the problem, you can't use Part object as Blob or InputStream. A cast exception should happen there.
Part filePart = req.getPart("photo");
Part InputStream = filePart; //this line is not needed at all
ps.setBlob(1, (Blob) InputStream);
Try something like this
ps.setBlob(1, filePart.getInputStream());
or
ps.setBinaryStream(1, filePart.getInputStream());

java upload servlet get additional form data

I have a java upload servlet and jsp form. the upload portion is working fine but i cannot get the regular form values in the upload servlet java code so that i can use these. Right now, I am trying to get the form data with request.getParameter("name"); but it is return null values. I am able to get the field values using item.getFieldName() and item.getFieldValue() but these are not really usable in additional processes in the item.iterator but these are not usable in further operations. For example, I want to pull in the email address field value so that I can send an email at the end of my upload servlet. I cannot use this data if I cannot make it into a string or variable which is where I am having issues. Any advice?
jsp file:
jsp form:
<form method="post" action="UploadServlet" enctype="multipart/form-data">
Username: <input type="text" name="username" value="username"/><br>
E-mail: <input type="email" name="email" autocomplete="on"><br>
<br>
Select file to upload:<input type="file" name="uploadFile" /><br>
<input type="submit" value="Upload" />
</form>
Java file:
UploadServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String id = request.getParameter("username");
System.out.println(id); //returns null value
String password = request.getParameter("email");
System.out.println(password);//returns null value
For using file upload you get value only in form field.
request method not work in file upload
if (ServletFileUpload.isMultipartContent(request)) {
List<FileItem> multipart = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : multipart) {
if (!item.isFormField();
{
//Your upload file code.
}
if (item.isFormField()) {
if (item.getFieldName().equals("username")) {
String id = item.getString();
}else if (item.getFieldName().equals("email")) {
String password = item.getString();
}
}

Doing an ActionRequest call from JS/jQuery/Ajax in Spring MVC

I'm trying to redirect to a portlet with specific parameters from JavaScript. I take parameters based on which link the user clicks (this part is OK, I get all the data I need), and afterwards construct an URL which I try to get with simple JS window.location..
My Controller:
#RenderMapping
public String view(Model model){
model.addAttribute("some", "stuff");
return "myPortlet/view";
}
#ActionMapping(params = "action=importantAction")
public void doAction(ActionRequest request, ActionResponse response){
String foo = request.getParameter("one");
String bar = request.getParameter("two");
System.out.println("Got " + one + " & " + two);
}
My JS:
function myFunction(one_val, two_val){
window.location = "http://www.my.url.com/nameOfMyPortlet?one=" + one_val +
+ "&two=" + two_val + "&action=importantAction";
}
This redirects to the correct page, however the action parameter keeps getting ignored and the whole doAction method doesn't get executed.
How to pass the action parameter to the target portlet from JavaScript?
I'm using Liferay & Spring MVC..
Thanks!
Did you try creating action URL using below way ?
var portletURL = new Liferay.PortletURL('ACTION_PHASE');
portletURL.setWindowState("maximized");
In portletURL you can set your desired parameter for calling your action.
Below link for reference
http://www.liferay.com/web/eduardo.lundgren/blog/-/blogs/liferay-portleturl-in-javascript
I've managed to find a way how it works - it's very similar to what #Ankit P wrote:
I have created hidden fields for the parameters and then sent the form which creates the URL:
JSP:
<liferay-portlet:actionURL var="link">
<liferay-portlet:param name="action" value="importantAction"/>
</liferay-portlet:actionURL>
<form action="${link}" method="POST" name="the-form" id="the-form">
<input type="hidden" value="" name="one" id="one"/>
<input type="hidden" value="" name="two" id="two"/>
</form>
JS:
function myFunction(one_val, two_val) {
document.getElementById("one").value = one_val;
document.getElementById("two").value = two_val;
document.getElementById("the-form").submit();
}
Controller stays the same. To use #ActionMapping you have to use POST method.

after enctype="multipart/form-data" request not working

public class Relay extends HttpServlet {
#Override
public void service(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String command = request.getParameter("command");
RequestDispatcher rd =request.getRequestDispatcher(command);
rd.forward(request, response);
System.out.println("Request forwarded to " + command + " servlet");
}
}
This is my Relay servlet, I'm sending data from this form
<form action="Relay" method="POST" enctype="multipart/form-data"> /
<input type="hidden" name="command" value="AddProduct" />
<input type="text" name="pname" value="" />
<input name="" type="submit" value="Add Product">
</form>
It is throwing a java.lang.NullPointerException.
But works fine when I remove this:
enctype="multipart/form-data"
Why do you need to add it then? Just keep it out.
If you need it in order to upload a file by <input type="file"> which you intend to add later on, then you should put #MultipartConfig annotation on your servlet, so that request.getParameter() will work and that all uploaded files can be retrieved by request.getPart().
#WebServlet("/Relay")
#MultipartConfig
public class Relay extends HttpServlet {
// ...
}
See also:
How to upload files to server using JSP/Servlet?
Parameters encoded with multipart/form-data are sent in POST body - not as regular request parameters, therefore can't be read using request.getParamter(...).
Check out Commons file upload package for multipart requests processing.
I am including this just for additional information for troubleshooting.
if you are stuck and want to know about what all parameters are coming through multipart request you can print all parameters using following code.
MultipartRequest multi = <Your code to retrieve multipart request goes here. Sorry but can not post code as I use proprietary APIs>
Enumeration en1 = multi.getParameterNames();
while (en1.hasMoreElements()) {
String strParamName = (String)en1.nextElement();
String[] strParamValues = multi.getParameterValues(strParamName);
for (int i = 0; i < strParamValues.length; i++) {
System.out.println(strParamName + "=" + strParamValues[i]);
}
}
remove the form tag and use
echo <?php form_open_multipart('Controller/function');
I got the same issue whenever I use enctype="multipart/form-data"
I didn't get the file name and when I remove that it was working fine
try it it worked for me

Categories

Resources