How to properly display Mysql tables using servlets and java? - java

I am newbie here. I have an assignment that requires to connect mysql, servlet and java (because i want to separate java code and html code. Previously, i combined the codes to make it easier and was rejected)
So, basically, in mySql i write this,
create table login2 (username varchar (30), password varchar(30), designation varchar(10));
insert into login2 values('lala','123','A');
and i create loginDisp.java in the servlet using eclipse. This is my command
package Servlet;
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class loginDisp extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
// String username=request.getParameter("Username");
// String password=request.getParameter("Password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>Servlet JDBC</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection
("url/tablename","uname","pssword");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM login2");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("<br>");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
When i execute, it is well displayed. Hence, i started to make the Login.jsp as i want to make a text.box for user to insert username and password. This is my code
<%# 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>Insert title here</title>
</head>
<body>
<body>
<center>
<div class="wrapper">
<br>
<br>
<h2>Doctor</h2>
<form name="form1" method="post" action="loginDisp" > <!-- onsubmit="return validateForm()" -->
<table width="326" border="1" align="center">
<center> <tr>
<th width="138" scope="row">Username</th>
<td width="142"><input type="text" name="Username"></td>
</tr>
</center>
<tr>
<th height="31" style="width: 162px;"><span class="style2">Password</span>
</th>
<td width="142"><input type="password" name="Password"></td>
</tr>
<tr>
</tr>
</table>
<p align="center">
<input type="submit" name="Submit" value="Submit">
</p> ${message}
</form>
</div>
</center>
</body>
</body>
</html>
and I get the data from mySQL displayed. I add another log.java in servlet because i thought when we need a data fetched from jsp to databased and displayed when be called. This is code in log.java
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class log extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get username and password from the JSP page
String username=request.getParameter("Username");
String password=request.getParameter("Password");
//Print the above got values in console
System.out.println("The username is" +username);
System.out.println("\nand the password is" +password);
}
}
The username and password inserted in login.jsp does not inserted automatically in mySQL, hence when i try to executed loginDisp.java , it will display only the data i inserted manually in mySQL.

You can not use the java file name as action this is defined in the web.xml file and there is servlet mapping and you can use
<servlet>
<servlet-name>log</servlet-name>
<servlet-class>loginDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>log</servlet-name>
<url-pattern>/loginDisplay</url-pattern>
</servlet-mapping>
and now you can use the action = "loginDisplay" in the action tag and by using this
I hope you did not face the problem of 404 error.

You entered a wrong action in form.
Since form's action attribute takes the path of the servlet you should give the relavent mapping specified in web.xml
action="loginDisplay.java"
should be action="/loginDisplay"
<form name="form1" method="post" action="loginDisplay.java" onsubmit="return validateForm()">
It should be
<form name="form1" method="post" action="/loginDisplay" onsubmit="return validateForm()">
If /loginDisplay is not the exact mapping in your web.xml check the web.xml file and see the mapping for loginDisplay and give that path as action.
A quick example

Create a new package (called dao or model) where you put your logic to access to the DB.
Then create a Java Bean Object where store the results of your DB and instanciate your class of the logic in the servlet, then access to the properties of the Bean and show it in the WEB.
package model:
class DaoAccess (methods to connect with DB)
class Login (properties of the table with getXXX and setXXX of each one)
package Servlet.
class loginDisplay:
public class loginDisplay extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>loginDisplay</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DaoAccess dao = new DaoAccess();
List<Login> list = dao.readAll();
for(Login obj: list){
out.write(obj.getName());
out.write(obj.getPassword());
}
out.close();
}
}

Related

Trying to implement an SQL vulnerability in a java web application. Java + MySQL

This is a bit of an odd one. For my uni final project I'm trying to develop a vulnerable web application as an educational tool. One of the vulnerabilities I want to implement is an SQL vulnerability where the user could perform an SQL injection through a 'product search' page on the site.
The problem is that somewhere along the way the inputs seem to be getting sanitised automatically which means I am unable to perform an injection attack. I made a test record of just a single quote (') and this is returned when a single quote in put into the search. If the input was not sanitised it would return an error, right? I'm thinking this could be a feature of the software I'm using that I'll need to disable or use an older version, or I've accidentally set it up in such a way that this is happening. If anyone knows why this might be happening, any help would be massively appreciated! :)
I have a database set up in MySQL Community Server 8.0.13 and a simple application made using JSPs. I have included source code below.
The 'Product Search' page:
<%#page import="java.sql.Connection"%>
<%#page import="databaseManagement.DBConnection"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.SQLException"%>
<%#page import="java.sql.Connection"%>
<%#page import="java.sql.PreparedStatement"%>
<?xml version="1.0" encoding="ISO-8859-1" ?>
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1" />
<title>Search Our Products</title>
</head>
<body>
<h1>Search for a product</h1>
<form method="post" action="ProductSearch">
Search: <input type="text" name="Search"> <br>
<input type="submit" value="Go">
<%#taglib uri="http://java.sun.com/jstl/core_rt" prefix="c"%><br>
<table align="left" border="1">
<tr>
<th>ID</th>
<th>Name</th>
<th>Description</th>
<th>Price</th>
</tr>
<c:forEach var="product" items="${r1}">
<tr bgcolor="">
<td>${product.id}</td>
<td>${product.name}</td>
<td>${product.description}</td>
<td>${product.price}</td>
</tr>
</c:forEach>
</table>
</form>
</body>
</html>
The java servlet:
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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 databaseManagement.DBConnection;
import databaseManagement.Product;
#WebServlet("/ProductSearch")
public class ProductSearch extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProductSearch() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
String searchTerm = request.getParameter("Search");
searchTerm = "%" + searchTerm + "%";
ArrayList<Product> ab = new ArrayList();
try {
String sql1 = "select * from products where name like ?;";
DBConnection db = new DBConnection();
Connection con = db.getConnection();
PreparedStatement ps = con.prepareStatement(sql1);
ps.setString(1, searchTerm);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
Product b = new Product();
b.setId(rs.getInt("id"));
b.setName(rs.getString("name"));
b.setDescription(rs.getString("description"));
b.setPrice(rs.getString("price"));
ab.add(b);
}
request.setAttribute("r1", ab);
request.getRequestDispatcher("productSearch.jsp").forward(request, response);
}
catch (Exception s2) {
s2.printStackTrace();
}
}
}
Fragment of doPost method that should be placed to accept SQL injection:
....
try {
String sql1 = "select * from products where name like '"+searchTerm+"';";
DBConnection db = new DBConnection();
Connection con = db.getConnection();
Statement ps = con.createStatement();
ResultSet rs = ps.executeQuery();
while (rs.next()) {
....
PreparedStatement prevents SQL Injection, so use Statement instead.
It's PreparedStatement who's sanitising your inputs. Instead of setting your parameters, simply concat them to the sql.

MySQL to JSP using Servlet

I am trying to retrieve data from one column of my table in MySQL and display the whole row in a .jsp file. Right now, when I run the code it prints the table with no values. As Shown here.
import java.sql.*;
import javax.servlet.*;
import javax.servlet.annotation.WebServlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.mysql.jdbc.PreparedStatement;
#WebServlet("/review")
public class findservlet1 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8402378218178447403L;
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException {
// res.setContentType("text/html");
PrintWriter out = res.getWriter();
Connection conn = null;
//using movie_resolved view
try{
// Get a Connection to the database
String DB_CONNECTION_URL = "jdbc:mysql://localhost:3306/mydatabase";
String DB_USERNAME = "root";
String DB_PASSWORD = "root";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection(DB_CONNECTION_URL, DB_USERNAME, DB_PASSWORD);
// Create a Statement object
PreparedStatement st = (PreparedStatement) con.prepareStatement("SELECT * FROM coursereview");
ResultSet rs = st.executeQuery();
if (rs.next())
{
com.java.bean.coursereview Course = new com.java.bean.coursereview ();
Course.setCourse_id(rs.getString("courseid"));
Course.setCourserate(rs.getString("courserate"));
Course.setProfessor(rs.getString("professor"));
Course.setProrate(rs.getString("prorate"));
Course.setReview(rs.getString("review"));
req.setAttribute("Course", Course);
RequestDispatcher view = req.getRequestDispatcher("review.jsp");
view.forward(req, res);
}
}
catch(ClassNotFoundException e) {
out.println("Couldn't load database driver: " + e.getMessage());
}
catch(SQLException e) {
out.println("SQLException caught: " + e.getMessage());
}
finally {
// Always close the database connection.
try {
if (conn != null) conn.close();
}
catch (SQLException ignored) { }
}
}
}
Here is my reivew page:
<%# 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>
<link rel="stylesheet" href="styles/style1.css">
<meta http-equiv="Content-Type" content="text/css; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<div class="banner">
<img class="banner-image" src="images/uncclogo400.jpg"></div>
<h2>Review a Course</h2>
<table>
<TR>
<TD>Course ID: </TD>
<TD>${course.courseid}</TD>
</TR>
<TR>
<TD>Course Rate: </TD>
<TD>${course.courserate}</TD>
</TR>
<TR>
<TD>Professor: </TD>
<TD>${course.professor}</TD>
</TR>
<TR>
<TD>Professor Rate: </TD>
<TD>${course.prorate}</TD>
</TR>
<TR>
<TD>Review: </TD>
<TD>${course.review}</TD>
</TR>
</table>
</body>
</html>
I am trying to pull the values from the MySQL DB to print to the review.jsp page. Any ideas on what I am doing wrong?
Hello, I think it's a typo
Change this req.setAttribute("Course", Course); by this req.setAttribute("course", Course);
Best,

Why isn't this code working? HTTP Status 404 – Not Found on jsp and servlet [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am writing a program in java that validate users and if the logged in user was admin he can add another user from registeration form to the database. but when I am going to register someone and press register button it shows me this error.
Here is my code:
index.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
</head>
<body>
<form action="loginServlet" method="post">
<fieldset style="width: 300px">
<legend> Login to App </legend>
<table>
<tr>
<td>User ID</td>
<td><input type="text" name="username" required="required" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="userpass" required="required" /></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</fieldset>
</form>
</body>
</html>
welcome.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Register form</h3>
<form method="post" action="Register.jsp">
Name:<input type="text" name="name" /><br/>
Password:<input type="text" name="pass" /><br/>
Email:<input type="text" name="email" /><br/>
<input type="submit" value="register" />
</form>
</body>
</html>
NewFile.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Login successful!!! user</h3>
<h4>
Hello,
<%=session.getAttribute("name")%></h4>
</body>
</html>
LoginCheck.java:
package com.example.saeid;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoginCheck {
static Boolean isadmin = false;
public static boolean validate(String name, int pass) {
boolean isValid = false;
Connection conn = null;
ResultSet rs = null;
String db_userName = "root";
String db_Password = "uyhgbv098";
String db_Name = "my_demo_database";
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
PreparedStatement ps = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url+db_Name,db_userName,db_Password);
ps =conn.prepareStatement
("select * from user_account where username=? and password=?");
ps.setString(1, name);
ps.setInt(2, pass);
rs = ps.executeQuery();
if(rs.next()) {
isValid = true;
isadmin = rs.getBoolean("isadmin");
}
}catch (Exception e) {
System.out.println(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return isValid;
}
public static Boolean admin(){
return isadmin;
}
}
loginservelet.java:
package com.example.saeid;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import com.example.saeid.LoginCheck;
public class LoginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
int p2 = Integer.parseInt(p);
HttpSession session = request.getSession(false);
if(session!=null)
session.setAttribute("name", n);
if(LoginCheck.validate(n, p2)){
if(LoginCheck.admin()){
RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
rd.forward(request,response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("NewFile.jsp");
rd.forward(request,response);
}
}
else{
out.print("<p style=\"color:red\">Sorry username or password error</p>");
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}
out.close();
}
}
register.java:
package com.example.saeid;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String pass1 = request.getParameter("pass");
int pass = Integer.parseInt(pass1);
String email = request.getParameter("email");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
String db_userName = "root";
String db_Password = "uyhgbv098";
String url = "jdbc:mysql://localhost:3306/";
String db_Name = "my_demo_database";
Connection con=DriverManager.getConnection
(url+db_Name,db_userName,db_Password);
PreparedStatement ps=con.prepareStatement
("insert into user_acount values(?,?,?)");
ps.setString(1, name);
ps.setInt(2, pass);
ps.setString(3, email);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are successfully registered");
}
}
catch(Exception se)
{
se.printStackTrace();
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>FirstHomework</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.example.saeid.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>com.example.saeid.Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
</web-app>
You have not given the fully qualified name of Register servlet in web.xml:-
</servlet-mapping>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>Register</servlet-class> // give the full path
</servlet>
and another thing is that you are storing the password as a String in register.java but when you run the query in Loginservelet you are setting the password as Int. Please prefer password as a String in both classes.
Just as Mayank Sharma said
First, in the web.xml file, you have to specify Register servlet's full path in the servlet-class tag same way you did for LoginServlet class.
Secondly, the value of your register servlet url-pattern tag should be the same value (excluding /) given to the action attribute of the form tag in your welcome.jsp page.
Lastly, take note of Mayank Sharma's second observation.
I must suggest you have to start learning how to develop java web applications using framework. It will help you a lot.

Storing files in MySql database using jsp and servlet.

I am trying to store files (text or image) in mySql database using jsp and servlet.
This is index.jsp.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="FileUploadDBServlet" 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>
This is my FileUploadDBServlet.
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(name = "FileUploadDBServlet", urlPatterns ={"/FileUploadDBServlet"})
public class FileUploadDBServlet extends HttpServlet {
// database connection settings
String dbURL = "jdbc:mysql://localhost:3306/rep";
String dbUser = "root";
String dbPass = "";
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();
}
//System.out.println(inputStream);
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);
}
}
}
And this is my Message.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"/>
<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 message page displays "ERROR: No value specified for parameter 3".
So, I think null value is being stored in inputStream. Why is it so and how can it be handled?
Thanks.
You can use statement.setNull(3, java.sql.Types.BLOB); if yoúr inputstream is null.
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
} else {
statement.setNull(3, java.sql.Types.BLOB);
}
As you are submitting form data with enctype="multipart/form-data" For this you have to mention #MultipartConfig(maxFileSize = "max file size") in your upload servlet.

PreparedStatment not fetching data from MySql using Java Class's Method parameters

I am trying to pass username and password from a jsp page to Authenticate Method in a Java class (LogMeIn.java), but I am getting 'false' as a result. However when I hard code values (abc/abc) I do get 'pass' result. ie. it's successful.
Please can you advise why it's not accepting the parameters passed through jsp?
--LogMeIn.java--
package org.cms.model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class LogMeIn {
public boolean Authenticate( String username, String password ) {
Connection connection = null;
// Statement statement = null;
ResultSet resultSet = null;
PreparedStatement pst = null;
String query;
boolean result = false;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
connection = ds.getConnection();
//statement = connection.createStatement();
query = "select name from account where name= ? and password = ?";
pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
resultSet = pst.executeQuery();
int count=0;
if(resultSet.next())
{
count++;
}
if(count>0)
{
result = true;
}
else
{
result = false;
}
}
catch (SQLException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return result;
}
}
---LoginServlet---
package org.cms.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
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.cms.model.LogMeIn;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username;
String password;
username = request.getParameter("user");
password = request.getParameter("pass");
LogMeIn a = new LogMeIn();
boolean result = a.Authenticate(username, password);
System.out.println(result);
if (result) {
request.setAttribute("loginresult","Pass");
RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
else {
request.setAttribute("loginresult","Failed");
RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
}
}
---Login.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">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Login</title>
<link rel="stylesheet" href="css/style.css" type="text/css"></link>
<script language="JavaScript" type="text/JavaScript" src="validate.js"> </script>
</head>
<body>
<form enctype="multipart/form-data" onSubmit="return validate(this)" method="post" action="LoginServlet" class="form">
<table border = "0">
<tr align="left" valign="top">
<td>User Name:</td>
<td><input type="text" name ="user" class="inputbox"/></td>
</tr>
<tr align="left" valign="top">
<td>Password:</td>
<td><input type="password" name ="pass" class="inputbox" /></td>
</tr>
<tr align="left" valign="top">
<td></td>
<td><input type="submit" name="submit"
value="submit" class="fb8"/></td>
</tr>
</table>
<c:out value="${loginresult}" > </c:out>
</form>
</body>
</html>
Many Thanks
use setAttribute() method. This method sets the value of the attribute for the request which is retrieved later in the servlet by passing the request object through the dispatcher method. The set value of the attribute is retrieved by the getAttribute() method of the request object.
http://www.roseindia.net/servlets/request-parameter.shtml
http://www.roseindia.net/tutorial/servlet/passParameters.html

Categories

Resources