I am using the example provided by #BalusC in the question. But I am getting an exception
java.lang.IllegalStateException: Unable to process parts as no multi-part configuration has been provided
org.apache.catalina.connector.Request.parseParts(Request.java:2824)
org.apache.catalina.connector.Request.getParts(Request.java:2792)
org.apache.catalina.connector.Request.getPart(Request.java:2961)
org.apache.catalina.connector.RequestFacade.getPart(RequestFacade.java:1105)
com.example.JSPtest.upload.doPost(upload.java:36)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:689)
jakarta.servlet.http.HttpServlet.service(HttpServlet.java:770)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:53)
This is what I have done.
<form action="upload" method="post" enctype="multipart/form-data">
<input type="text" name="description" />
<input type="file" name="file" />
<input type="submit" />
</form>
static String URL = "localhost:3306/";
static String DATABASE_NAME = "DB";
static String USERNAME = "user";
static String PASSWORD = "";
#WebServlet("/upload")
#MultipartConfig(maxFileSize = 16*1024*1024)
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
InputStream fileContent = filePart.getInputStream();
// ... (do your job here)
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + URL + DATABASE_NAME, USERNAME, PASSWORD);
PreparedStatement ps = con.prepareStatement("insert into data(image) values(?)");
ps.setBinaryStream(1, fileContent);
int result = ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
The data column is a blob. Note I have not used servlets as IntelliJ has an issue where it is not finding the java servlet class files.Any help?
Add this to web.xml:
<multipart-config>
<location>/tmp</location>
<max-file-size>20848820</max-file-size>
<max-request-size>418018841</max-request-size>
<file-size-threshold>1048576</file-size-threshold>
</multipart-config>
Related
Below I have a code that should accept a user's uploaded image in the form of an input element and push it to a MySQL Database. I am using Tomcat 9. Why is it not working yet no exceptions are being thrown? Nothing is being pushed to the database and there is no way of telling to what point the code is being executed. Note that I have embedded the class within the jsp file as IntelliJ has issues with separate servlet classes. Also note that the code was influenced by BalusC's answer. If possible, could anyone suggest an alternative code that can be used instead?
<form action="trial4.jsp" method="post" enctype="multipart/form-data">
<input type="text" name="description"/>
<input type="file" name="file"/>
<input type="submit"/>
</form>
static String URL = "localhost:3306/";
static String DATABASE_NAME = "MYDB";
static String USERNAME = "user";
static String PASSWORD = "";
#WebServlet("/upload")
#MultipartConfig
public class UploadServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
String description = request.getParameter("description"); // Retrieves <input type="text" name="description">
Part filePart = request.getPart("file"); // Retrieves <input type="file" name="file">
String fileName = Paths.get(filePart.getSubmittedFileName()).getFileName().toString(); // MSIE fix.
InputStream fileContent = filePart.getInputStream();
// ... (do your job here)
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://" + URL + DATABASE_NAME, USERNAME, PASSWORD);
PreparedStatement ps = con.prepareStatement("insert into data(image) values(?)");
ps.setBinaryStream(1, fileContent);
ps.executeUpdate();
} catch (Exception e) {
e.printStackTrace();
}
}
}
For other people who are facing a similar challenge, there is a repo that has really helped. The repo owner deserves a cup of coffee.
EDIT 03/2022
The documentation provides a good solution, one that is bettered by the fact that it does not involve third party libraries.
I have problems with running the JSP web to register a user to the database, but when running the program with the JBOSS server:
The HTTP POST Method is not supported by this URL
But I don't understand the conflict of the post with the servlet
This is my HTML/JSP code of registrarusuario.jsp that sends with the method post and action "registerUser" to the servlet where the servlet receives with #WebServlet ("/ registerUser")
<section>
<em>{0}</em>
<form action="registerUser" method="post">
<label for="documento">No. Documento: </label><br>
<input type="text" name="documento" id="documento" placeholder="Ingrese si numero de doucmento" required><br>
<label for="nombre">Nombres: </label><br>
<input type="text" name="nombreusuario" id="nombre" placeholder="Ingrese su nombre" required><br>
<label for="apellido"></label><br>
<input type="text" name="apellidousuario" id="apellido" placeholder="Ingrese su apellido" required><br>
<label for="clave"></label><br>
<input type="text" name="claveusuario" id="clave" placeholder="Ingrese su clave" required><br>
<label for="correo"></label><br>
<input type="email" name="correousuario" id="correo" placeholder="Ingrese su correo" required><br>
<label for="celular"></label><br>
<input type="text" name="celularusuario" id="celular" placeholder="Ingrese su numero celular" required><br>
<input type="reset" value="Cancelar"><input type="submit" value="Registrar">
</form>
</section>
This is the code of my Servlet
#WebServlet("/registerUser")
public class RegistraUsuarioServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
String documento = req.getParameter("documento");
String nombreusuario = req.getParameter("nombreusuario").toUpperCase();
String apellidousuario = req.getParameter("apellidousuario").toUpperCase();
String claveusuario = req.getParameter("claveusuario");
String correousuario = req.getParameter("correousuario");
String celularusuario = req.getParameter("celularusuario");
//recoleccion de datos
Usuario usuarioVo =
new Usuario(documento, nombreusuario, apellidousuario, claveusuario, correousuario, celularusuario);
// call DAO layer and save the user object to DB
UsuarioDAO usuarioDAO = new UsuarioDAO();
int rows = usuarioDAO.insertar(usuarioVo);
// prepare an information message for user about the success or failure of the operation
String infoMessage = null;
if(rows==0){
infoMessage="Sorry, an error occurred!";
}
else{
infoMessage="User registered successfully!";
}
// write the message back to the page in client browser\
String page = getHTMLString(req.getServletContext().getRealPath("registrousuario.jsp"), infoMessage);
res.getWriter().write(page);
}
public String getHTMLString(String filePath, String message) throws IOException{
BufferedReader reader = new BufferedReader(new FileReader(filePath));
String line="";
StringBuffer buffer = new StringBuffer();
while((line=reader.readLine())!=null){
buffer.append(line);
}
reader.close();
String page = buffer.toString();
page = MessageFormat.format(page, message);
return page;
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
String page = getHTMLString(req.getServletContext().getRealPath("registrousuario.jsp"), "");
resp.getWriter().write(page);
}
}
XML web.xml file code
<?xml version="1.0" encoding="UTF-8"?>
<web-app 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-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>RegistraUsuarioServlet</servlet-name>
<servlet-class>cartech.com.cartech.controlador.RegistraUsuarioServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistraUsuarioServlet</servlet-name>
<url-pattern>/registerUser</url-pattern>
</servlet-mapping>
</web-app>
Thanks for your attention
I am from the Spanish community sorry for my English
HTML form
<html>
<!--// This the client html page that receive data and uploads it.>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<body>
<center>
<h1>Task It User profile page</h1><br></br>
<form action="Upload" method="post" enctype="multipart/form-data">
<table border="0">
<tr>
<td>First Name: </td>
<td><input type="text" name="firstName" size="50"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastName" size="50"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="50"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Servlet
package net.codejava.upload;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet("/Upload")
#MultipartConfig(maxFileSize = 16177215) // upload file's size up to 16MB
public class FileUpload extends HttpServlet {
// database connection settings
private String dbURL = "jdbc:mysql://localhost:3306/appdb";
private String dbUser = "root";
private String dbPass = "asdf";
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
// ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/message.jsp").forward(request, response);
}
}
}
The second code is the servlet code that i am trying to use to store data from client into the appdb
javax.servlet.ServletException: The request content-type is not a multipart/form-data is the error that i am getting.
I am very new this so if there is a trivial mistake, still answer the question
I have problem accessing database with servlet java. I want to add users with an html registration form.
this is the html:
<form name="registration-form" action="RegisterUser" method="post">
<div class="form-group has-feedback">
<label class="control-label">Inserisci nome*</label>
<input type="text" class="form-control" name="name" id="inputName" placeholder="Nome">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Inserisci cognome*</label>
<input type="text" class="form-control" name="surname" id="inputLastname" placeholder="Cognome">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Inserisci email*</label>
<input type="email" class="form-control" name="email" id="inputEmail" placeholder="Email">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Inserisci password (compresa tra 6 e 30 caratteri)*</label>
<input type="password" class="form-control" name="password" id="inputFirstPassword" placeholder="Password">
<span class="glyphicon form-control-feedback"></span>
</div>
<div class="form-group has-feedback">
<label class="control-label">Reinserisci password*</label>
<input type="password" class="form-control" id="inputSecondPassword" placeholder="Password">
<span class="glyphicon form-control-feedback"></span>
</div>
<button id="submitBtn" class="btn btn-lg btn-primary btn-block" >Registrati!</button>
</form>
This is the java class (InsertUser.java):
import java.sql.*;
public class InsertUser {
public static void main(String name, String surname, String email, String password) {
PreparedStatement insert = null;
String queryString = "INSERT INTO Utente(Nome, "
+ "Cognome, Email, Password) VALUES (?, ?, ?, ?)";
Connection conn = null;
try {
new com.mysql.jdbc.Driver();
Class.forName("com.mysql.jdbc.Driver").newInstance();
//Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String connectionUrl = "jdbc:mysql://localhost:3306/NoteDB";
String connectionUser = "root";
// String connectionPassword = "root";
conn = DriverManager.getConnection(connectionUrl, connectionUser, "");
conn.setAutoCommit(false);
insert = conn.prepareStatement(queryString);
insert.setString(1, name);
insert.setString(2, surname);
insert.setString(3, email);
insert.setString(4, password);
insert.executeUpdate();
conn.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
try { if (conn != null) conn.close(); } catch (SQLException e) { e.printStackTrace(); }
}
}
This is the servlet (RegisterUser.java)
import java.io.IOException;
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 RegisterUser
*/
#WebServlet("/RegisterUser")
public class RegisterUser extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public RegisterUser() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String name = request.getParameter("name");
String surname = request.getParameter("surname");
String email = request.getParameter("email");
String password = request.getParameter("password");
//InsertUser myUser = new InsertUser();
InsertUser.main(name, surname, email, password);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
This is the error I get:
error page
I'm sorry that is a long question, but I am in despair :( Thanks everyone!
EDIT: in this picture you can see the mysql-connector.jar: mysqlconnector
Remove this line conn.setAutoCommit(false);
As Ramanlfc mentioned, you have to add mysql driver to your classpath.
You can do it natively via your ide, or use build managers, like maven, gradle or ant.
In maven, your pom.xml would look like:
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>your.app</groupId>
<artifactId>mysql-test</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.38</version>
</dependency>
</dependencies>
This question already has answers here:
Http Servlet request lose params from POST body after read it once
(13 answers)
Closed 7 years ago.
I have a jsp page with a form. After submitting it is calling a httpservlet class. But all getParamter() operations are returning null. What am I doing wrong?
JSP
<form action="GatherController" method="post">
<input type='text' name="a"/>
<input type='date' name="b" />
...
<input type="submit" />
</form>
Servlet
#WebServlet(name = "GatherController", urlPatterns = { "/GatherController" })
public class GatherController extends HttpServlet {
...
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String a = request.getParameter("a");
System.out.println(a);
...
}
}
Edit
-I am using Tomcat v8.0
-doPost(...) method is executed, I am getting an output with System.out.println(a); which is null
I have no enough reputation to put comments, so I put it as answer if you don't mind.
Please make sure that you don't call other methods on httpServletRequest before, like getReader() or getInputStream(). You can't access your post parameters after these calls.
<form action="GatherController" method="post"><input type="text" name="a"/>
Please use double quotes,it might work
<html>
<h1>Register</h1><br>
<body>
<form name="userRegistration" method="post">
<input type="text" name="firstname" class="textbox" required/>
<input type="text" name="lastname" class="textbox" required/>
<input type="text" name="email" class="textbox" required/>
</form>
</body>
</html>
servlet code
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String firstname = request.getParameter("firstname");
String lastname = request.getParameter("lastname");
String email = request.getParameter("email");
HttpSession session = request.getSession(false);
if (//handle your logic) {
out.print("<p style=\"color:red\">Account Created</p>");
RequestDispatcher rd = request.getRequestDispatcher("index.jsp");
rd.forward(request, response);
} else {
out.print("<p style=\"color:red\">Error Occured </p>");
RequestDispatcher rd = request.getRequestDispatcher("newuser.jsp");
rd.include(request,response);
}
}