How to get POST form data using VERTX handlers? - java

I am able to get the form data using the buffer handler, but it is a void function and I cannot return the form data values. Have about 4-7 forms total, I don't want to end up writing the same handler over and over because the default function is void.
html:
<!DOCTYPE html>
<html>
<head><title>Login Page</title></head>
<body>
activate user
<br/>
log in
<br/>
<form id='login' action='/login' method='post'>
<fieldset >
<legend>Login</legend>
<input type='hidden' name='submitted' id='submitted' value='1'/>
<label for='username' >UserName: </label>
<input type='text' name='username' id='username' maxlength="50"/>
<label for='password' >Password: </label>
<input type='password' name='password' id='password' maxlength="50"/>
<input type='submit' name='Submit' value='Submit' />
</fieldset>
</form>
</body>
</html>
java:
import org.jboss.netty.handler.codec.http.QueryStringDecoder;
import org.vertx.java.core.Handler;
import org.vertx.java.core.Vertx;
import org.vertx.java.core.buffer.Buffer;
import org.vertx.java.core.http.HttpServer;
import org.vertx.java.core.http.HttpServerRequest;
import org.vertx.java.core.http.RouteMatcher;
import org.vertx.java.deploy.Verticle;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
/**
* Created by IntelliJ IDEA.
* User: yao
* Date: 1/17/13
* Time: 2:22 PM
*/
public class Main extends Verticle
{
#Override
public void start() throws Exception
{
System.out.println("starting the vertx stuff");
final String host = "localhost";
final String port = "8181";
Vertx vertx = Vertx.newVertx();
HttpServer httpServer = vertx.createHttpServer();
...
httpServer.requestHandler(new Handler<HttpServerRequest>()
{
public void handle(HttpServerRequest req)
{
String path = req.path;
/* start mapping of page urls*/
// redirect user to the login page
if (path.equals("/"))
{
req.response.sendFile(dir + "html/loginPage.html");
}
...
/* end mapping of page urls*/
/* start mapping of form urls */
// login
else if (path.equals(login))
{
mainLogin();
getFormData(req);
}
...
/* end mapping of form urls */
/* all other pages */
else
{
req.response.end("404 - page no exist");
}
}
});
System.out.println("vertx listening to: " + host + " " + port);
httpServer.listen(Integer.valueOf(port), host);
}
...
private void getFormData(final HttpServerRequest req)
{
req.bodyHandler(new Handler<Buffer>()
{
#Override
public void handle(Buffer buff)
{
String contentType = req.headers().get("Content-Type");
if ("application/x-www-form-urlencoded".equals(contentType))
{
QueryStringDecoder qsd = new QueryStringDecoder(buff.toString(), false);
Map<String, List<String>> params = qsd.getParameters();
System.out.println(params);
}
}
});
}
}

Nowadays BodyHandler is provided by vertx, using it isExpectMultipart will be set to true and you will be able to read form attributes as
request.getFormAttribute("username");//to read input named username.
just add this line before your actual handler:
router.route().handler(BodyHandler.create());

For java this worked perfectly:
request.expectMultiPart(true);
request.endHandler(req->{
String text = request.formAttributes().get("bigtext");
//got it here
//do something ...
});

what i did in the end is basically this:
do the ajax call using post, the data from the form needs to be serialized.
$.ajax
({
type: "POST",
url: "/login",
data: $('#frm_login').serialize(),
success: function(data)
...
in the backend, vertx receives this data as a buffer. rest is to parse the buffer by splitting by "&" and "=".
Map<String, String> params = new HashMap<String, String>();
String[] paramSplits = buffer.toString().split("&");
String[] valueSplits;
if (paramSplits.length > 1)
{
for (String param : paramSplits)
{
valueSplits = param.split("=");
if (valueSplits.length > 1)
{
// add this check to handle empty phone number fields
params.put(decode(valueSplits[0]), decode(valueSplits[1]));
}
}
}
hope this will help others!

This can be done using the formAttributes on the http request. Here is an example in scala
req.expectMultiPart(true) //Will expect a form
req.endHandler({
req.formAttributes() //This is used to access form attributes
//some code with attributes
})
Reference: http://vertx.io/core_manual_java.html#handling-multipart-form-attributes

Related

Pass value from Angular 5 to Java REST API using http put, line 0:-1 no viable alternative at input '<EOF>

I'm facing an issue to try learn the full cycle of web following of data, i passed value from java jersay REST-API to angular 5, but i wanna pass text from angular to backend to execute some query and return the result again, i got confused between #FormParam and many things,
bellow my code,
File-list.service.ts
import { Injectable } from '#angular/core';
import { Http, Response, Headers, RequestOptions } from '#angular/http';
import { Observable } from 'rxjs/Observable';
import { HttpClient } from '#angular/common/http';
import { FileList } from './file-list';
import 'rxjs/add/operator/catch';
import 'rxjs/add/operator/map'
save(fileList: FileList): Observable<Response> {
console.log('Saving person ' + JSON.stringify(fileList));
return this.http.put('http://localhost:8080/SWBackend/jaxrs/Person/Save', JSON.stringify(fileList), { headers: this.getHeaders()});}
List.component.html
<form (click)="save()" method="POST" action="http://localhost:8080/SWBackend/jaxrs/Person/Save">
<p>
Path : <input type="text" name="pathUrl" />
</p>
Press to show the files
<input type="submit" value="Add User" />
<input type="hidden" name="_method" value="PUT">
</form>
Java file.java
#PUT
#Path("Save")
#Consumes({ "application/xml", "application/json" })
#Produces("application/json")
public Response saveEmp(FilesList pathUrl) {
System.out.println("Reach Save Emp");
return Response.ok().header("Access-Control-Allow-Origin", "*").build();
}
i'm getting this error:
line 0:-1 no viable alternative at input ''
i don't know if my way is right or no, but i was trying since week ago,
thank you all.
Try this instead,
in your form remove this:
<form (click)="save()" method="POST" action="http://localhost:8080/SWBackend/jaxrs/Person/Save">
Use ReactiveFormsModule for your forms, using FormGroup and FormControl.
Then in your component, when you submit the form, it will invoke the function to call your service which in return will communicate with your java controller.
The Component should have the function that is associated with your formGroup in your template(html).
The function should then call your service such as: this.service.save(fileList);
https://angular.io/guide/reactive-forms
ex:
<form [formGroup]="fileListForm" (ngSubmit)="save(fileListForm.value)">
<input type="text" formControlName="fileListNameControl">
</form>
Component:
private fileListForm: FormGroup;
private fileListNameControl: FormControl;
ngOninit(){
this.fileListForm = new FormGroup({
fileListNameControl: new FormControl("", Validators.required)
});
}
save(form: any){
// get your form values here and then call service
this.fileLIstService.save('your value');
}
** Make sure to import ReactiveFormsModule via #angular/forms in your module.

servlet, tracking session with hidden parameters

I have a trouble with servlet coding and I don't know how to solve it.
I was trying to track a session (using TomCat web server) using only hidden parameters.
In this example there are name, surname and email as parameters. My idea was to ask the client just one parameter per time and send it to him as hidden parameter (iteratively).
If I start just one session (since when the client sends the first parameter to when the client sends the last parameter) my servlet works fine.
The problem is when I start another session:
when i send to to server the surname (a different value from the revious session) the server gives me an url where there is two times the hidden parameter "surname" with the value of the current surname and the value of the previous one's session surname.
Here is my servlet class:
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
public class HiddenParamServlet extends HttpServlet {
private final String[] PARAMS = { "name", "surname", "e-mail" };
private Map<String, String> hiddenParameters;
#Override
public void init() {
hiddenParameters = new HashMap<String, String>();
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// control the last parameter added by the client
List<String> clientParameters = Collections.list(request.getParameterNames());
// checks if the client already sent all the parameters
if(clientParameters.size() == 3) {
// start the html document
out.println("<html><head><title>Session finished</title></head>");
out.println("<body><h1>Session succesfully completed</h1></body>");
out.println("</html>");
// end the html
out.close();
hiddenParameters.clear();
}
else {
String lastParam = clientParameters.get(clientParameters.size() -1);
//memorizing the last param sent by the client
String value = request.getParameter(lastParam);
hiddenParameters.put(lastParam, value);
// starts the HTML document
out.println("<html>");
out.println("<head><title>Tracking session with hidden parameters</title></head>");
out.println("<body>");
out.println("<form method=\"get\" action=\"/DirectoryDiSaluto/HiddenParamServlet\">");
out.println("<p>");
//write the next parameter to ask to the client
out.println("<label>Insert "+PARAMS[clientParameters.size()]+":");
// write the hidden parameters of the server
for(String key : hiddenParameters.keySet()) {
out.println("<input type=\"hidden\" name=\""
+key+"\" value=\""+hiddenParameters.get(key)+"\" />");
}
out.println("<input type=\"text\" name=\""+PARAMS[clientParameters.size()]+"\" />");
out.println("<input type=\"submit\" value=\"Submit\" />");
out.println("</label>");
out.println("</p>");
out.println("</form>");
out.println("</body>");
out.println("</html>");
// end the html
out.close();
}
}
}
Here is the html page where all starts:
<html>
<head>
<title>Tracking session with hidden parameters</title>
</head>
<body>
<form method="get" action="/DirectoryDiSaluto/HiddenParamServlet">
<p>
<label>Insert name:
<input type="text" name="name"/>
<input type="submit" value="Submit" />
</label>
</p>
</form>
</body>
</html>
I can't understand where the problem is. Can you help me? Thanks so much!
hiddenParameters is guilty of this behaviour, because of its bad scope. Have a look at this answer for more explanations.

Dynamically populate a dropdown box with Jquery and Java

Please bear with me as I am new to jQuery, and JEE and am not a programmer :-)
I have followed a number of tutorials on how to dynamically populate a dropdown box; however I can not get it to work.
I want to select a State and populate the Region drop down based on that selection (each State is made up of Regions).
My issue is with the call to the java and return of values.
So far I have (mashed up from a number of tutorials) the following:
HTML
<div class="row">
<div class="col-md-6">
<div class="form-select-group">
<label for="selectState">Select State:</label>
<select class="form-control" id="selectState">
<option value="" disabled selected>Select your State</option>
<option>ACT</option>
<option>NSW</option>
<option>NT</option>
<option>QLD</option>
<option>SA</option>
<option>TAS</option>
<option>VIC</option>
<option>WA</option>
</select>
</div>
</div>
<div class="col-md-6">
<div class="form-select-group">
<label for="selectRegion">Select Region:</label>
<select class="form-control" id="selectRegion">
<option>Please select your State first</option>
</select>
</div>
</div>
</div>
jQUERY
$(document).ready(function(){
$('#selectState').on('change', function() {
//do something here
//alert($("#accountName").val());
$.ajax({
type: "POST",
url: "RegionView",
cache: false,
data: $(selectState).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text(data);
}
}).done(function(response) {
// Clear options
$("#selectRegion").find("option").remove();
// Loop through JSON response
$.each(response, function (index, value) {
$('#selectRegion').append($('<option>', { value: value.name }, '</option>'));
})
});
});
});
JAVA
package client;
import java.io.IOException;
/**
* The purpose of this View is to return a list of Regions associated with a selected State.
*/
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import server.MySQLConnection;
#WebServlet("/RegionView")
public class RegionView extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String state = request.getParameter("selectState"); // From bootstrap
response.getWriter().write("Here " + state);
MySQLConnection.getConnection();
List<String> listRegions = MySQLConnection.listGroupRegions(state);
if (listRegions == null || listRegions.isEmpty()) {
response.getWriter().write("Please select a State");
}else{
response.getWriter().write("State found");
request.setAttribute("selectRegion", listRegions);
}
}
}
This code answers my question as it allows me to dynamically populate a dropdown box with Jquery and Java:
Java:
#WebServlet("/RegionView")
public class RegionView extends HttpServlet {
private static final long serialVersionUID = 1L;
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String state = request.getParameter("selectState"); // From bootstrap
MySQLConnection.getConnection();
List<String> listRegions = MySQLConnection.listGroupRegions(state);
if (listRegions == null || listRegions.isEmpty()) {
response.getWriter().write("Please select a State");
}else{
String json = new Gson().toJson(listRegions);
response.setContentType("application/json");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(json);
}
}
}
JSON:
$(document).ready(function(){
$('#selectState').on('change', function() {
//do something here
//alert($("#accountName").val());
$.ajax({
type: "POST",
url: "RegionView",
cache: false,
data: $(selectState).serialize(),
success: function(data){
$('#ajaxGetUserServletResponse').text(data);
}
}).done(function(responseJson) {
dataType: "json",
// Clear options
$("#selectRegion").find("option").remove();
// Loop through JSON response
$.each(responseJson, function(key, value) {
$('<option>').val(key).text(value).appendTo($("#selectRegion"));
});
});
});
});

How to bind dynamic form fields to a HashSet in Play! with Java?

I am fairly new to Play! and I am writing code for a simple dynamic form. I have two model classes: Extension and ExtensionPair. An Extension can contain many ExtensionPairs, so I want to be able to add as many ExtensionPairs as I want and submit the form and bind it to an Extension Java object after it's submitted.
My code works fine when I use an ArrayList for the ExtensionPairs (see code below). However, if I try to use a HashSet instead, I get:
[InvalidPropertyException: Invalid property 'objectExtensionPairs[0]' of bean class
[models.Extension]: Illegal attempt to get property 'objectExtensionPairs' threw
exception; nested exception is org.springframework.beans.InvalidPropertyException:
Invalid property 'objectExtensionPairs[0]' of bean class [models.Extension]: Cannot
get element with index 0 from Set of size 0, accessed using
property path 'objectExtensionPairs[0]']
I was looking for some questions in StackOverflow and found this one that pretty much says I can't bind a HashSet with Spring Framework.
Are there any alternatives to use a HashSet and form bindings with Play! and Java?
Please see my code below:
Extension.java:
package models;
import java.util.ArrayList;
public class Extension {
public Extension() {
objectExtensionPairs = new ArrayList<ExtensionPair>();
}
public Extension(String objectExtensionOrganization, String objectExtensionDescription) {
this();
this.objectExtensionOrganization = objectExtensionOrganization;
this.objectExtensionDescription = objectExtensionDescription;
}
// Getters and Setters
private ArrayList<ExtensionPair> objectExtensionPairs;
private String objectExtensionOrganization;
private String objectExtensionDescription;
}
ExtensionPair.java:
package models;
public class ExtensionPair {
public ExtensionPair() {
}
public ExtensionPair(String objectExtensionKey, String objectExtensionValue) {
this.objectExtensionKey = objectExtensionKey;
this.objectExtensionValue = objectExtensionValue;
}
// Getters and Setters
private String objectExtensionKey;
private String objectExtensionValue;
}
I have coded Play! Java templates for both, so that I can create or edit an Extension using a dynamic form with an "Add" and "Remove" button to have as many ExtensionPairs as I want.
extensionPairTemplate.scala.html:
#(extP: ExtensionPair, index: Int = 0)
#extensionPair = #{ if(extP == null) new ExtensionPair("","") else extP }
<script type="text/javascript">
// Some JavaScript code to make the form dynamic (add/remove pairs)
</script>
<div id="epDiv#index.toString()">
objectExtensionKey:
<input type="text" name="objectExtensionPairs[#index.toString()].objectExtensionKey" value="#extensionPair.getObjectExtensionKey()"/>
objectExtensionValue:
<input type="text" name="objectExtensionPairs[#index.toString()].objectExtensionValue" value="#extensionPair.getObjectExtensionValue()" />
<button type="button" id="removeExtensionPairButton#index.toString()" onclick="removeExtensionPairFormElements(#index.toString())">Remove</button>
</div>
extensionTemplate.scala.html:
#(extensionForm: Form[models.Extension], ext: Extension)
#extension = #{ if(ext == null) new Extension("","") else ext }
<script src="#routes.Assets.versioned("javascripts/jquery-1.11.3.min.js")" type="text/javascript"></script>
<script type="text/javascript">
// Some JavaScript code to make the form dynamic (add/remove pairs)
</script>
#helper.form(action = routes.Application.addExtension) {
<div id="extensionDiv">
<fieldSet>
#helper.inputText(extensionForm("objectExtensionOrganization").copy(value=Some(extension.getObjectExtensionOrganization())))
#helper.inputText(extensionForm("objectExtensionDescription").copy(value=Some(extension.getObjectExtensionDescription())))
<div id="extensionPairsDiv">
#if(extension.getObjectExtensionPairs().size() > 0) {
#for((ep,epIndex) <- extension.getObjectExtensionPairs().zipWithIndex) {
#extensionPairTemplate(ep, epIndex)
}
}
</div>
</fieldSet>
<br/>
<button type="button" id="addPair">Add extension pair</button>
<input type="submit" value="Submit"/>
</div>
}
My controller:
// For when the form is submitted (i.e. editing an Extension)
public Result addExtension() {
Form<Extension> formExtension = Form.form(Extension.class).bindFromRequest();
Extension e = formExtension.get();
return ok(extensionTemplate.render(Form.form(Extension.class), e));
}
// For when a new Extension is being created
public Result extensionForm() {
return ok(extensionTemplate.render(Form.form(Extension.class), null));
}
You can always bind your form manually:
Map<String, String[]> formMap = request().body().asFormUrlEncoded();
String myContent = formMap.get("myFormElementName")[0]);

Sending multipart encryption data using dropzone

Here is my index.html:
<%# 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">
<script src="extra/js/jquery-1.10.2.min.js"></script>
<script src="extra/downloads/dropzone.js"></script>
<script>
$(document).ready(function()
{
var myDropzone = new Dropzone("div#my-awesome-dropzone", {url:'UploadServlet'});
Dropzone.autoDiscover = false;
myDropzone.on("addedfile", function(file) {
// Create the remove button
var removeButton = Dropzone.createElement("<button>Remove file</button>");
// Capture the Dropzone instance as closure.
var _this = this;
// Listen to the click event
removeButton.addEventListener("click", function(e) {
// Make sure the button click doesn't submit the form:
e.preventDefault();
e.stopPropagation();
// Remove the file preview.
_this.removeFile(file);
// If you want to the delete the file on the server as well,
// you can do the AJAX request here.
});
// Add the button to the file preview element.
file.previewElement.appendChild(removeButton);
});
$("#button").click(function(){
var source = $("#my-awesome-dropzone").attr("src");
alert(source);
});
});
</script>
<link rel="stylesheet" href="extra/downloads/css/dropzone.css" type="text/css">
<title>Insert title here</title>
</head>
<body>
<form action="UploadServlet" method="post" enctype="multipart/form-data" >
<table id="table">
<tr>
<td> Unique ID : </td>
<td><input type="text" id="unique" name="unique" maxlength="6" required></input></td>
</tr>
<tr>
<td> Name : </td>
<td><input type="text" id="fullname" name="fullname" maxlength="255" required></input></td>
</tr>
<tr>
<td> Age : </td>
<td><input type="text" id="age" name="age" maxlength="255" required></input></td>
</tr>
<tr>
<td> Address : </td>
<td><input type="text" id="address" name="address" maxlength="255" required></input></td>
</tr>
<tr>
<td> Phone_number </td>
<td><input type="text" id="phonenumber" name="phonenumber" maxlength="10" required></input></td>
</tr>
</table>
<div id="my-awesome-dropzone" class="dropzone"></div>
<div>
<input type="submit" value="Submit data and files!"></input>
</div>
</form>
</body>
</html>
And this my servlet:
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package dropzone;
import java.io.File;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.html.HTMLDocument.Iterator;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.FilenameUtils;
import com.oreilly.servlet.multipart.MultipartParser;
import com.oreilly.servlet.multipart.Part;
import com.oreilly.servlet.multipart.FilePart;
public class UploadServlet extends HttpServlet {
private String fileSavePath;
private static final String UPLOAD_DIRECTORY = "upload";
public void init() {
fileSavePath = getServletContext().getRealPath("/") + File.separator + UPLOAD_DIRECTORY;/*save uploaded files to a 'Upload' directory in the web app*/
if (!(new File(fileSavePath)).exists()) {
(new File(fileSavePath)).mkdir(); // creates the directory if it does not exist
}
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
Connection con = null;
List<FileItem> items;
try {
items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request);
for (FileItem item : items) {
if (item.isFormField()) {
// Process regular form field (input type="text|radio|checkbox|etc", select, etc).
String fieldname = item.getFieldName();
String fieldvalue = item.getString();
// ... (do your job here)
} else {
// Process form file field (input type="file").
String fieldname = item.getFieldName();
String filename = FilenameUtils.getName(item.getName());
InputStream filecontent = item.getInputStream();
// ... (do your job here)
}
}
} catch (FileUploadException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
}
/*
String uid = request.getParameter("unique");
String fullname = request.getParameter("fullname");
System.out.println(fullname);
String age = request.getParameter("age");
String address = request.getParameter("address");
String phonenumber = request.getParameter("phonenumber");*/
String path = null;
String message = null;
String resp = "";
int i = 1;
resp += "<br>Here is information about uploaded files.<br>";
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/dropzone", "root", "root");
String sql = "INSERT INTO details(u_id,name,age,address,phonenumber,path) values(?,?,?,?,?,?)";
PreparedStatement statement = con.prepareStatement(sql);
//##########################################################?//
MultipartParser parser = new MultipartParser(request, 1024 * 1024 * 1024); /* file limit size of 1GB*/
Part _part;
while ((_part = parser.readNextPart()) != null) {
if (_part.isFile()) {
FilePart fPart = (FilePart) _part; // get some info about the file
String name = fPart.getFileName();
if (name != null) {
long fileSize = fPart.writeTo(new File(fileSavePath));
resp += i++ + ". " + fPart.getFilePath() + "[" + fileSize / 1024 + " KB]<br>";
} else {
resp = "<br>The user did not upload a file for this part.";
}
}
}// end while
//##################################################################//
statement.setString(1,"uid");
statement.setString(2,"fullname");
statement.setString(3,"age");
statement.setString(4,"address");
statement.setString(5,"phonenumber");
statement.setString(6,"path");
int row = statement.executeUpdate();
if(row>0){
message = "Contact saved";
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
message = "ERROR: " +e.getMessage();
}
finally
{
if(con !=null)
{
try{
con.close();
}
catch(SQLException ex)
{
ex.printStackTrace();
}
}
System.out.println(message);
request.setAttribute("Message",message);
getServletContext().getRequestDispatcher("/index.jsp").forward(request, response);
}
}
}
Here is screenshot of the error:
I want to use the dropzone for uploading images.But if I use multipart/form-data for the form, the fields except the images give null values. I tried using the simple getParameter method. But it doesnt seem to work. Also I tried using Lists but it gives an error. Anyone tried dropzone with jsp?? Help
This is happening because you are not treating the whole form as dropzone but you are treating only the #my-awesome-dropzone div as dropzone .That won't work if you want to submit whole form with the files on one click.
1)In the form tag add an id say id="mydropzone" and class class="dropzone"
<form action="UploadServlet" id="mydropzone" class="dropzone" method="post" enctype="multipart/form-data" >
2)Remove the div from your code which has the id id="my-awesome-dropzone".Then Add a new div to show the files uploaded in drag and drop
<div id="dropzonePreview"></div>
3)add an id to your submit button
<input type="submit" id="sbmtbtn" value="Submit data and files!" />
4)now add this script
<script>
Dropzone.options.mydropzone = {
// url does not has to be written if we have wrote action in the form tag but i have mentioned here just for convenience sake
addRemoveLinks: true,
autoProcessQueue: false, // this is important as you dont want form to be submitted unless you have clicked the submit button
autoDiscover: false,
paramName: 'pic', // this is similar to giving name to the input type file like <input type="file" name="pic" />
previewsContainer: '#dropzonePreview', // we specify on which div id we must show the files
clickable: false, // this tells that the dropzone will not be clickable . we have to do it because v dont want the whole form to be clickable
accept: function(file, done) {
console.log("uploaded");
done();
},
error: function(file, msg){
alert(msg);
},
init: function() {
var myDropzone = this;
//now we will submit the form when the button is clicked
document.getElementById("sbmtbtn").onclick = function(e) {
e.preventDefault(); //this will prevent the default behaviour of submit button because we want dropzone to submit the form
myDropzone.processQueue(); // this will submit your form to the specified action which directs to your jsp upload code
// after this, your whole form will get submitted with all the inputs + your files and the jsp code will remain as usual
//REMEMBER you DON'T have to call ajax or anything by yourself to submit the inputs, dropzone will take care of that
};
} // init end
};
</script>
NOTE :
YOU DO NOT have to write any extra code to make the form submit .
After writing the above code just follow your normal flow to upload
file in jsp like writing the xml and writing the servlet class and fetch all the inputs and files there.
Remember dropzone uses ajax to upload so the form will not be
refreshed when you click submit.
You cannot click on the form to upload files now you have to just
drag the files in the form.

Categories