Servlets Jsp And Null Pointers - java

Hi all I have a website where a Lecturer assigns a tutor to a lab, Currently I have a list of tutors where I can click assign and then it takes the user to another page where there is a drop down box and they can select which lab they would like the tutor to teach. It's supposed to submit the id of the lab and the id of the user to the database.
Currently When a user gets the tutor list, they click a link called 'assign' which puts the tutors id up in the url, then they have a list of tutes they can select, once I've selected the tute and click submit I get the following error.
description The server encountered an internal error () that prevented it from fulfilling this request.
exception
java.lang.NumberFormatException: null
java.lang.Integer.parseInt(Unknown Source)
java.lang.Integer.parseInt(Unknown Source)
TutorAssign.doPost(TutorAssign.java:97)
javax.servlet.http.HttpServlet.service(HttpServlet.java:641)
javax.servlet.http.HttpServlet.service(HttpServlet.java:722)
the sendBack method is running but the doPost is not and it's pointing to the line where I get the request parameter as being null - int user_id = Integer.parseInt(request.getParameter("id"));
how can i fix this? I'll include the entirety of my servlet for better clarification
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
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 javax.servlet.http.HttpSession;
/**
* Servlet implementation class TutorAssign
*/
#WebServlet("/TutorAssign")
public class TutorAssign extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TutorAssign() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendBack(request, response);
}
private void sendBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
//Set data you want to send back to the request (will be forwarded to the page)
//Can set string, int, list, array etc.
int user_id = Integer.parseInt((String)request.getParameter("id"));
String sql = "SELECT l.id,s.name,l.day,l.time,l.room" +
" FROM subject s, lab l " +
" WHERE s.user_id="+(Integer)session.getAttribute("id");
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got a hj");
System.out.println(session.getAttribute("id"));
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(sql);
System.out.println(res);
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
if (res.next()){
do{
list1.add(res.getString(1));
list2.add(res.getString(2)+" "+res.getString(3)+" "+res.getString(4)+" "+res.getString(5));
}while(res.next());
System.out.println("Outside");
String[] arr1 = list1.toArray(new String[list1.size()]);
String[] arr2 = list2.toArray(new String[list2.size()]);
System.out.println(list1);
request.setAttribute("res1", arr1);
request.setAttribute("res2", arr2);
request.setAttribute("user_id", user_id);
}
}catch (SQLException e) {
}
catch (Exception e) {
}
//Decides what page to send the request data to
RequestDispatcher view = request.getRequestDispatcher("TutorAssign.jsp");
//Forward to the page and pass the request and response information
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int user_id = Integer.parseInt((String)request.getParameter("id"));
System.out.println(user_id);
int lab_id = 0;
System.out.println("I got a blow job");
String message = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
System.out.println(user_id);
Statement s = con.createStatement();
String sql = "INSERT INTO user_lab" +
" (user_id, lab_id)" +
" VALUES" +
" ('" + user_id + "'," +
" '" + lab_id + "')";
System.out.println(sql);
int i = s.executeUpdate(sql);
if (i==1) {
message = "Successfully assigned a tutor.";
response.sendRedirect("Lecturer_labs");
}
s.close();
con.close();
}
catch (SQLException e) {
message = "Error." + e.toString();
boolean error = true;
}
catch (Exception e) {
message = "Error." + e.toString();
boolean error = true;
}
if (message!=null) {
PrintWriter out = response.getWriter();
out.println("<B>" + message + "</B><BR>");
out.println("<HR><BR>");
}
}
// TODO Auto-generated method stub
}
here is my jsp code
<form name ="TutorAssign" ACTION="TutorAssign" method="post">
<input type="hidden" name="user_id" value="user_id"/>
<select name="lab_id">
<%
for(int i=0; i<list1.length;i++)
{
out.println("<option value="+list1[i]+"> "+list2[i]+" </option>");
} %>
</select>
<input type=SUBMIT value="Submit" name="Submit" />
</form>

It appears that id is not being passed into your servlet when a HTTP POST occurs. You could guard against this by adding a suitable guard statement:
if (request.getParameter("id") == null) {
// handle non existance of id
}
The reason that id is not being passed in is that you don't have any input field in your JSP form to pass in this value. This would look like:
<input type="hidden" name="id" value="your_id_here"/>

The problem is here:
<form name ="TutorAssign" ACTION="TutorAssign" method="post">
<select name="labs">
<%
for(int i=0; i<list1.length;i++)
{
out.println("<option value="+list1[i]+"> "+list2[i]+" </option>");
} %>
</select>
More specifically:
<select name="labs">
If you would either change the name to id OR use request.getParameter("labs"), you will probably get what you want.

Related

Drop down list is causing an error on the jsp page

I was trying to create the drop-down list to delete the booktag value by retrieving the data and using the remove function from the DAO class but it made this error: "java.lang.NumberFormatException: For input string: "isbn13" ". I have found out that the servlet must gain access to the name attribute so I inserted this code int isbn13ID = Integer.parseInt(request.getParameter("booktag"));. But the problem is that eclipse tells me that the variable is unused so I am not sure what else to do for the select tag to gain access to the servlet variable. Here is code:
JSP:
<!-- Header -->
<jsp:include page="header.jsp" />
<!-- JSTL includes -->
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn"%>
<header>
<div class="container">
<h1>PUBHUB <small>Add Booktag</small></h1>
<hr class="book-primary">
<form action="AddBookTag" method="post" class="form-horizontal">
<div class="form-group">
<label for="isbn13" class="col-sm-4 control-label">ISBN 13</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="isbn13" name="isbn13" placeholder="ISBN 13" required="required" value="${param.isbn13 }" />
</div>
</div>
<div class="form-group">
<label for="nametag" class="col-sm-4 control-label">NameTag</label>
<div class="col-sm-5">
<input type="text" class="form-control" id="nametag" name="nametag" placeholder="NameTag" required="required" value="${param.nametag }" />
</div>
</div>
</form>
</div>
</header>
<section>
<div class="container">
<h1><small>Delete Booktag</small></h1>
<form action="DeleteBookTag" method="post" class="form-horizontal" >
<select name="booktag">
<c:forEach items="${booktags}" var="booktag">
<option value="${booktags.isbn13}">${booktags.isbn13}</option>
<option value="${booktags.nameTag}">${booktags.nameTag}</option>
</c:forEach>
</select>
</form>
</div>
</section>
<!-- Footer -->
<jsp:include page="footer.jsp" />
AddBookTag Servlet:
package examples.pubhub.servlets;
import java.io.IOException;
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 examples.pubhub.model.BookTag;
import examples.pubhub.dao.BookTagDAO;
import examples.pubhub.utilities.DAOUtilities;
#WebServlet("/AddBookTag")
public class AddBookTagServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.getRequestDispatcher("").forward(request, response);
}
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//String isbn13 = req.getParameter("isbn13");
BookTagDAO database = DAOUtilities.getBookTagDAO();
BookTag bookTag = new BookTag();
bookTag.setIsbn13(req.getParameter("isbn13"));
bookTag.setNameTag(req.getParameter("nametag"));
boolean isSuccess = database.addNameTag(bookTag);
if(isSuccess){
req.getSession().setAttribute("message", "Book Tag successfully added");
req.getSession().setAttribute("messageClass", "alert-success");
// We use a redirect here instead of a forward, because we don't
// want request data to be saved. Otherwise, when
// a user clicks "refresh", their browser would send the data
// again!
// This would be bad data management, and it
// could result in duplicate rows in a database.
resp.sendRedirect(req.getContextPath() + "/AddBookTag");
}else {
req.getSession().setAttribute("message", "There was a problem publishing the book");
req.getSession().setAttribute("messageClass", "alert-danger");
req.getRequestDispatcher("bookTag.jsp").forward(req, resp);
}
}
}
BookTAG Servlet
package examples.pubhub.servlets;
import java.io.IOException;
import java.util.List;
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 examples.pubhub.model.BookTag;
import examples.pubhub.dao.BookTagDAO;
import examples.pubhub.utilities.DAOUtilities;
#WebServlet("/BookTag")
public class BookTagServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Populates the drop down list
BookTagDAO dao = DAOUtilities.getBookTagDAO();
List<BookTag>tagList = dao.getAllBookTags();
request.getSession().setAttribute("booktags", tagList);
request.getRequestDispatcher("bookTag.jsp").forward(request, response);
}
}
Delete BookTag Servlet
package examples.pubhub.servlets;
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 examples.pubhub.model.BookTag;
import examples.pubhub.dao.BookTagDAO;
import examples.pubhub.utilities.DAOUtilities;
#WebServlet("/DeleteBookTag")
public class DeleteBookTagServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
boolean isSuccess = false;
String isbn13 = request.getParameter("isbn13");
String nameTag = request.getParameter("nametag");
BookTag booktag = new BookTag();
booktag.setIsbn13(isbn13);
booktag.setNameTag(nameTag);
BookTagDAO dao = DAOUtilities.getBookTagDAO();
isSuccess = dao.removeNameTag(booktag);
int isbn13ID = Integer.parseInt(request.getParameter("booktag"));
if(isSuccess){
request.getSession().setAttribute("message", "Book successfully deleted");
request.getSession().setAttribute("messageClass", "alert-success");
response.sendRedirect("ViewBookDetails?isbn13=" + isbn13);
}else {
request.getSession().setAttribute("message", "There was a problem deleting this booktag");
request.getSession().setAttribute("messageClass", "alert-danger");
request.getRequestDispatcher("bookTag.jsp").forward(request, response);
}
}
}
BookTag DAO class
package examples.pubhub.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import examples.pubhub.model.BookTag;
import examples.pubhub.model.Book;
import examples.pubhub.utilities.DAOUtilities;
public class BookTagDAOImpl implements BookTagDAO {
Connection connection = null; // Our connection to the database
PreparedStatement stmt = null; // We use prepared statements to help protect against SQL injection
#Override
public List<BookTag>getAllBookTags(){
List<BookTag>bookTags = new ArrayList<>();
try {
connection = DAOUtilities.getConnection(); // Get our database connection from the manager
String sql = "SELECT * FROM book_tag"; // Our SQL query
stmt = connection.prepareStatement(sql); // Creates the prepared statement from the query
ResultSet rs = stmt.executeQuery(); // Queries the database
// So long as the ResultSet actually contains results...
while (rs.next()) {
// We need to populate a Book object with info for each row from our query result
BookTag bookTag = new BookTag();
// Each variable in our Book object maps to a column in a row from our results.
bookTag.setIsbn13(rs.getString("isbn_13"));
bookTag.setNameTag(rs.getString("name_tag"));
// Finally we add it to the list of Book objects returned by this query.
bookTags.add(bookTag);
}
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
// We need to make sure our statements and connections are closed,
// or else we could wind up with a memory leak
closeResources();
}
return bookTags;
}
#Override
public List<BookTag> getNameTagsByBook(String isbn13) {
List<BookTag> booktags = new ArrayList<>();
try {
connection = DAOUtilities.getConnection();
String sql = "SELECT * FROM book_tag WHERE isbn_13 = ?";
stmt = connection.prepareStatement(sql);
stmt.setString(1,isbn13);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
BookTag booktag = new BookTag();
booktag.setNameTag(rs.getString("name_tag"));
booktag.setIsbn13(rs.getString("isbn_13"));
booktags.add(booktag);
}
}
catch (SQLException e) {
e.printStackTrace();
} finally {
closeResources();
}
return booktags;
}
#Override
public List<Book> getBookByNameTag(String nameTag) {
List<Book> books = new ArrayList<>();
try {
connection = DAOUtilities.getConnection();
String sql = "SELECT * FROM books\r\n"
+ "LEFT JOIN book_tag ON books.isbn_13=book_tag.isbn_13\r\n"
+ "WHERE name_tag = ?";
stmt = connection.prepareStatement(sql);
stmt.setString(1, nameTag);
ResultSet rs = stmt.executeQuery();
while(rs.next()) {
//BookTag booktag = new BookTag();
Book book = new Book();
book.setIsbn13(rs.getString("isbn_13"));
book.setAuthor(rs.getString("author"));
book.setTitle(rs.getString("title"));
book.setPublishDate(rs.getDate("publish_date").toLocalDate());
book.setPrice(rs.getDouble("price"));
book.setContent(rs.getBytes("content"));
books.add(book);
//books.add(book);
}
}
catch (SQLException e) {
e.printStackTrace();
} finally {
closeResources();
}
return books;
}
#Override
public boolean addNameTag(BookTag booktag) {
try {
connection = DAOUtilities.getConnection();
String sql = "INSERT INTO book_tag VALUES (?, ?)"; // Were using a lot of ?'s here...
stmt = connection.prepareStatement(sql);
// But that's okay, we can set them all before we execute
stmt.setString(1, booktag.getNameTag());
stmt.setString(2, booktag.getIsbn13());
// If we were able to add our book to the DB, we want to return true.
// This if statement both executes our query, and looks at the return
// value to determine how many rows were changed
if (stmt.executeUpdate() != 0)
return true;
else
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
closeResources();
}
}
#Override
public boolean removeNameTag(BookTag booktag) {
try {
connection = DAOUtilities.getConnection();
String sql = "DELETE book_tag WHERE name_tag=? AND isbn_13=?";
stmt = connection.prepareStatement(sql);
stmt.setString(1, booktag.getNameTag());
stmt.setString(2, booktag.getIsbn13());
if (stmt.executeUpdate() != 0)
return true;
else
return false;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
closeResources();
}
}
private void closeResources() {
try {
if (stmt != null)
stmt.close();
} catch (SQLException e) {
System.out.println("Could not close statement!");
e.printStackTrace();
}
try {
if (connection != null)
connection.close();
} catch (SQLException e) {
System.out.println("Could not close connection!");
e.printStackTrace();
}
}
}
Your Dao code for deletion seems ill-designed: it should take a single unique identifier for the BookTag to be deleted. You would use that as <option> value in your drop-down list.
Anyway, you can't pass 2 separate values from a <select> in a <form>. If you really need both the name and ISBN13 fields for deletion, then concatenate both in the <option> value attribute, and then split them apart in your DeleteBookTagServlet
JSP
<h1><small>Delete Booktag</small></h1>
<form action="DeleteBookTag" method="post" class="form-horizontal" >
<select name="booktag">
<c:forEach items="${booktags}" var="booktag">
<option value="${booktags.isbn13};<c:out value="${booktags.nameTag}" />">
${booktags.isbn13}
-
<c:out value="${booktags.nameTag}" />
</option>
</c:forEach>
</select>
</form>
DeleteBookTagServlet.java
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
...
final String selectedOption = request.getParameter("booktag");
if (selectedOption == null)
return; //TODO: Manage error
final String[] spl = selectedOption.trim().split("\\s*;\\s*", 2);
if (spl.length < 2)
return; //TODO: Manage error
final String isbn13 = spl[0];
final String nameTag = spl[1];
final BookTag booktag = new BookTag();
booktag.setIsbn13(isbn13);
booktag.setNameTag(nameTag);
//Perform deletion and redirect
...
}

Exporting MySQL as Excel File through Java Servlet, coming up with 404 Error

I'm running a page trying to export an Excel file through a Java Servlet. A rundown of the structure:
downloadreports.jsp is where the button is that is supposed to call the file. The button calls ReportsServlet.java, which is just the download and that in turn calls ExcelCreatorBanned.java, which calls the database and creates the Excel file.
The problem is that 1) when I try to click on downloadreports.jsp when running the full site, it automatically goes to the ReportsServlet instead of displaying the page (turning up a 404 error for /Reports) and 2) I've been messing with this for days and it's just not working. Not sure what I'm doing wrong, but any help would be very appreciated!
downloadreports.jsp
<div align="center">
<form id="downloadBanned" action="../Reports" method="post">`
<input class="btn btn-lg btn-red" type="submit" value="Download Banned Student List"><br> `
</form>`
ReportsServlet.java
package controllers;
import java.io.IOException;
import java.io.OutputStream;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import helpers.ExcelCreatorBanned;
/**
* Servlet implementation class ReportsServlet
*/
#WebServlet({ "/ReportsServlet", "/Reports" })
public class ReportsServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private HttpSession session;
private String url;
/**
* #see HttpServlet#HttpServlet()
*/
public ReportsServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doPost(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.session = request.getSession(false);
ExcelCreatorBanned ecb = new ExcelCreatorBanned();
ecb.downloadExcel();
url = "admin/downloadreports.jsp";
RequestDispatcher dispatcher = request.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
private Object getOutputStream() {
// TODO Auto-generated method stub
return null;
}
}
ExcelCreatorBanned.java (The reference to DbConnect.java is the credentials to the server, and it definitely works because it works on the other pages)
package helpers;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import javax.servlet.ServletOutputStream;
import model.DbConnect;
import java.sql.Statement;
public class ExcelCreatorBanned {
public String downloadExcel( ) { //ServletOutputStream out){
String outFileName = "BannedStudents.csv";
int nRow = 1;
String strQuery = null;
Connection con = null;
try {
// Getting connection here for mySQL database
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DbConnect.devCredentials();
System.out.println(con);
if(con==null)
return "Connection Failed";
// Database Query
strQuery = "select * from banned";
Statement stmt=con.createStatement();
ResultSet rs=stmt.executeQuery(strQuery);
File file = new File(outFileName);
FileWriter fstream = new FileWriter(file);
BufferedWriter out = new BufferedWriter(fstream);
//Get Titles
String titleLine = "BannedID" + "," + "UserID" + "," + "AdminID"
+ "," + "Ban Start Date" + "," +
"Ban End Date" + "," + "Penalty Count" + "," +
"Description" + "," + "Status" + "\n";
out.write(titleLine);
//stmt = conn.createStatement();
while (rs.next()) {
int BannedId = rs.getInt(1);
int UserID = rs.getInt(2);
int AdminID = rs.getInt(3);
String BanStartDate = rs.getString(4);
String BanEndDate = rs.getString(5);
int PenaltyCount = rs.getInt(6);
String Description = rs.getString(7);
String Status = rs.getString(8);
String outline = BannedId + "," + UserID + "," + AdminID +
"," + BanStartDate + "," +
BanEndDate + "," + PenaltyCount + "," + Description +
"," + Status + "\n";
out.write(outline);
} //end of while
out.close();
} catch (Exception e) {
System.err.println("Got an exception!");
System.err.println(e.getMessage());
}
return outFileName;
}
}
I don't like the look of the action="../Reports" attribute in the line
<form id="downloadBanned" action="../Reports" method="post">
Try the following instead:
<form id="downloadBanned" action="${pageContext.request.contextPath}/Reports" method="post">
See this question for a discussion about what ${pageContext.request.contextPath} is.

SQL query returning "oracle.jdbc.driver.OracleResultSetImpl#48f675" instead of my expected data

I have successfully connected to my database, but when trying to return SQL query results to my index.jsp page using a Java servlet forward request receive the output of" oracle.jdbc.driver.OracleResultSetImpl#48f675" instead of the expected data results. (Note: I am receiving expected results from my SQL query in the console view of Eclipse; however, the data is not shown on my jsp page as I am expecting. Instead the ResultSetImp message is shown. Any insight anyone can share as to why I am getting this ResultSetImp instead of my expected data would be appreciated. Also does anyone care to explain what the ResultSetImp is saying...my searches have not turned up anything useful, or at least that I understand. Code is below:
package com.database;
import java.sql.*;
public class DBConnection {
public static void main(String[] args)
throws ClassNotFoundException, SQLException{
}
public static ResultSet queryExecute() throws ClassNotFoundException, SQLException
{
Class.forName("oracle.jdbc.OracleDriver");
Connection conn = DriverManager.getConnection("**Connection string here**");
if (conn == null)
{
System.out.println("Database connection not successfull");
}
else
{
System.out.println("Database connection success!");
//System.out.println(conn);
}
Statement stmt = conn.createStatement();
//ResultSet rs = stmt.executeQuery("SELECT COUNT(*) FROM Request natural join RequestTerm");
ResultSet rs = stmt.executeQuery("select * from (select QIPNUMBER,model,SERIALNUMBER,YEAROFMFG,DATERECEIVED,TERM,DEALERNAME from Request natural join RequestTerm)WHERE ROWNUM <= 20");
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
//List<String> displayRecords = new ArrayList<String>(); try store result set into an array object
while (rs.next()) {
// Iterate through the data in the result set and display it.
//int count = rs.getInt(1);
while (rs.next()) {
//Print one row
for(int i = 1 ; i <= columnsNumber; i++){
System.out.print(rs.getString(i) + " " + " "); //Print one element of a row -- print vs println
}
System.out.println(); //Move to the next line to print the next row.
//System.out.println("Number of row:"+count);
}
}
rs.close();
stmt.close();
conn.close();
return rs;
}
}
My servlet code:
package com.srccodes.example;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.SQLException;
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 com.database.DBConnection;
/**
* Servlet implementation class HelloWorld
*/
#WebServlet("/HelloWorld")
public class HelloWorld extends HttpServlet {
public static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloWorld() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
printWriter.println("<h1>Hello from the doGet function!</h1>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try {
//ResultSet display = DBConnection.queryExecute();
request.setAttribute("display", DBConnection.queryExecute());
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
request.getRequestDispatcher("/index.jsp").forward(request, response);
/*String nextJSP = "/result.jsp";
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(nextJSP);
dispatcher.forward(request,response);*/
}
}
Finally the statement I use to call my servlet within my index.jsp:
<%= request.getAttribute("display")%>
I know this statement is a scriplet and is frowned upon; however, I am trying to get data to populate to my jsp first and then move from there.
When you are returning Object of ResultSet, you will get the reference of the same. you wont get the values in it as you desire.
You will have to do something like this (if you really want to use scriplet):
<%
ResultSet rs = (ResultSet)request.getAttribute("display");
ResultSetMetaData rsmd = rs.getMetaData();
int columnsNumber = rsmd.getColumnCount();
while (rs.next()) {
for(int i = 1 ; i <= columnsNumber; i++){
out.print(rs.getString(i) + " " + " " + "<br/>");
}
out.print("<br/>"); //Move to the next line to print the next row.
}
}
rs.close();
%>
A more appropriate way to this will be to use a bean:
class MyBean {
int QIPNUMBER;
String model;
.....
//getters and setters
}
now in your class create list of MyBean and populate the objects, one Row = One object.
List<MyBean> lst = new ArrayList<MyBean>();
MyBean myBean;
while (rs.next()) {
myBean = new MyBean();
myBean.setModel(rs.getString("model"));
....
lst.add(myBean);
}
.....
return lst;
After this add the list to request in Servlet not the resultSet.
request.setAttribute("display", DBConnection.queryExecute());
// queryExecute now returns List<MyBean>
Now in your JSP if you want to use scriplet, then :
<%
List<MyBean> lst = (ArrayList<MyBean>)request.getAttribute("display");
for(MyBean mb : lst){
out.print(mb.getModel() + "<br/>");
.....
}
%>
You are passing an instance of a ResultSet back to the JSP:
http://docs.oracle.com/javase/7/docs/api/java/sql/ResultSet.html
As you are using Oracle, what is returned is the Oracle implementation of the ResultSet interface i.e. oracle.jdbc.driver.OracleResultSetImpl
Your JSP code is simply calling the toString method of a oracle.jdbc.driver.OracleResultSetImpl object which, because it has not been overridden, is simply invoking the version of toString in the java.lang.Object class - which explains the output:
oracle.jdbc.driver.OracleResultSetImpl#48f675
You need to pull the necessary values out of the ResultSet object and return them accordingly. See this article on how to do just that:
http://docs.oracle.com/javase/tutorial/jdbc/basics/retrieving.html

Servlets and JSP blank

hi all I've typed out a page that queries the database then inputs something into the database but when I go to load the servlet/jsp page its comes back blank and am unsure what is happening or why? I'm coding in eclipse and after looking at the console and not getting anything printing out I figured there was something wrong with my code but I cannot see the problem.
Here is my servlet
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
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 javax.servlet.http.HttpSession;
/**
* Servlet implementation class TutorAssign
*/
#WebServlet("/TutorAssign")
public class TutorAssign extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public TutorAssign() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
private void sendBack(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession(true);
//Set data you want to send back to the request (will be forwarded to the page)
//Can set string, int, list, array etc.
String sql = "SELECT l.id,s.name,l.day,l.time,l.room" +
" FROM subject s, lab l " +
" WHERE s.user_id="+(Integer)session.getAttribute("id");
try{
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got boobs");
System.out.println(session.getAttribute("id"));
Statement stmt = con.createStatement();
ResultSet res = stmt.executeQuery(sql);
System.out.println(res);
ArrayList<String> list1 = new ArrayList<String>();
ArrayList<String> list2 = new ArrayList<String>();
if (res.next()){
do{
list1.add(res.getString(1));
list2.add(res.getString(2)+" "+res.getString(3)+" "+res.getString(4)+" "+res.getString(5));
}while(res.next());
System.out.println("Outside");
String[] arr1 = list1.toArray(new String[list1.size()]);
String[] arr2 = list2.toArray(new String[list2.size()]);
System.out.println(list1);
request.setAttribute("res1", arr1);
request.setAttribute("res2", arr2);
}
}catch (SQLException e) {
}
catch (Exception e) {
}
//Decides what page to send the request data to
RequestDispatcher view = request.getRequestDispatcher("TutorAssign.jsp");
//Forward to the page and pass the request and response information
view.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
int user_id = Integer.parseInt(request.getParameter("id"));
int lab_id = 0;
String message = null;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con =
DriverManager.getConnection("jdbc:mysql://localhost:3306/wae","root","");
System.out.println("got connection");
System.out.println(user_id);
Statement s = con.createStatement();
String sql = "INSERT INTO user_lab" +
" (user_id, lab_id)" +
" VALUES" +
" ('" + user_id + "'," +
" '" + lab_id + "')";
System.out.println(sql);
int i = s.executeUpdate(sql);
if (i==1) {
message = "Successfully assigned a tutor.";
response.sendRedirect("Lecturer_labs");
}
s.close();
con.close();
}
catch (SQLException e) {
message = "Error." + e.toString();
boolean error = true;
}
catch (Exception e) {
message = "Error." + e.toString();
boolean error = true;
}
if (message!=null) {
PrintWriter out = response.getWriter();
out.println("<B>" + message + "</B><BR>");
out.println("<HR><BR>");
}
}
// TODO Auto-generated method stub
}
I noticed that your doGet method has not been implemented.
I would assume that your sendBack code is not being called
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
sendBack(request,response);
}
You have several empty catch blocks. This means that if the program encounters some problem the error will be silently swallowed and you don't know what code got executed and what code was skipped, so the outcome is unknown. At least log the error in the catch block, like this (very basic example, using java.util.logging
} catch (SQLException e) {
logger.log(Level.INFO,"SQL Error encountered",e);
} catch (Exception e) {
logger.log(Level.INFO,"Other error encountered",e);
}
Start by getting your error handling right, and study the errors the program encounters.
Aside from that problem, as the others point out your doGet isn't implemented - so if you call the page with GET it won't do anything because doGet is empty. It should do something on POST though.

Searching from PostgreSQL using Java Servlet. Cannot get any result to show

When I search by Name or Latname, it does not return anything. It returns values only if date of birth is given. Another question is if date of birth is left blank I get
null value in column "birthyear" violates not-null constraint error.
import java.util.*;
import java.sql.*;
import java.io.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class searchfromdatabase
*/
public class searchfromdatabase extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public searchfromdatabase() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
System.out.println("command: " + request.getParameter("command"));
response.setContentType("text/html");
java.io.PrintWriter out = response.getWriter();
out.println("<html><head>");
out.println("<title>Search form</title></head><body>");
out.println("<h2>Artist details.</h2><tr>");
// HTMl Customer Input
out.println("<form method=\"post\" action =\""
+ request.getContextPath() + "/searchfromdatabase\" >");
out.println("<table border='0' width='300' align='center' bgcolor='#CDFFFF'>");
out.println("<tr><td colspan=2 style='font-size:12pt;color:#00000;' align='center'><h3>Search Artist</h3></td></tr>");
out.println("<tr><td ><b>Artist Name</b></td><td>: <input type='text' name='givenname' id='givenname'></td></tr>");
out.println("<tr><td ><b>Artist Last Name</b></td><td>: <input type='text' name='familyname' id='familyname'></td></tr>");
out.println("<tr><td ><b>Date of Birth</b></td><td>: <input type='text' name='birthyear' id='birthyear'></td></tr>");
out.println("<tr><td colspan=2 align='center'><input type='submit' name='submit' value='Submit'></td></tr></table>");
out.println("</form>");
out.println("</body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
java.io.PrintWriter out = response.getWriter();
Connection conn = null;{
try {
Class.forName("org.postgresql.Driver");
conn = DriverManager.getConnection(
"jdbc:postgresql://localhost:5432/caglar", "postgres",
"abracadabra");
System.out.println("Connected to the database");
String agent_name = request.getParameter("givenname");
String agent_lastname = request.getParameter("familyname");
String dob = request.getParameter("birthyear");
//if dob is left blank
if (request.getParameter("birthyear").equals("")) {
dob = null;
// otherwise, get the exact number and define it as variable
} else {
dob = request.getParameter("birthyear");
}
//
ArrayList al=null;
ArrayList agent_list =new ArrayList();
//Problem 1: If dob is not given, it is not searching by name or lastname.
String query = "select * from agent where givenname='"+agent_name+"' or familyname='"+agent_lastname+"' or birthyear='"+dob+"' order by givenname";
System.out.println("query" + query);
Statement st = conn.createStatement();
ResultSet rs = st.executeQuery(query);
while(rs.next())
{
al = new ArrayList();
al.add(rs.getString(1));
al.add(rs.getString(2));
al.add(rs.getString(3));
al.add(rs.getString(4));
System.out.println("al :: "+al);
agent_list.add(al);
}
request.setAttribute("agentList",agent_list);
System.out.println("agentList " + agent_list);
// out.println("agent_list " + agent_list);
// HTML results
response.setContentType("text/html");
//java.io.PrintWriter out = response.getWriter();
out.println("<html><head>");
out.println("<title>Final Results</title></head><body>");
out.println("<table width='700px' align='center' style='border:1px solid #000000;'><tr><td colspan=8 align='center' style='background-color:ffeeff'><b>Artist Record</b></td>");
out.println("</tr><tr style='background-color:efefef;'><td><b>Artist ID</b></td><td><b>Date of Birth</b></td><td><b>Artist First Name</b></td><td><b>Artist Last Name</b></td></tr>");
int count=0;
String color = "#F9EBB3";
if(request.getAttribute("agentList")!=null)
{
al=(ArrayList)request.getAttribute("agentList");
Iterator itr = al.iterator();
while(itr.hasNext())
{
if((count%2)==0)
{
color = "#eeffee";
}
else
{
color = "#F9EBB3";
}
count++;
ArrayList agentList = (ArrayList)itr.next();
out.println("<tr style='background-color:"+color+";'>");
out.println("<td>"+agentList.get(0)+"</td>");
out.println("<td>"+agentList.get(1)+"</td>");
out.println("<td>"+agentList.get(2)+"</td>");
out.println("<td>"+agentList.get(3)+"</td></tr>");
}
}
if(count==0)
{
out.println("<tr><td colspan=8 align='center' style='background-color:eeffee'><b>No Record</b></td></tr>");
}
conn.close();
System.out.println("Disconnected from database");
} catch (Exception e) {
e.printStackTrace();
}
out.println("</table></body></html>");
}
}
}
String query = "select * from agent where givenname='"+agent_name+"' or familyname='"+agent_lastname+"' ";
if(dob!=null && !"".equals(dob))
query = query + " or birthyear='"+dob+"'";
query = query+ "order by givenname";
User conditional statement to construct a query.

Categories