How do I insert data from JSP to MySQL database? - java

I have already made the jsp file (which receives data from the html form) and the database (using MySQL workbench).
contact.jsp code:
<%#page contentType="text/html" pageEncoding="UTF-8" errorPage="errorpage.jsp" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h3>Messages from contact us page</h3>
<ul>
<li><p><b>Name:</b>
<%= request.getParameter("name")%>
</p></li>
<li><p><b>Email:</b>
<%= request.getParameter("txtEmail")%>
</p></li>
<li><p><b>Message:</b>
<%= request.getParameter("txtMessage")%>
</p></li>
</ul>
</body>
</html>
Database name: KSG_Database
Schema: web_data
Table: contact_messages
Columns: c_name , email , txtmessage
Now I just need the code to insert the input data from the form to the database. Can someone please help me?

First, Import the JDBC Driver:
<%#page import="java.sql.DriverManager"%>
<%#page import="java.sql.ResultSet"%>
<%#page import="java.sql.Statement"%>
<%#page import="java.sql.Connection"%>
else
<%#page import="java.sql.*"%>
Then Second, Value your Strings:
String your_name = request.getParameter("name");
String your_Email = request.getParameter("txtEmail");
String your_txtMessage = request.getParameter("txtMessage");
Then, create a connection to your database:
try{
Class.forName("com.mysql.jdbc.Driver");// Driver to establish connection to the database
Connection con1=DriverManager.getConnection("jdbc:mysql://localhost:3306/KSG_Database","your_id","your_pass"); //Create connection using your ID and Password
Statement st1=con1.createStatement();
ResultSet rs1=st1.executeQuery("SELECT * FROM contact_messages");
while(rs1.next()){
//-----------------------------Then, Create an InsertQuery using a String:---------------------
String InsertQuery = "insert into contact_messages (c_name,email,txtmessage) values('"+your_name+"','"+your_Email+"','','"+your_txtMessage+"');";
//-----------------------------Finally, Execute your Insert Query:-----------------------------
st1.executeUpdate(InsertQuery);}}
catch(Exception error){
out.println(error);}
It worked for me.
If you have doubts ask me! :-)

You have to call, from the JSP and through a form, an "action". That "action" will process the data it gets from the jsp and do whatever it needs to do (the connection with the database), and finally return to the servlet the nextPage.
The form in the jsp should look like this:
<form action="<%= response.encodeURL("/path/nameOfController?action=accions.nameAction") %>" method="POST">
// whatever data you want to send to db in inputs like this:
<input type="HIDDEN" name="name" value=<%=variableName%>>
</form>
What's inside action is the path of the "action" you want to call. You will process that in the controller, and use that "nameAction" to call the action as you prefere (here I use a Factory to call the classes). Here's how I manage it:
In the doGet of the controller:
Action action=null;
String nextPage=null;
String nameAction = request.getParameter("action");
// get the action acording to what was sent through the jsp form
action= FactoryImpl.getReference().getAction(nameAction);
// run the action with whatever method, in this case it's called execute
nextPage = action.execute(request, response);
// nextPage has returned the name of the next jsp, now just sent the redirect
RequestDispatcher rd = getServletContext().getRequestDispatcher(response.encodeURL(nextPage));
rd.forward(request, response);
Now, you just have to create the "action", and inside the execute method, connect to the db and make the inserts you need to. Also, I would recommend to make the connection in another class and get it from the action, just so you don't have it all in the same class.
The Action class should something like this:
package whatever;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import presentacio.Action;
public class nameOfTheAction implements Action {
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception {
//connection with db
return "nameOfNextJspToSendToClient";
}
}
Now, just if you're wondering, I use an interface which is Action, and all the actions implement that interface. If you want to know how the interface looks like, here it is, but you don't need to do it like me:
package presentacio;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public interface Action{
public String execute(HttpServletRequest request, HttpServletResponse response) throws Exception;
}
If I haven't explained myself well enough, or you want me to detail something, just ask.

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.

Variables not making it from one JSP to the other when using HttpSession

I am having trouble retrieving any type of parameter from one jsp page to the other using doPost, and a form where my method is post. Note below is a minimal example.
First, I have two pages:
Here is search.jsp:
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<!DOCTYPE html>
<html>
<head>
<title>search</title>
<body>
<form name="search" method="post" action="search_results.jsp">
<p>
<input type="text" class="inputTitle" id="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
<button type="submit">Search</button>
<p>
</form>
</body>
</html>
And my search_results.jsp
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<title>search results</title>
<body>
<p>Title: ${movie.title}</p>
</body>
</html>
Now I have a class called SearchServlet.java:
#WebServlet("/search")
public class SearchServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
request.getRequestDispatcher("search.jsp").forward(request,response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
HttpSession session = request.getSession();
String title = request.getParameter("inputTitle");
String searchTitle;
try {
if(title != null && !title.isEmpty()) {
searchTitle = "hello";
} else {
searchTitle = "world";
}
session.setAttribute("movie.title", searchTitle);
request.getRequestDispatcher("search_results.jsp").forward(request, response);
} catch(ServletException e) { e.printStackTrace(); }
}
}
No matter what I enter the result (movie.title) always ends up being empty and so I get world on search_results.jsp. Why is my parameter not being passed to search_results.jsp?
It will not happen if you bypass the servlet
Look at your form action
<form name="search" method="post" action="search_results.jsp">
You are sending the post request directly to the search_results.jsp: you should send it to the servlet instead (mapped # /search)
<form name="search" method="post" action="search">
Then from the servlet you should forward the request to the search_result.jsp, which you actually did.
In addition to that when you call request.getParameter you have to keep in mind that what counts is the name of the input field, not the id. You should change the id attribute to name
<input type="text" class="inputTitle" name="inputTitle" value="${fn:escapeXml(param.inputTitle)}">
Lastly, hopefully :) the '.' (dot) might cause issues:
session.setAttribute("movie.title", searchTitle);
When you retrieve the attribute the dot notation indicates that you are accessing a field in a object called movie
<p>Title: ${movie.title}</p> <!-- you are accessing the title property of a movie object !-->
but you do not have that...you have a movietitle, a String presumably. Change the attribute name to something like movietitle without the dot and retrieve it in the jsp the same way. the above lines will become:
session.setAttribute("movietitle", searchTitle);
<p>Title: ${movietitle}</p>
That should solve the issue.

Retrieving data from database using ArrayList and displaying it in JSP [duplicate]

This question already has answers here:
How to install JDBC driver in Eclipse web project without facing java.lang.ClassNotFoundexception
(13 answers)
Closed 5 years ago.
MySQL DB server used. Database name: library, table name: book.
table contains the following columns with given type and order:
title(varchar),
author(varchar),
book_id(int)- primary key,
count (int),
favs (int).
I want to view all the records of this table using ArrayList in servlet and JSP.
Here are my codes:
ViewBook (servlet)
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;
import java.util.*;
import java.sql.*;
import p1.*;
public class ViewBook extends HttpServlet
{
public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,IOException
{
PrintWriter out=res.getWriter();
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3307/library", "root", "admin");
PreparedStatement ps=con.prepareStatement("select * from book");
ResultSet rs=ps.executeQuery();
ArrayList<Book> books=new ArrayList<Book>();
while(rs.next())
{
Book b= new Book();
b.bookID=rs.getInt(3);
b.bookTitle=rs.getString(1);
b.bookAuthor=rs.getString(2);
b.bookCopies=rs.getInt(4);
b.bookFavs=rs.getInt(5);
books.add(b);
}
req.setAttribute("bookslist",books);
con.close();
RequestDispatcher rd=req.getRequestDispatcher("/view_book.jsp");
rd.forward(req,res);
}
catch(Exception e)
{
out.println(e);
}
}
}
Package p1 contains the following class:
Book.java
package p1;
public class Book
{
public int bookFavs,bookID, bookCopies;
public String bookTitle;
public String bookAuthor;
}
The JSP to which the request is dispatched- view_book.jsp:
<html>
<body>
<head>
<title>
View Books
</title>
</head>
<body>
<table border=2>
<tr>
<th>Book ID</th>
<th>Title</th>
<th>Author</th>
<th>No. of copies AVAILABLE</th>
<th>Number of favourites</th>
</tr>
<%
ArrayList<Book> dbooks=(ArrayList)request.getAttribute("bookslist");
Iterator it=dbooks.iterator();
while(it.hasNext())
{
Book b=(Book)it.next();
%>
<tr>
<td><%=b.bookID%></td>
<td><%=b.bookTitle%></td>
<td><%=b.bookAuthor%></td>
<td><%=b.bookCopies%></td>
<td><%=b.bookFavs%></td>
</tr>
<%
}
%>
</table>
</body>
</html>
The servlet and JSP aren't working. I know it's a vague question. Please point the blunders made. And solutions if possible!
The JSP file cant compile because the ArrayList needs an import directive :
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%# page import="java.util.*" %>
You have to import your Book and ArrayList and Iterator in your JSP. Otherwise your JSP file will not compile.
you can import multiple classes by using , instead of ; like in the java. If you specify ; then you JSP will throw Exception.
<%# page import="java.util.ArrayList,java.util.Iterator, p1.Book" %>
Import java.util.*;to import the ArrayList class in the jsp. Then, also import the required classes e.g. the Book class too. It should work.
The problem is quite simple: you don't execute the servlet anytime. You must to invoke the servlet from another .jsp then, inside that servlet, call the other jsp.

retrieve data from database table and display it in atable with html

i am a beginer and am currently working on my final school project which require retrieving data from a database table and displaying the datas in an html page. i have searched alot but still no progress. i was linked to this site through google, i saw a format and i try to do the same thing but after running the code i get this error
Exception report
message An exception occurred processing JSP page /crimeinfo.jsp at line 32 description The server encountered an internal error that prevented it from fulfilling this request.
exception
org.apache.jasper.JasperException: An exception occurred processing JSP page /crimeinfo.jsp at line 32
29:
30:
31: <%List <String> data =(List)request.getAttribute("data");
32: Iterator <String> itr = data.iterator() ;
33: for (itr = data.iterator();
34: itr.hasNext();)
35: {%>
please i need help. i dont known what else to do. thnks...
viewcrime.xml
<?xml version="1.0" encoding="UTF-8"?>
<!--web.xml code-->
<servlet>
<servlet-name>viewcrimereport</servlet-name>
<servlet-class>viewcrimereport</servlet-class>
<servlet-mapping>
<servlet-name>viewcrimereport</servlet-name>
<url-pattern>viewcrimereport</url-pattern>
</servlet-mapping></servlet>
viewcrimereport.java
public class viewcrimereport extends javax.servlet.http.HttpServlet implements javax.servlet.Servlet {
private ServletConfig config;
String page = "crimeinfo.jsp";
public void init(ServletConfig config)
throws ServletException{
this.config = config; }
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
response.setContentType("text/html");
Connection conn = null;
String url = "jdbc:mysql://localhost/citycrime";
String userName = "root";
String passw = "jids";
PreparedStatement pst = null;
ResultSet rs;
ArrayList<String> datalist = new ArrayList<String>();
try{
int i=0;
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(url, userName, passw);
pst = conn.prepareStatement("");
String sql ="select suspectname,suspectaliases,suspectht,suspectgender,features,crimeaddress,crimetype,caseno,casestatus from crimereport";
pst.executeQuery(sql);
rs = pst.getResultSet();
while(rs.next()){
datalist.add(rs.getString("suspectname"));
datalist.add(rs.getString("suspectaliases"));
datalist.add(rs.getString("suspectht"));
datalist.add(rs.getString("suspectgender"));
datalist.add(rs.getString("features"));
datalist.add(rs.getString("crimeaddress"));
datalist.add(rs.getString("crimetype"));
datalist.add(rs.getString("caseno"));
datalist.add(rs.getString("casestatus"));}
rs.close();pst.close(); }
catch(Exception e){System.out.println("Exception is;"+e);}
request.setAttribute("data",datalist);
RequestDispatcher dispatcher = request.getRequestDispatcher(page);
if (dispatcher != null){
dispatcher.forward(request, response);
}
}
}
crimeinfo.jsp
<%# page language="java" import="java.sql.*" import="java.util.*"
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>Crime Report</title>
</head>
<body>
<table border="1" with="600">
<tr><td><tb><td>SuspectName</td></b>
<td><tb>SuspectAlias</b></td>
<td><tb>suspectaliases</tb></td>
<td><tb>Height</tb></td>
<td><tb>suspectht</tb></td>
<td><tb>Gender</tb></td>
<td><tb>suspectgender</tb></td>
<td><tb>Features</tb></td>
<td><tb>features</tb></td>
<td><tb>Address</tb></td>
<td><tb>crimeaddress</tb></td>
<td><tb>CrimeType</tb></td>
<td><tb>crimetype</tb></td>
<td><tb>CaseNumber</tb></td>
<td><tb>caseno</tb></td>
<td><tb>Status</tb></td>
<td><tb>casestatus</tb></td></tr>
<% Iterator <String> itr;%>
<%List data =(List)request.getAttribute("datalist");
for (itr = data.iterator();
itr.hasNext();){%><tr>
<%String s =(String)itr.next(); %>
<td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td>
<tr><td><%=itr.next()%>></td></tr><%} %>
</table>
</body>
</html>
At line 32, make it Iterator itr = data.iterator() ; I advise you to use while(itr.hasNext() instaed of for loop for more clarity of the code. Also, the initialization part in the for loop is retundant.
rename your xml file to web.xml and put it as \WEB-INF\web.xml
in web.xml, url-pattern should be <url-pattern>/viewcrimereport</url-pattern>
for your servlet, since you have already extended HttpServlet class, there is no need to implement Servlet interface. HttpServlet class already implements that interface
you have not closed your connection. use conn.close().
in your jsp, it should be <%List data =(List)request.getAttribute("data"); because you have set request attribute with name data and not "datalist"
use of scriptlets (those <% %> things) are discouraged. see this
since you are not outputting anything from your servlet to your browser, you can omit the following code PrintWriter out=response.getWriter();
response.setContentType("text/html");
in my personal opinion, i would suggest to use service instead of doGet(). Service method will itself call the doGet method. Plus it can also invoke other meyhods like doPost, doHead etc if it requires.
You can use the datalist.get(column index) method of ArrayList. For more details refer to:
http://www.tutorialspoint.com/java/java_arraylist_class.htm

How to pass an Object from the servlet to the calling JSP [duplicate]

This question already has answers here:
Passing an object from JSP page back to Servlet
(3 answers)
Closed 1 year ago.
How to pass an Object from the servlet to the calling JSP.
I have a JSP calling a servlet. From this servlet, I am setting the properties of a viewBean.
Now, I want to get this property valued set from Servlet on a JSP page.
How to make this ViewBean object available on JSP from Servlet.
Put the object either in session or request in servlet like :
String shared = "shared";
request.setAttribute("sharedId", shared); // add to request
request.getSession().setAttribute("sharedId", shared); // add to session
this.getServletConfig().getServletContext().setAttribute("sharedId", shared); // add to application context
You can read it in jsp like :
<%# taglib prefix="c" uri="http://java.sun.com/jstl/core" %>
<body>
<cut value= "${shared}"/>
<cut value= "${requestScope.shared}"/>
<cut value= "${requestScope.request.shared}"/>
${shared}
Or read it using scriptlet with code :
<%
String shared = (String)request.getAttribute("sharedId");
String shared1 = (String)request.getSession().getAttribute("sharedId");
String shared2 = (String)this.getServletConfig().getServletContext().getAttribute("sharedId");
%>
Well, firstly you need to set the value so you can access it from your page, something like:
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class MyServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) {
// Do some work.
Person value = new Person("Matthew", "Abbott";
request.setAttribute("person", person);
// Forward to to the JSP file.
request.getRequestDispatcher("showValue.jsp").forward(request, response);
}
}
Next thing, you can access the properties of your value, using Expression Language:
<!DOCTYPE html>
<html>
<head>
<title>${person.forename} ${person.surname}</title>
</head>
<body>
<h1>Hello ${person.forename}!!!</h2>
</body>
</html>
Something like this should work
request.setParameter("nameOfmyObjectParam",MyObject); //or request.setAttribute
String yourJSP = "/WEB-INF/pages/yourJSP.jsp";
RequestDispatcher rd = getServletContext().getRequestDispatcher(yourJSP);
rd.forward(request, response);
Set the bean as request attribute in servlet using the Servlet API as follows -
request.setAttribute("viewBean", viewBean);
and retrieve (use) it in the JSP using EL as follows -
${requestScope.viewBean}
Add that ViewBean object in session attribute in servlet. And get that variable in jsp.
in servlet
ViewBean viewbwanObject= new ViewBean()
session.setAttribyte("obj",vi);
in jsp.
<%
ViewBean v= (ViewBean)session.getAttribute("obj")
%>

Categories

Resources