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

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

Related

java.lang.IllegalStateException: Cannot (forward | sendRedirect JSP/Java

I read some information about my issue here
java.lang.IllegalStateException: Cannot (forward | sendRedirect | create session) after response has been committed
but I didn't manage to solve my problem with it.
I've got a index.jsp page which should only be accessible to authorized users.
To do so, I use a java file which will feed the session with this information.
When I access my index, if the session is empty I go to my java part to check it, else I just display the content or not.
From my understanding, my issue is that I call this java part twice but I don't know where.
Could you please help me ?
Java code:
public class GroupeUtilisateur extends HttpServlet
{
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,IOException
{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
Connection connBDUtil = null;
String autorise = "";
autorise = CheckAuth.isAllowed(request, response, "IML-Thanact-Admin;IML-Thanact-User");
HttpSession session = request.getSession();
/* Mise en session d'une chaîne de caractères */
session.setAttribute( "autorisation", autorise );
String nextJSP = "/index.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);
}
}
And this is my index.jsp (minus non important parts)
<%# page language="java" import="java.util.*"%>
<%# page contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%# taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>
<%# page session="true" %>
<head>
// In this script I initialise a datatable and some button will only be available for admin so I need to get the autorisation to
<script type='text/javascript' class='init'>
var authScript = '${sessionScope.autorisation}'; // Récupération de l'autorisation récupérée par GroupeUtilisateur.
</script>
</head>
<body>
<div class ="err"> <c:out value="${sessionScope.message}"/> </div>
<c:set var = "auth" scope = "session" value = "${sessionScope.autorisation}"/> <!-- Récupération de l autorisation pour la session -->
<!--
<div class ="err"> Log Autorisation : [<c:out value = "${auth}"/>] </div>
<div class ="err"> Log Autorisation sans var : [<c:out value = "${sessionScope.autorisation}"/>] </div>
-->
<c:choose>
<c:when test = "${empty auth}">
<div class ="err"> Empy session we go to the java part <c:out value="${sessionScope.autorisation}"/> </div>
<script language="javascript"> document.location.href="./GroupeUtilisateur/" </script>
</c:when>
<c:when test = "${!fn:contains(auth, 'Thanact-Admin') && !fn:contains(auth, 'Thanact-User')}">
<div class ="err">Vous n êtes pas habilité à utiliser cet écran. - [<c:out value = "${auth}" />]</div>
<br/>
<input type="button" name="back" value="Retour" onClick="parent.location='/Thanact/index.jsp'" class="buttonGrey">
</c:when>
<c:otherwise>
<!-- my data-->
</c:otherwise>
</c:choose>
</body>
</html>
Thanks a lot for your help !
EDIT:
Ok so after further investigation I think I located the issue, but still don't know how to fix it.
In fact to see if the user connected belong to the correct AD group we check the session. This is a method used in different app on our ecosystem, I didn't create it.
I think, it is the one who do this :
public class CheckAuth
{
//...
public static String isAllowed(
HttpServletRequest request,
HttpServletResponse response,
String groupMember,
String millPosition,
String forWhat) throws IOException, ServletException
{
//...
String auth = request.getHeader("Authorization");
if (auth == null)
{
response.setStatus(response.SC_UNAUTHORIZED);
response.setHeader("WWW-Authenticate", "NTLM");
response.flushBuffer();
return "KO" ;
}
//...
}
}
It looks like after setting the header, the servlet is called again.
I need this bit because I can't get the username without.
How may I fix this ?

How do I insert data from JSP to MySQL database?

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.

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.

servlet error on console doesn't redirect to error page

I have a problem when I try to enter duplicate entries as you can see in the servlet below. The problem is that tomcat shows the duplicate error but the servlet doesn't redirect to the desired error page (dup_organism.jsp). However I have no problem when I enter a new record and redirect to another page, while the code is pretty much the same.
I have this servlet:
package package_ergasia;
import java.sql.*;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class AddOrganism extends HttpServlet
{
#Override
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
response.setContentType("text/html");
Connection connection= null;
String url = "jdbc:mysql://localhost:3306/";
String dbName = "ergasia";
String user = "root";
String password = "password";
String org_id = request.getParameter("id");
String oname = request.getParameter("oname");
try {
connection = DriverManager.getConnection(url + dbName, user, password);
Statement statement = connection.createStatement() ;
ResultSet resultset = statement.executeQuery("SELECT * FROM organism") ;
while(resultset.next()){
if(resultset.getString("org_id").equalsIgnoreCase(org_id)){
String contextPath= "http://localhost:8084/secured";
response.sendRedirect(response.encodeRedirectURL(contextPath + "/dup_organism.jsp"));
}
else{
PreparedStatement ps = connection.prepareStatement("INSERT INTO organism (org_id,organismName) VALUES (?,?)");
ps.setString(1, org_id);
ps.setString(2, oname);
ps.executeUpdate();
String contextPath= "http://localhost:8084/secured";
response.sendRedirect(response.encodeRedirectURL(contextPath + "/all_organisms.jsp"));
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
#Override
public String getServletInfo() {
return "info";
}
}
this is the error page dup_organism.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">
<link rel="stylesheet" type="text/css" href="../CSS/mystyle.css">
<title>Duplicate entry</title>
</head>
<body>
<h1>Error</h1>
<% String org_id = request.getParameter("org_id"); %>
<h2><div align="center">
<br><br><br>
Duplicate data <br> #Organism Id:
<% out.println(org_id); %>
</div></h2>
</body>
</html>
browser shows nothing (still on servlet page) and tomcat shows the following error: com.mysql.jdbc.exceptions.MySQLIntegrityConstraintViolationException: Duplicate entry '02' for key 'PRIMARY'
The problem why your getting null is that your using response.sendRedirect which creates a new instance of request and response object. you can do any one of the following:
Replace it with request.getRequestDispatcher(url);
Set the Org_id in the session object and retrieve it in the jsp.

passing an array from java to javascript using bean

I am trying to pass a String[] from a java class to a jsp file, i manage to pass a simple String, but i am stuck on this one for few days now. Can someone help me, i wold like the answer to be more detailed since i am new at this.
Java class:
public class UserArray extends Applet {
public String javaArray [] =
{ "array 1", "array 2" , "array 3" };
public String [] getJavaArray() {
return javaArray;
}
}
JSP
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="s" uri="/struts-tags" %>
<%# taglib prefix="sb" uri="/struts-bootstrap-tags" %>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<jsp:useBean id ="array" class="eu.xyx.ztr.applet.UserArray"/>
</head>
<body>
<h4>
<jsp:getProperty name ="array" property="javaArray"/>
</h4>
</body>
So far i have maage to obtain the address of String[]. I just want to obtain the values of javaArray and if it is posible to obtain them in a form like this:
<script>
function addrow(tableID){
var numeuser=document.numeuser;
var nume=["adrian","cristi","levi",numeuser];
var prenume=["ric","dre","asd"];
var email=["rew#td","qq#eqwq","ee#ew"];
Servlet
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
ArrayList myArray = new ArrayList();
myArray.add("array 1");
myArray.add("array 2");
myArray.add("array 3");
request.setAttribute("myArray", myArray);
//then call jsp :
RequestDispatcher rd = request.getRequestDispatcher("mypage.jsp");
rd.forward(request, response);
}
jsp
<body>
<c:forEach var="myarr" items="${myArray}">
<c:out value="${myarr}" />
</c:forEach>
</body>
You should use javascript library like google JSON or jackson JSON for the same
have a look at these links
http://viralpatel.net/blogs/creating-parsing-json-data-with-java-servlet-struts-jsp-json/

Categories

Resources