I'm developing a simple application with Eclipse and Apache in which i display a table created with MySQL pertaining to products (with columns id, name and price) using Java, JSP and HTML. I also have a text box with a button which allows to filter the table showing only the products which have a bigger price than the one inserted on the text box.
Everything seems to be working fine including the filter. However, when i run the application for the first time, the full table isn't displayed like it should. It only displays when i use the filter. I'm not sure but there seems to be some conflict between the scriptlet for the filter elements and the table because if i comment the scriptlet for the filter elements in the JSP file, the table loads on startup like it should.
This is the code for JSP class which loads the table and the search elements (with some Bootstrap styling):
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.sql.Connection,java.sql.ResultSet,java.sql.DriverManager,project1.components.DBConnector, project1.components.Filter"%>
<!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>Product</title>
<style type="text/css">
<%#include file="bootstrap/css/bootstrap.css" %>
<%#include file="bootstrap/css/bootstrap-theme.css" %>
</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="bootstrap/js/jquery.js"></script>
<script src="bootstrap/js/bootstrap.js"></script>
</head>
<body>
<%
DBConnector dbc = new DBConnector();
Connection conn = dbc.connect();
String query = "select * from product";
%>
</body>
<form method="post">
<div class="col-xs-2 col-xs-offset-5">
<input type="text" class="form-control" name="value" value=<%=request.getParameter("firstinput")%>>
<br><br>
<input type="submit" class="form-control" name="submit" value="Filter">
<%
if(!request.getParameter("value").isEmpty()){
String val = request.getParameter("value");
Filter ft = new Filter();
query = ft.filterByValue(val);
}
%>
</div>
<br></br>
<table class = 'table table-hover'>
<tr>
<td>Id</td>
<td>Name</td>
<td>Product</td>
</tr>
<%
try
{
ResultSet rs = dbc.obtainTable(query);
while(rs.next())
{
%><tr>
<td><%=rs.getInt("ID") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getFloat("PRICE") %></td>
</tr> <%
}
%>
</table>
<%
rs.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</form>
</html>
The Java class which connects to the database and obtains data with a given query to be loaded on the table defined in the previous JSP file:
package project1.components;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBConnector {
String url = "jdbc:mysql://localhost:3306/products?autoReconnect=true&useSSL=false";
String user = "root";
String pass = "root";
public Connection connect() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
return (Connection) DriverManager.getConnection(url,user,pass);
}
public ResultSet obtainTable(String query) throws ClassNotFoundException, SQLException{
Connection cn = this.connect();
Statement stmt= (Statement) cn.createStatement();
return stmt.executeQuery(query);
}
}
And finally, the filter itself defined in Java:
package project1.components;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Filter {
public String filterByValue(String val) throws ClassNotFoundException, SQLException{
int num = Integer.parseInt(val);
String query = null;
if(num >= 0){
query = "select * from product where price >" + val;
}
else{
query = "select * from product";
}
return query;
}
}
Any help would be really appreciated.
Could you please replace the following:
if(!request.getParameter("value").isEmpty()){
by:
if(request.getParameter("value")!=null && !request.getParameter("value").trim().isEmpty()){
and see the results?
Related
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.
I'm trying to get my java code to connect to the database. I swear it was connecting a few hours ago and suddenly it's not. I have reinstalled, restarted xampp, eclipse my laptop. I even uninstalled and reinstalled mysql.
Here's my .java file:
import java.sql.DriverManager;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.jdbc2.optional.MysqlDataSource;
public class Connect_db {
// private static final String url = "jdbc:mysql://localhost:3306/sjsu";
// private static final String user = "root";
// private static final String password = "";
//
// public static void main(String[] args) throws Exception {
// java.sql.Connection con = null;
// try {
// Class.forName("com.mysql.jdbc.Driver");
// con = DriverManager.getConnection(url, user, password);
// // commented since doesn't exists in Java 6
// // System.out.println(con.getSchema());
// System.out.println(con.getCatalog());
// } finally {
// con.close();
// }
// }
private static MysqlDataSource ds = null;
public static MysqlDataSource getDataSource(String db_name) {
if (ds == null) {
// db variables set here
getDataSource("jdbc:mysql://localhost:3306", "root", "", 3306);
}
ds.setDatabaseName(db_name);
return ds;
}
private static void getDataSource(String db_url, String db_user, String db_password, int db_port) {
try {
ds = new MysqlDataSource();
ds.setServerName(db_url);
ds.setUser(db_user);
ds.setPassword(db_password);
ds.setPort(db_port);
} catch (Exception e) {
System.out.println("MysqlDataSource err: " + e.getMessage());
e.printStackTrace();
}
}
}
My .jsp file
<%# 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>atozknowledge.com demo Regjsp</title>
</head>
<body>
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<%
String user=request.getParameter("userid");
session.putValue("userid",user);
String pwd=request.getParameter("pwd");
String fname=request.getParameter("fname");
String lname=request.getParameter("lname");
String email=request.getParameter("email");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = Connect_db.getDataSource("sjsu").getConnection();
Statement st= con.createStatement();
ResultSet rs;
int i=st.executeUpdate("insert into users values ('"+user+"','"+pwd+"','"+fname+"', '"+lname+"','"+email+"')");
out.println("Registered");
%>
Home
</body>
</html>
My html:
<!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>atozknowledge.com demo Registration</title>
</head>
<body>
<form action="reg.jsp" method="post">
User name :<input type="text" name="userid" /><br/><br/>
password :<input type="password" name="pwd" /><br/><br/>
First name :<input type="text" name="fname" /><br/><br/>
Last name :<input type="text" name="lname" /><br/><br/>
Email :<input type="text" name="email" /><br/><br/>
<br/><br/>
<input type="submit" />
</form>
</body>
</html>
The error
It used to be able to put the userid, pwd, ... etc in my database and now it can't.
As the error states, it cannot find the class Connect_db. You need to add an explicit import for Connect_db to your JSP, that is add:
<%# page import ="package.of.Connect_db" %>
Querying directly from JSP is a poor choice, your should separate getting the data from displaying the data.
Tomcat also provides support for creating and registering data sources, use that instead of rolling your own. Especially, as MysqlDataSource doesn't provide connection pooling.
And finally, concatenating values into your query string is unsafe, especially with user provided input, as it leaves you open to SQL injection. Instead you should use a prepared statement with parameters. Please take a look at Using Prepared Statements in the JDBC tutorial.
I recommend you instead of giving the my.jsp inn the from action it is better to use a servlet. Maybe it can solve your. Create a new servlet and write your code inside of post method.
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,
I know it is a simple task but don't able to find out what is the problem.
I made one login.jsp which is starting page.
LoginAction.jsp which will validate the user
I think there is some problem with ReqestDispatcher.
I am trying to find out solution from past 2 days and I am exhausted please help me.
All the table names and their field names are correct.
This is LoginAction.jsp
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="DataBase.DBCONNEction"%>
<%#page import="java.sql.PreparedStatement"%>
<%#page import="java.sql.Connection"%>
<%#page import="javax.servlet.RequestDispatcher"%>
<%#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>
<%
String uname = request.getParameter("name");
String pass = request.getParameter("pass");
String unam, upass;
Connection con = null;
PreparedStatement prst = null;
Statement stm = null;
DBCONNEction DBC = null;
con = DBC.getConnection();
stm = con.createStatement();
RequestDispatcher rd = request.getRequestDispatcher("/welcome.jsp");
ResultSet rs = stm.executeQuery("select password from details where username = '" + uname + "'");
if (rs.next()) {
if (rs.getString("password").equals(pass)) { //If valid password
session.setAttribute("User", uname);
}else {
request.setAttribute("Error", "Invalid password.");
rd = request.getRequestDispatcher("/login.jsp");
}
}
else {
request.setAttribute("Error", "Invalid user name.");
rd = request.getRequestDispatcher("/login.jsp");
}
rd.forward(request, response);
%>
</body>
</html>
This is login.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Knowledge Repository System</title>
<link rel="stylesheet" type="text/css" href="index.css">
</head>
<body>
<div class="header">
<h1>Knowledge Repository System JSP</h1>
<form id="search" action="loginAction.jsp" method="POST">
<label>Username <input type="text" name="name" id="s-user" style="width:90%;" required></label>
<label>Password<input type="password" name="pass" id="s-pass" style="width:90%;" required></label>
<input type="submit" class="submit" value="Submit">
</form>
</div>
Admin Panel
<div class="nav">
<h2 style="font-size: 36px"><strong>Sign Up</strong></h2>
<form action="details" method="POST">
<signup>
<p><input type="text" name="name" required placeholder="Username"></p>
<p><input type="password" name="pass" required placeholder="password"></p>
<p><input type="text" name="email" required placeholder="xyz#abc.com"></p>
<p><input type="submit" value="Sign Up" align="center"></p>
</signup>
</form>
</div>
</body>
</html>
This is DBCONNEction.java
package DataBase;
import java.sql.Connection;
import java.sql.DriverManager;
public class DBCONNEction {
private static String URL = "jdbc:mysql://localhost:3306/repository";
private static String DRIVER = "com.mysql.jdbc.Driver";
private static String pass = "myserver";
private static String user = "root";
static Connection con = null;
static {
try {
Class.forName(DRIVER);
con = DriverManager.getConnection(URL, user, pass);
} catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection() {
return con;
}
}
I am trying to retrieve the data from a mysql database on a jsp page, When the page loads, it loads the latest data (which is what i want), but then when i click on the refresh button i made it refreshes the table with older data and then the button doesnt work after that (wont refresh the table).
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*, javax.sql.*, java.io.*, javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
<title>Main Page</title>
<h1>
<strong>test page</strong>
</h1>
<hr />
<canvas id="mycanvas" width="400" height="186"></canvas>
<script src="JavaScript/smoothie.js"></script>
<script src="JavaScript/chart.js"></script>
<script src="JavaScript/basic.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("#refresh").click(function(){
$("#heart_rate").load("basic2.jsp")
});
});
</script>
</head>
<body>
<br>
<br>
<button id="refresh">Refresh table</button>
<br>
<br>
<form method="post" name="form">
<table id="heart_rate" border="1">
<tr>
<th>Sensor id</th>
<th>Time stamp</th>
<th>Heart rate</th>
<th>Event time</th>
</tr>
<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "Avantidrome";
String driver = "com.mysql.jdbc.Driver";
String un ="root";
String pw="root";
Statement st;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db, un, pw);
String sql = "select * from avantidrome.heartratedata order by timestamp DESC limit 10";
st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
%>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
</tr>
<%
}
%>
<%
} catch(Exception e){
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>
once the button is clicked it calls basic.jsp which is just:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="java.sql.*, javax.sql.*, java.io.*, javax.naming.*"%>
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<br>
<br>
<form method="post" name="form">
<table id="heart_rate" border="1">
<tr>
<th>Sensor id</th>
<th>Time stamp</th>
<th>Heart rate</th>
<th>Event time</th>
</tr>
<%
Connection con = null;
String url = "jdbc:mysql://localhost:3306/";
String db = "Avantidrome";
String driver = "com.mysql.jdbc.Driver";
String un ="root";
String pw="root";
Statement st;
try{
Class.forName(driver).newInstance();
con = DriverManager.getConnection(url + db, un, pw);
String sql = "select * from avantidrome.heartratedata order by timestamp DESC limit 10";
st = con.createStatement();
ResultSet rs = st.executeQuery(sql);
%>
<%
while(rs.next())
{
%>
<tr>
<td><%=rs.getString(1)%></td>
<td><%=rs.getString(2)%></td>
<td><%=rs.getString(4)%></td>
<td><%=rs.getString(5)%></td>
</tr>
<%
}
%>
<%
} catch(Exception e){
e.printStackTrace();
}
%>
</table>
</form>
</body>
</html>
all it needs to do is for the button to select the newest data from the database and return it to the table whenever it is clicked.
There are two ways to do what you want:
When the user press the refresh button, you simple refresh the page (this should be so fast that he wont notice that the page changed)
Using ajax. So, if choose this option you need to understand that to do this you only need one jsp (the one that loads the page in the begin and has the refresh button), a scrip of javascript that handles the refresh button and uses ajax to get the new data, and a servlet that receives the ajax request and returns an ajax response in json/xml containing the updates.
In my opinion, I prefer the first option, but if you choose to go for the second one, heres another SO post that may help you: How to use Servlets and Ajax?