I am simply trying to retrieve a image from database and display it. I have written the following code:
RetreiveImage.java
import myconnection.ConnetionDefault;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class RetreiveImage extends HttpServlet{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
PrintWriter out = response.getWriter();
Connection con=null;
String id=request.getParameter("id");
try{
con=ConnetionDefault.getConnection();
ResultSet results = null;
PreparedStatement ps = null;
ps = con.prepareStatement("select picture from pic_229084519 where pic_id=?");
ps.setString(1,id);
results = ps.executeQuery();
String imgLen="";
if(results.next()){
imgLen = results.getString(1);
System.out.println(imgLen.length());
int len = imgLen.length();
byte [] rb = new byte[len];
InputStream readImg = results.getBinaryStream(1);
int index=readImg.read(rb, 0, len);
System.out.println("index"+index);
ConnetionDefault.close(results,ps,con);
response.reset();
response.setContentType("image/jpg");
response.getOutputStream().write(rb,0,len);
response.getOutputStream().flush();
RequestDispatcher rd=request.getRequestDispatcher("gg.html");
rd.forward(request,response);
}
} catch (Exception e){
e.printStackTrace();
}
}
}
retImagel.html
<html>
<head>
<title>Login</title>
</head>
<body bgcolor="Gold">
<center>
<form action="ret.pic">
<table>
<tr><th>Namme</th><td><input type="text" name="id" size="3"/></td><td></td>
<td><input type="submit" value="Get"></td><td><input type="reset" value="Cancel"/></td></tr>
</table>
</form>
</center>
</body>
</html>
gg.html
<html>
<head>
<title>Login</title>
</head>
<body bgcolor="Gold">
<img src="/ret.pic?id=${id}"/>
</center>
</body>
</html>
My problem is its displaying image in default response page. but i want it in gg.html where i am going wrong.. pls help me.
Set the filter in your web.xml to call your servlet.
On your gg.html page insert tag < img "url to image that filter can intersept" >
Related
I have got a Form Page index.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>
<style>
fieldset
{
width: 70px;
}
</style>
</head>
<body>
<form action="Upload" method="post" enctype="multipart/form-data">
<fieldset>
<table>
<tr>
<td>Name</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td>Select Photo</td>
<td><input type="file" name="photo"></td>
</tr>
<td><input type="submit" value="Upload"></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
MyServlet Page Upload.java:
import java.sql.*;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintWriter;
import java.sql.DriverManager;
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(name = "Upload", urlPatterns = {"/Upload"})
#MultipartConfig(maxFileSize = 169999999) // upload file's size up to 16MB
public class Upload extends HttpServlet
{
private static final long serialVersionUID = 1L;
PrintWriter out;
InputStream inputStream = null;
int allField = 0;
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try
{
out = response.getWriter();
String name=request.getParameter("name");
Part filePart = request.getPart("photo");
if (filePart != null)
{
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/db","root","root")
PreparedStatement ps = con.prepareStatement("insert into PhotoDetails(Name,Images)values(?,?)");
ps.setString(1,name);
ps.setBlob(2,inputStream);
ps.executeUpdate();
out.println("Image Inserted");
}
catch(Exception e)
{
out.println(e);
}
}
}
I am using mysql database and here is my table:
create table PhotoDetails
(
Name varchar(100),
Images blob
)
After filling all the form and when I click on the Update button then I get this error :
HTTP Status 500 - Servlet execution threw an exception
How could I resolve this problem?
This is the best way to show image in jsp file.
Just create showLogo.jsp
and include where ever you want it.
<%# page trimDirectiveWhitespaces="true" %>
<%# page import="java.sql.*,java.io.*,org.apache.struts2.ServletActionContext"%>
<%# page language="java" import="java.util.*, com.abc.util.dbutil.*,javax.servlet.http.HttpServletRequest" %>
<%
try{
InputStream sImage;
ResultSet resultSet = null;
PreparedStatement pstmt = null;
DBConnection dbConnection= null;
dbConnection= new DBConnection();
Connection con = null;
con= dbConnection.getConnection();
ServletInputStream sInIm = null;
Statement st=con.createStatement();
String company_id = request.getParameter("company_id");
resultSet=st.executeQuery("select logo from company where company_id='" + company_id + "'");
if(resultSet.next()){
byte[] bytearray = new byte[1048576];
int size=0;
sImage = resultSet.getBinaryStream(1);
response.reset();
response.setContentType("image/jpeg");
while((size=sImage.read(bytearray))!= -1){
response.getOutputStream().write(bytearray,0,size);
}
response.getOutputStream().flush();
response.getOutputStream().close();
}
con.close();
}
catch(Exception ex){
}
%>
I am getting it like this.
/company/showLogo.jsp?company_id=" id="blah_s" class="logo-small">
Get image from file to FileInputStream
FileInputStream fs = null;
try {
fs = new FileInputStream(getUserImage());
} catch (FileNotFoundException e) {
e.printStackTrace();
}
.................
ps.setBinaryStream(8, fs, fs.available());
insert into table(logo) values (?)
This is for mysql with blob column.
I need help in checking the data into the database before insertion.
Issue:
I have used the general method to insert the values into database.But I need to include this condition into my servlet code i.e if a data is already present in the database,then that data should not be inserted into the database and the remaining data should be inserted into the database.While doing this no alert should be raised to the user.
This is my code.
products.jsp
<%#page import="java.util.List"%>
<%#page import="web.Products"%>
<%#page import="java.util.ArrayList"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<form method="post" action="Save_Products">
<b>
Brand Name:<font color="green">
<% String brand_name=(String)session.getAttribute("brand_name");
out.print(brand_name);%>
<c:set var="brand_name" value="brand_name" scope="session" />
</font></b>
<table>
<tr>
<th> Products</th>
<th> Description </th>
</tr>
<tr>
<td> <b><%
List<Products> pdts = (List<Products>) request.getAttribute("list");
if(pdts!=null){
for(Products prod: pdts){
out.println("<input type=\"checkbox\" name=\"prod\" value=\"" + prod.getProductname() + "\">" + prod.getProductname()+"<br>");
} %> </b></td>
<td><%for(Products prod: pdts){
out.println("<input type=\"text\" name=\"desc\" style=\"width:50px; height:22px\"/><br/>");
}
}
%> </td>
</tr>
<br/>
<br/>
<tr><td align="center"> <input type="submit" value="Save" name="save"/> </td></tr>
</table>
</form>
</body>
</html>
Servlet code
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpSession;
public class Save_Products extends HttpServlet {
static final String dbURL = "jdbc:mysql://localhost:3306/pdt";
static final String dbUser = "root";
static final String dbPass = "root";
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ResultSet rs=null;
Connection connection = null;
try{
HttpSession session = request.getSession();
String brand_name =(String) session.getAttribute("brand_name");
String [] prod_list = request.getParameterValues("prod");
String [] desc_list = request.getParameterValues("desc");
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection (dbURL,dbUser,dbPass);
String sql="insert into pdt_list(brand_name,product_name,desc)values(?,?,?)";
PreparedStatement prep = connection.prepareStatement(sql);
int num_values = Math.min(prod_list.size(), desc_list.size());
int count_updated = 0;
for(int i = 0; i < num_values; i++){
prep.setString(1, brand_name);
prep.setString(2, prod_list[i]);
prep.setString(3,desc_list[i]);
count_updated += prep.executeUpdate();
}
if(count_updated>0)
{
out.print("Products Saved Successfully...");
RequestDispatcher rd=request.getRequestDispatcher("Save_Success.jsp");
rd.forward(request,response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("Save_Failure.jsp");
rd.forward(request,response);
}
prep.close();
}
catch(Exception E){
//Any Exceptions will be caught here
System.out.println("The error is"+E.getMessage());
}
finally {
try {
connection.close();
}
catch (Exception ex) {
System.out.println("The error is"+ex.getMessage());
}
}
}
}
I am still wondering what it is that i am doing wrong,my problem is i dont know if it is my entire sample code which has na error or my connection to the database which has an issues, as of where i stand i am not sure what is making me get this error. (displayed below).I have tried to look here at stack overflow but all i get is loading images using JSP but not adding them to the database. If we have one i couldnt trace please help me with the link. I have included all the libraries needed and my code has no error apart from this output. I came here because i am stranded and need a short review of what you proffesionals think is wrong with my code as done below. I will really appreciate anyhelp given as i am working on a deadline.
my Database name is
AppDB
I was wondering should i use the name of the table? to INSERT INTO? which is
'contacts'
Error Message
HTTP Status 404 - /UploadImageOnWeb/uploadServlet type Status report
message /UploadImageOnWeb/uploadServlet description The requested
resource is not available. Apache Tomcat/8.0.23
Thank you
Java Servlet Code
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;
/**
* Servlet implementation class FileUploadDBServlet
*/
#MultipartConfig(maxFileSize = 16177215)
#WebServlet("/FileUploadDBServlet")
public class FileUploadDBServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
// database connection settings
/*private String dbURL = "jdbc:mysql://localhost/AppDB";
private String dbUser = "root";
private String dbPass = "mypassword";*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null;
Part filePart = request.getPart("photo");
if (filePart != null) {
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
inputStream = filePart.getInputStream();
}
Connection conn = null;
String message = null;
try {
// connects to the database
/*DriverManager.registerDriver("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);*/
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/AppDB","root","mypassword");
// 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);
}
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.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);
}
}
}
My .Jsp class
<%# 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>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="uploadServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>Enter First Name: </td>
<td><input type="text" name="firstName" size="20"/></td>
</tr>
<tr>
<td>Enter Last Name: </td>
<td><input type="text" name="lastName" size="20"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="20"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table>
</form>
</center>
</body>
</html>
Display Jsp
<%# 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">
<title>Message</title>
</head>
<body>
<center>
<h3><%=request.getAttribute("Message")%></h3>
</center>
</body>
</html>
The 404 error indicates that the form is not even getting to the servlet.
You defined the action attribute in the form as uploadServlet which doesn't seem to be a valid URL for your application.
The servlet's URL is defined in the #WebServlet annotation as FileUploadDBServlet.
So you can fix it by changing the action in the form or changing the URL for the servlet.
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 7 years ago.
At beggining. There is a application structure.
I have 3 MySQL tables ( Obiekt, Termin, Rezerwacja). In project i have jsp page (here is code) :
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# page import="java.sql.*"%>
<%# page import="java.io.*"%>
<%# page import="java.util.*"%>
<%# page import="test.Obiekt"%>
<%# page import="test.ListaObiektow"%>
<%# page import="test.Termin"%>
<%# page import="test.ListaTerminow"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>menu główne</title>
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<meta name="android-mobile-web-app-capable" content="yes">
<meta name="android-mobile-web-app-status-bar-style" content="black">
<link href="css/ratchet.css" rel="stylesheet">
<link href="css/ratchet-theme-android.css" rel="stylesheet">
<script src="js/ratchet.js"></script>
<script type="text/javascript">
function Refresh(idObiekt){
location.href="pilkaNozna.jsp?idObiekt=" + idObiekt;
}
</script>
</head>
<body>
</br>
</br>
</br>
<header class="bar bar-nav">
<a class="icon icon-left-nav pull-left" href="wyszukaj.jsp"></a>
<h1 class="title">Wybierz obiekt</h1>
</header>
<div id="content">
<div class="tabelawybor">
<b>Wybierz obiekt:</b>
<%
ArrayList<Obiekt> list = new ListaObiektow().getObiekty();
%>
<form>
<select name="obiekt" onChange="Refresh(this.value)">
<option value="0" selected>Wybierz Obiekt</option>
<%
String selectedObiekt = request.getParameter("idObiekt");
int counter=0;
for (Obiekt obiekt : list) {
if(selectedObiekt == null && counter==0)
{
selectedObiekt = Integer.toString(obiekt.idObiekt);
}
%>
<option value="<%=obiekt.idObiekt%>"
<%= ((Integer.toString(obiekt.idObiekt)).equals(selectedObiekt))?"selected":""%>><%=obiekt.nazwa%>
<%=obiekt.adres%></option>
<%
}
%>
</select>
</form>
</div>
<div class="tabelawybor">
<td><b>Wpisz liczbę uczestników:</b><input type="text"
name="uczest" /></td>
<% String liczbaUczestnikow = request.getParameter("liczbaUczestnikow"); %>
</div>
<div class="tabelawybor">
<form action="Rezerwacja?action=doPost" method="post">
<table class="center">
<tr>
<td>Nazwa obiektu:</td>
<td>Data:</td>
<td>Godzina</br> rozpoczęcia:
</td>
<td>Godzina</br> zakończenia:
</td>
<td></td>
</tr>
<%
ListaTerminow listaterminow = new ListaTerminow();
listaterminow.setId(selectedObiekt);
ArrayList<Termin> lista =listaterminow.getTerminy();
String idTermin = request.getParameter("idTermin");
for (Termin termin : lista) {
%>
<tr>
<td><%=termin.nazwaObiektu%> <%=termin.adresObiektu%></td>
<td><%=termin.dzien%></td>
<td><%=termin.odKtorej%></td>
<td><%=termin.doKtorej%></td>
<td>
<button class="btn btn-primary">Zarezerwuj</button>
</td>
</tr>
<%
}
%>
</table>
</form>
</div>
</div>
</body>
</html>
In this jsp page i have select form which have List of Obiekt (this list is created in ListaObiektow.java), but it works. I also have table form which contains List of Termin (created in ListaTerminow.java). It works too. But, in this table form there is button to make Rezerwacja.
I made Rezerwuj servlet. Here is code:
package test;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
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 test.ConnectionClass;
import test.Rezerwacja;
import test.Termin;/**
* Servlet implementation class Rezerwuj
*/
#WebServlet("/Rezerwacja")
public class Rezerwuj extends HttpServlet {
private static final long serialVersionUID = 1L;
Connection conn;
private int idTermin;
private int liczbaUczestnikow;
public Rezerwuj() {
super();
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
conn = ConnectionClass.Polacz();
ArrayList<Rezerwacja> rezerwacje = new ArrayList<Rezerwacja>();
PreparedStatement st = null;
ResultSet rs = null;
String sql = "INSERT INTO rezerwacje (liczbaUczestnikow,idTermin) values ('" + liczbaUczestnikow + "','" + idTermin + "')"
+ "UPDATE termin SET termin.czyZajety=true WHERE termin.idTermin = '"+ idTermin +"'";
try
{
st = conn.prepareStatement(sql);
if(liczbaUczestnikow > 0 && liczbaUczestnikow < 20)
{
rs = st.executeQuery();
}
while(rs.next())
{
Rezerwacja rezerwacja = new Rezerwacja();
rezerwacja.setLiczbaUczestnikow(rs.getInt(1));
rezerwacja.setIdTermin(rs.getInt(2));
rezerwacje.add(rezerwacja);
}
}
catch(SQLException e)
{
System.out.println(e);
}
}
public void setIdTermin(String id)
{
idTermin = Integer.parseInt(id);
}
public void setliczbaUczestnikow(String liczba)
{
liczbaUczestnikow = Integer.parseInt(liczba);
}
}
When i click on the button, it returns error like this:
type Exception report
message
description The server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
test.Rezerwuj.doPost(Rezerwuj.java:63)
javax.servlet.http.HttpServlet.service(HttpServlet.java:648)
javax.servlet.http.HttpServlet.service(HttpServlet.java:729)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
What i want:
I select one of option in select form, then type value (0-20) into text input, then click on button and create a record in MySQL table Rezerwacja. Any suggestions ?
<form action="Rezerwacja?action=doPost" method="post">
In this line the action is where you are sending the request, so it should be action="Rezerwacja" and method should be method="POST"
I think you have problem with liczbaUczestnikow after initialization is always 0. As result rs always null, therefore exception thrown.
I'm having a little issue connecting with my servlet so that I can pass some data to a mysql database. I've read a bunch of the threads here, but have had no luck with suggestions to other members.
I have a jsp page named "insertData.jsp" On that page there is a form where the action points to a servlet named "UpdateData". When I click submit on the web page, I get a 404 error stating that the requested resource is not available. I have also updated my web xml file to try to point to the right direction.
So here's my folder setup:
The UpdateData.java is in the controller package of the source packages folder. The name of the project is "RukertContainerTracker".
Here's my jsp page:
<%#taglib prefix="sql" uri="http://java.sun.com/jsp/jstl/sql"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.Connection"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert Data</title>
</head>
<body>
<h1>Insert Data Into Container Records</h1>
<H1>The Rukert Terminals Container Tracker </H1>
<form name="Insert Record" action="/UpdateData" method="Post">
Container Number: <input type="text" name="containerNumber"> <br />
Full Out: <input type="date" name="fullOut" /> <br/>
Empty In: <input type="date" name="emptyIn" /> <br/>
Empty Out <input type="date" name="emptyOut" /> <br/>
Full In: <input type="date" name="fullIn" /> <br/>
Comments: <input type="text" name="comments" /> <br/>
<input type="submit" value="Submit" />
</form>
<div>
<a href="javascript:history.back();">
<span class="categoryLabelText">HOME</span>
</a>
</div>
</body>
</html>
My servlet:
package controller;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class UpdateData extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException, SQLException {
//Get container data from the JSP page
String container=request.getParameter("containerNumber");
String fullOutDate=request.getParameter("fullOut");
String emptyInDate=request.getParameter("emptyIn");
String emptyOutDate=request.getParameter("emptyOut");
String fullInDate=request.getParameter("fullIn");
String comments=request.getParameter("comments");
//Print the above got values in console
System.out.println("The username is" +container);
System.out.println("\nand the password is" +fullOutDate);
String connectionparams="jdbc:mysql://localhost:3306/rukerttracker";
String db="rukerttracker";
String uname="root";
String psword="Colorado1982";
Connection connection=null;
ResultSet rs;
try {
// Loading the available driver for a Database communication
Class.forName("com.mysql.jdbc.Driver");
//Creating a connection to the required database
connection = DriverManager.getConnection
(connectionparams, uname, psword);
//Add the data into the database
String sql = "insert into containerinventory values (?,?,?,?,?,?)";
try (PreparedStatement prep = connection.prepareStatement(sql)) {
prep.setString(1, container);
prep.setString(2, fullOutDate);
prep.setString(3, emptyInDate);
prep.setString(4, emptyOutDate);
prep.setString(5, fullInDate);
prep.setString(6, comments);
prep.executeUpdate();
}
}catch(Exception E){
System.out.println("The error is=="+E.getMessage());
}
finally{
connection.close();
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String userPath = request.getServletPath();
// if category page is requested
if (userPath.equals("/insertData")) {
// TODO: Implement category request
// use RequestDispatcher to forward request internally
String url = "/WEB-INF/view" + userPath + ".jsp";
try {
request.getRequestDispatcher(url).forward(request, response);
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
And finally my web.xml page:
<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>controller.ControllerServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/chooseLanguage</url-pattern>
<url-pattern>/viewTracker</url-pattern>
<url-pattern>/editTracker</url-pattern>
<url-pattern>/addToCart</url-pattern>
<url-pattern>/viewCompany</url-pattern>
<url-pattern>/category</url-pattern>
<url-pattern>/updateCart</url-pattern>
<url-pattern>/purchase</url-pattern>
<url-pattern>/viewCart</url-pattern>
<url-pattern>/checkout</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>UpdateData</servlet-name>
<servlet-class>controller.UpdateData</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>UpdateData</servlet-name>
<url-pattern>/insertData</url-pattern>
</servlet-mapping>
I have two servlets, I don't know if this matters, but I couldn't get the application to work in the controller servlet, so I created the Update Data servlet.
Any help as to why I keep getting this 404 error would be greatly, greatly appreciated. Thanks for taking the time to look at this.
I think in form you are using POST method and your servlet does not have post method. please check it.
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{...}
not available.