Encountering an error when uploading an image - mysql

I am trying to upload an image to my database using jsp. I want to store the image in a folder called Upload and want to insert the image name in the database. I used a servlet to do this.
I uses seperate pages for input, action and database connection and I explain the code below.
Photo.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body><form name="f" action="uploadimage" method="post" enctype="multipart/form-data">
<table>
<tr><td>
Name</td><td><input type="text" name="name"/></td></tr>
<tr><td> Address</td><td><textarea name="addr" rows="10" cols="10"></textarea></td></tr>
<tr> <td><input type="file" name="f1"></td></tr>
<tr><td colspan="2"><input type="submit" name="b1"></td></tr></table> </form>
</body>
</html>
My database connection is given below:
public int insert_file(String name, String addr, String img)
{
int i=0;
System.out.println("inside insert_file");
try
{
Connection con21=get_con();
System.out.print(con21);
Statement s21=con21.createStatement();
String s11="insert into image(name,addr,image) values ('"+name+"','"+addr+"','"+img+"')";
System.out.println("i"+s11);
i=s21.executeUpdate(s11);
System.out.println(i);
}
catch(Exception e)
{
System.out.println(e);
}
return i;
}
Here is my servlet page:
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Iterator;
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 org.apache.tomcat.util.http.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import DBConnection.MYConnection;
/**
*
* #author MONOOS
*/
#WebServlet(name = "uploadimage", urlPatterns = {"/uploadimage"})
public class uploadimage extends HttpServlet {
String name,addr,img;
//MYConnection obj=new MYConnection();
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
MYConnection obj=new MYConnection();
out.println(obj);
out.println("haiiii");
try {
out.println("inside try");
System.out.print("inside try");
List fileItems;
// Parsing field values
DiskFileItemFactory factory = new DiskFileItemFactory();
out.println(factory);
factory.setSizeThreshold(10000000);
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(10000000);
try {
// Parse the request to get file items.
out.println("inside nested try");
fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println(i);
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (fi.isFormField()) {
if (fi.getFieldName().equals("name")) {
name = fi.getString();
out.println(name);;
System.out.println("name:"+name);
}
if (fi.getFieldName().equals("addr"))
{
addr = fi.getString();
System.out.println("address:"+addr);
out.println(addr);
}
}
else
{
out.println("inside else");
System.out.println("inside else");
img = fi.getName();
System.out.println("Image :"+img);
File outfile = new File("I:\\NetBeansProjects\\MGNREGA\\web\\Upload" + fi.getName());
fi.write(outfile);
}
}
int j=obj.insert_file("nayana","gfg",img);
System.out.println("j:" + j);
}
catch(Exception e)
{
System.out.print(e);
}
}
finally {
out.close();
}
}// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP
* <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP
* <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
My problem is that the code is running, but it does not do what I want. The first print statement in the try clause are printed successfully.

I resolve my problem... I change the package "import org.apache.tomcat.util.http.fileupload.FileItem;" into "import org.apache.commons.fileupload.FileItem;".
now it running well....

Related

Hyperlink `<a>` not invoking a mapped Servlet. Returning 404: Resource not found [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 2 years ago.
What it says on the title. I'm trying to invoke a servlet to create a page when I click on a link. Attached below is the code.
HTML:
<html>
<head>
<title>NavBar</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="sheet.css">
</head>
<body>
<section class="ft_root">
<div class="ft">
<ul>
<li> 1 </li>
<li> 2 </li>
<li> 3 </li>
<li> 4 </li>
<li> 5 </li>
</ul>
</div>
</html>
Web.XML
<?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_3_1.xsd"
version="3.1">
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<servlet>
<servlet-name>entry_page_gen</servlet-name>
<servlet-class>Servlets.entry_page_gen</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>entry_page_gen</servlet-name>
<url-pattern>/entry/*</url-pattern>
</servlet-mapping>
</web-app>
entry_page_gen.java
package Servlets;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author oras
*/
#WebServlet(name = "entry_page_gen", urlPatterns = {"/entry/*"})
public class entry_page_gen extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet entry_page_gen</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet entry_page_gen at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
entry_page_gen.java is stored in a package called Servlets.
What's going wrong? If more information is needed, please ask. I didn't want to bog down the question with info that might not be needed.
A point to note is that if I change the Web.xml -> <servlet-mapping> -> <url-pattern> to /entry_page_gen and call the servlet from a <form> with the action parameter, everything works fine.
P.S: I referred to this question while creating the above pieces of code.
Well here is a solution for you.
entry_page_gen.java (By the way you should change this name to follow the java convention)
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//processRequest(request, response);
response.sendRedirect("hello.html");
return;
}
Configuration:
Output:
Notes:
In the image you are seeing the URL http://localhost:8080/web-project/hello.html because of the redirect in the method, but you can reach this element with: http://localhost:8080/web-project/entry
The explanation of the configuration could see here:
https://stackoverflow.com/a/26329628/1670134
As answered in here, the initial slash character refers to the path from the base URL (by default the domain name, unless changed with a <base> HTML element). So if your app URL is http://www.example.com/myapp, then an anchor 1 will refer to http://www.example.com/entry/test.html, therefore the servlet is not called.
You could change the anchor's href to this 1

before inserting check already existing data in database

Register.java
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author srini
*/
#WebServlet(urlPatterns = {"/RegisterServlet"})
public class RegisterServlet extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
public void doGet(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
processRequset (request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequset (request,response);
}
#SuppressWarnings("unused")
public void processRequset(HttpServletRequest request,HttpServletResponse response)
throws IOException,ServletException{
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String phone =request.getParameter("phone");
String username =request.getParameter("uname");
String password =request.getParameter("pass");
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection(
"jdbc:mysql://localhost:3306/register","root","toor");
PreparedStatement pstmt=con.prepareStatement("select * from headwy where unmae=? " );
ResultSet rs = pstmt.executeQuery();
if(rs.next()==true)
{
out.print("username already exist");
}
else {
String insertquery = "insert into headwwy (phone,uname,pass) values(?,?,?)";
pstmt.executeQuery("insertquery");
pstmt.setString(1,phone);
pstmt.setString(2,username);
pstmt.setString(3,password);
out.print("You are successfully registered...");
pstmt.close();
con.close();
}
}
catch (Exception e2) {System.out.println(e2);
}
out.close();
}
}
I am trying to check the existing data in database and insert the record.In the above try to execute it shows the blank page.
before insert command is worked but we adding the select command its not working.
using the select command for the check the database and in case any data existing the database it shows the record is already exist ,please choose the another name.
In case of no duplicate data not found,insert command perform the action and insert the new record into the database and it shows the new record in to database successfully.
But my code is not working for the properly.
thank you.
You have mistake in your code :
PreparedStatement pstmt=con.prepareStatement("select * from headwy where unmae=? " );
check your column name its "uname" not "unmae".
There are multiple issues in your code. First there is a typo. If that is the reason for failure.
select * from headwy where unmae=?
insert into headwwy (phone,uname,pass) values(?,?,?)
Also
pstmt.executeQuery("insertquery");
should be executed after you have set the parameters
pstmt.setString(1,phone);
pstmt.setString(2,username);
pstmt.setString(3,password);
I'll recommend to go through JDBC tutorial and run again.
You should set the parameters in your preparedstatement before executing your preparedstatement.
PreparedStatement pstmt=con.prepareStatement("select * from headwy where unmae=? " );
pstmt.setString(1,username);
ResultSet rs = pstmt.executeQuery();
if(rs.next())
{
System.out.print("username already exist");
}

my sql query error in servlet/jdbc ? inserting blob into database ..?

I am unable to insert the image of a user into a blob field through the following code:
/*
* To change this license header, choose License Headers in Project Properties.
* To change this template file, choose Tools | Templates
* and open the template in the editor.
*/
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.*;
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;
/**
*
* #author SUKIRTI
*/
#WebServlet(urlPatterns = {"/imageupload"})
#MultipartConfig(maxFileSize = 16177215)
public class imageupload extends HttpServlet {
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet imageupload</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet imageupload at " + request.getContextPath() + "</h1>");
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// processRequest(request, response);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
InputStream inputStream = null;
Part filePart = request.getPart("photo");
if (filePart != null) {
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/final_project?zeroDateTimeBehavior=convertToNull", "root", "madhumakhis");
String sql = "insert into signup(dp) values(?) where signup.name =" + request.getSession(false).getAttribute("uname")+";";
PreparedStatement statement = con.prepareStatement(sql);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(1, inputStream);
}
int row = statement.executeUpdate();
if (row > 0) {
out.println("image uploaded");
}
}catch(Exception e){out.println(e);}
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
It's showing the following error:
"com.mysql.jdbc.exceptions.jdbc4.MySQLSyntaxErrorException: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'where signup.name =mummy' at line 1"
where mummy is the retrieved attribute("uname") ?
I am new in jsp/servlets so kindly explain what should I do to make it work.
There is no syntax insert into ...values .. where defined
looks like you want to update a column, so you have to use:
Update signup set dp =? where signup.name = ?
For more information about update syntax look in the official mysql documantation

HTML form HTTP post does not pass any parameters for certain mobile browsers

I have an HTML form that uses 'POST' to send parameters to a servlet. When I use a computer the form works for both 'GET' and 'POST' methods. However, on certain mobile phones there are no parameters passed to the servlet when using 'POST'. It does work on mobile phones when using the 'GET' method.
I have tested it on an iPhone 5C (iOS7), iPhone 4 (iOS 6), Samsung Galaxy S3 (Android 4.4.2), Samsung Galaxy S4 (Android 4.4.2), and LG G2 (Android 4.4.2).
It works unreliably when using the Google Chrome mobile browser, but not at all when using the default browser installed. Does anyone know how to make it work for the native browsers?
Thanks!
Below is the code for a simplified version of the error. The form posts to the servlet that prints to the browser all parameters. It is hosted on an Amazon Web Services Elastic Beanstalk running Tomcat 8 Java 8.
The deployed example can also be viewed here:
http://centum2-env-bc2wqa62ib.elasticbeanstalk.com/
On mobile browsers, only the word "Parameters" is printed to the browser.
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="./Test" method="post">
First name: <input type="text" name="firstname">
Last name: <input type="text" name="lastname">
<input type="submit" value="Login">
</form>
</body>
</html>
Test.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
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 Test
*/
#WebServlet("/Test")
public class Test extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Test() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.write("Parameters\n");
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
out.write(paramName);
out.write("\n");
String[] paramValues = request.getParameterValues(paramName);
for (int i = 0; i < paramValues.length; i++) {
String paramValue = paramValues[i];
out.write("\t" + paramValue);
out.write("\n");
}
}
out.close();
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
response.setContentType("text/plain");
out.write("Parameters\n");
Enumeration<String> parameterNames = request.getParameterNames();
while (parameterNames.hasMoreElements()) {
String paramName = parameterNames.nextElement();
out.write(paramName);
out.write("\n");
String[] paramValues = request.getParameterValues(paramName);
for (int i = 0; i < paramValues.length; i++) {
String paramValue = paramValues[i];
out.write("\t" + paramValue);
out.write("\n");
}
}
out.close();
}
}

How can I pass value from JSP page to Servlet and save in MySQL database?

I want to upload a file in apache tomcat and save data in the MySQL from text field using JSP. On doing so, I could not pass the value from JSP page to Servlet and save in Database.
How can I do it?
I tried the following lines of code:
JSP:
<form action="UploadServlet" method="post"
enctype="multipart/form-data">
<input type="file" name="file" size="50" />
<br />
<input name="a" type="text"/>
<br />
<input type="submit" value="Upload File" />
</form>
And also I used the following lines of code in Servlet:
Servlet
import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.util.*;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.JOptionPane;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
public class UploadServlet extends HttpServlet {
private boolean isMultipart;
private String filePath;
private int maxFileSize = 10000 * 1024;
private int maxMemSize = 5 * 1024;
private File file;
String gi;
#Override
public void init() {
// Get the file location where it would be stored.
filePath = getServletContext().getInitParameter("file-upload");
}
protected void processRequest(HttpServletRequest request, HttpServletResponse
response) throws ServletException, IOException {
// Check that we have a file upload request
isMultipart = ServletFileUpload.isMultipartContent(request);
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
gi =request.getParameter("a");
if (!isMultipart) {
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
out.println("<p>No file uploaded</p>");
out.println("</body>");
out.println("</html>");
return;
}
DiskFileItemFactory factory = new DiskFileItemFactory();
// maximum size that will be stored in memory
factory.setSizeThreshold(maxMemSize);
// Location to save data that is larger than maxMemSize.
factory.setRepository(new File("D:\\Software\\apache-tomcat-7.0.29\\webapps\\Hello\\temp"));
// Create a new file upload handler
ServletFileUpload upload = new ServletFileUpload(factory);
// maximum file size to be uploaded.
upload.setSizeMax(maxFileSize);
try {
// Parse the request to get file items.
List fileItems = upload.parseRequest(request);
// Process the uploaded file items
Iterator i = fileItems.iterator();
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet upload</title>");
out.println("</head>");
out.println("<body>");
while (i.hasNext()) {
FileItem fi = (FileItem) i.next();
if (!fi.isFormField()) {
// Get the uploaded file parameters
String fieldName = fi.getFieldName();
String fileName = fi.getName();
String contentType = fi.getContentType();
boolean isInMemory = fi.isInMemory();
long sizeInBytes = fi.getSize();
// Write the file
if (fileName.lastIndexOf("\\") >= 0) {
file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\")));
} else {
file = new File(filePath + fileName.substring(fileName.lastIndexOf("\\") + 1));
}
fi.write(file);
out.println("Uploaded Filename: " + fileName + "<br>");
}
}
} catch (Exception ex) {
out.println("Your file size should be less than 10 or equal to 10kb" + ex);
}
try {
/* TODO output your page here. You may use following sample code. */
out.println("<h1>"+gi+"</h1>");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/webSiteTest", "root", "root");
PreparedStatement stat = conn.prepareStatement("insert into abc(name) values (?)");
stat.setString(1, gi);
int aa = stat.executeUpdate();
JOptionPane.showMessageDialog(null, "Database Connected Successfully.");
} catch (SQLException ex) {
JOptionPane.showMessageDialog(null, "Query Error!");
} catch (ClassNotFoundException ee) {
JOptionPane.showMessageDialog(null, "Database not Found!");
}
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
processRequest(request, response);
}
#Override
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, java.io.IOException {
//throw new ServletException("GET method used with " + getClass().getName() + ": POST method required.");
processRequest(request, response);
}
}
How can I do this.
Create file object that points to a file specified by you in JSP.
and in JSP do,
request.setAttribute("file",fileObject);
and in Servlet get that object using
request.getAttribute("file");
try this.it should work.
To send a file through a JSP/servlet we need a commonsio.jar file and this will be easily found in the google. Now place that jar file in the lib directory of the tomcat folder and Now it will work.