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.
Related
I wanted to create a servlet that shows Studentlist which is from SQL Server. However, when I click show button the server returns:
HTTP Status 500 - Cannot invoke "model.StudentList.getList()" because "list" is null
controller.StudentServlet.java
package controller;
import java.io.IOException;
import java.sql.SQLException;
import java.util.ArrayList;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import model.Student;
import model.StudentList;
/**
* Servlet implementation class StudentServlet
*/
public class StudentServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public StudentServlet() {
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
StudentList list = null;
try {
list = new StudentList();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<Student> myStudents = list.getList();
request.setAttribute("MYSTUDENTS", myStudents);
RequestDispatcher dispatcher = request.getRequestDispatcher("list.jsp");
dispatcher.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
model.StudentList.java
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class StudentList {
private static ArrayList<Student> list = new ArrayList<>();
public StudentList() throws SQLException {
Connection conn = null;
PreparedStatement p = null;
ResultSet rs = null;
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=Workshop1";
String user = "quan167";
String pass = "12345";
conn = DriverManager.getConnection(dbURL, user, pass);
int id = 0;
String name = "";
String gender = "";
String date = "";
String sql = "select * from Student";
try {
p = conn.prepareStatement(sql);
rs = p.executeQuery();
// Condition check
while (rs.next()) {
id = rs.getInt("id");
name = rs.getString("name");
gender = rs.getString("gender");
date = rs.getString("dob");
list.add(new Student(id, name, gender, date));
}
} catch (SQLException ex) {
ex.printStackTrace();
} finally {
try {
if (conn != null && !conn.isClosed()) {
conn.close();
}
} catch (SQLException ex) {
ex.printStackTrace();
}
}
}
public ArrayList<Student> getList() {
return list;
}
}
and model.Student.java which has: id(int), name(String), gender(String), dob(String) stands for date of birth.
But this works out just fine in this test class
package model;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
public class tst {
public static void main(String[] args) throws SQLException {
Connection conn = null;
PreparedStatement p = null;
ResultSet rs = null;
String dbURL = "jdbc:sqlserver://localhost:1433;databaseName=Workshop1";
String user = "quan167";
String pass = "12345";
conn = DriverManager.getConnection(dbURL, user, pass);
StudentList list = null;
try {
list = new StudentList();
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
ArrayList<Student> myStudents = list.getList();
System.out.println(myStudents);
}
}
Anyone knows the solution? Thank you.
Edit: I knew where the problem is. So basically I have not put the sqlijdbc4.jar in WEB-INF.lib
Change the following lines:
public class StudentList {
private static ArrayList<Student> list = new ArrayList<>();
to these lines:
public class StudentList {
public ArrayList<Student> list = new ArrayList<>();
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.
This question already has answers here:
How can I upload files to a server using JSP/Servlet?
(14 answers)
Closed 8 years ago.
I am uploading more images using single upload button such as below code,
Updated based on Answer :
package TeachChapter;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
/**
* Servlet implementation class ImageUploadToDB
*/
#WebServlet("/ImageUploadToDB")
public class ImageUploadToDB extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ImageUploadToDB() {
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
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
System.out.println("Entered successfully:");
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
// get the request content and iterate through
try {
items = fileUpload.parseRequest(request);
} catch (FileUploadException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
if (items != null) {
System.out.println("if0 successfully:");
final Iterator iter = items.iterator();
while (iter.hasNext()) {
System.out.println("while successfully:");
final FileItem item = (FileItem) iter.next();
// this is for non-file fields
if (item.isFormField()) {
System.out.println("if1 successfully:");
// logic for setting non-file fields
} else {
// item.getName() - gives file name
fileMap.put(item.getName(), item.getInputStream());
System.out.println("else successfully:");
}
}
}
}
try {
System.out.println("try connection successfully:");
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
Connection con;
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
Set<String> keySet = fileMap.keySet();
for (String fileName : keySet) {
System.out.println("for successfully:");
String sql ="INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)" ;
PreparedStatement statement;
statement = con.prepareStatement(sql);
statement.setString(1, "mani");
statement.setString(2, "vasu");
statement.setBlob(3, fileMap.get(fileName));
int row = statement.executeUpdate();
System.out.println("inserted successfully:");
}
}
catch (SQLException e) {
// TODO Auto-generated catch block
System.out.println("errror is:"+e);
}
}
}
OP :
Entered successfully:
try connection successfully:
I know above code totally wrong but i want to get that all uploaded images in servlet page for insert into mysql.
Please Help me out.
Had faced a similar issue - probably you could build upon it further.
This is a generic solution - where you don't know the number of attachments in the input request. It caters to a multi-part request as below.
// imports
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
// code flow
// HttpServletRequest request
final FileItemFactory factory = new DiskFileItemFactory();
final ServletFileUpload fileUpload = new ServletFileUpload(factory);
List items = null;
private Map<String, InputStream> fileMap = new HashMap<String, InputStream>();
if (ServletFileUpload.isMultipartContent(request)) {
// get the request content and iterate through
items = fileUpload.parseRequest(request);
if (items != null) {
final Iterator iter = items.iterator();
while (iter.hasNext()) {
final FileItem item = (FileItem) iter.next();
// this is for non-file fields
if (item.isFormField()) {
// logic for setting non-file fields
} else {
// item.getName() - gives file name
fileMap.put(item.getName(), item.getInputStream());
}
}
}
}
//Here i will insert that images on by one to DB
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/raptor1_5","root","");
Set<String> keySet = fileMap.keySet();
for (String fileName : keySet) {
String sql = "INSERT INTO contacts (photo) values (?)";
PreparedStatement statement = con.prepareStatement(sql);
statement.setBlob(1, fileMap.get(fileName));
int row = statement.executeUpdate();
}
fileMap will contain all the files you have sent in the request.
If you don't bother for file names, you can change the implementation from HashMap to ArrayList and modify the for loop accordingly.
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
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.