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.
Related
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
...
}
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 is model part of my MVC app and it is supposed to communicate with the Database(Oracle 10g XE).Here is the code that I have written,
package com.cid_org.model;
import java.sql.*;
public class LoginModelPOJO {
private String username;
private String password;
private Connection connection;
public LoginModelPOJO(String username, String password, Connection connection){
this.username = username;
this.password = password;
this.connection = connection;
validate();
}
private void validate(){
try {
String query = "SELECT * FROM CRIME_SOLVING_OFFICIAL where OFFICIAL_USERNAME=? and OFFICIAL_PASSWORD=?";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, username);
ps.setString(2, password);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
// String name=rs.getString(3);
System.out.println("success");
} else {
System.out.println("access denied");
}
} catch (Exception e) {
System.out.println("Connection " + e);
}
}
}
but as it gets executed, it generates the following error:
Connection java.sql.SQLException: ORA-00904: "PASSWORD": invalid identifier
Here is the table that I have created in Oracle,
Here is the image
Btw, I know this question will be branded as duplicate question and indeed it is but FYI I have gone through all the available posts related to this question(You can see all the tabs opened in firefox in the picture) but couldn't find any answer.
Edit: I have made all the 'password' strings disappear to corner out the 'PASSWORD' identifier Exception is talking about.And I have also altered the column name of the OFFICIAL_PASSWORD to OFFICIAL_PWD just to be sure about things.
Here is the login.html form,
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>Criminal Investigation Department-Home</title>
<link rel="stylesheet" href="css/login_page.css">
</head>
<body>
<img src="css/images/logo/CID_Logo_1.png" alt="CID Logo">
<nav id="navigation">
<a id="link1" class="header_links" href="most_wanted.html">Most Wanted</a>
<a id="link2" class="header_links" href="hotnews.html">Hot News</a>
<a id="link3" class="header_links" href="report_crime.html">Report Crime</a>
<a id="link4" class="header_links" href="login.html">Login</a>
<a id="link5" class="header_links" href="about.html">About Us</a>
<a id="link6" class="header_links" href="contact.html">Contact Us</a>
<a id="link7" class="header_links" href="safety_measures.html">Safety Measures</a>
</nav>
<div id="login_page_border">
<form action="LoginScript.do" method="POST">
<div id="form_border">
<span id="login_label">Login</span><br>
<div id="login_contents">
<span class="login_field">Username:</span> <input name="username" type="text"><br><br>
<span class="login_field">Password:</span> <input name="pass" type="password">
<input id="login_button" type="submit" value=" ">
</div>
</div>
</form>
</div>
</body>
Here is the controller servlet,
package com.cid_org.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.cid_org.model.*;
import java.sql.*;
/**
* Servlet implementation class LoginControllerServlet
*/
public class LoginControllerServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public LoginControllerServlet() {
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 {
/*Take the data submitted by the user though the login
* form(Remember the HTTP Post request ->HttpServletRequest request object*/
String username = request.getParameter("username");
String pwd = request.getParameter("pass");
System.out.println(username + "aaa");
System.out.println(pwd);
Connection connection = (Connection)getServletContext().getAttribute("connection_context_param");
LoginModelPOJO lmpojo = new LoginModelPOJO(username, pwd, connection);
boolean isValidFlag = lmpojo.isValid();
if(isValidFlag){
RequestDispatcher view =request.getRequestDispatcher("view_profile.jsp");
view.forward(request, response);
}
else{
response.sendRedirect("/CrimeReportingSystem/static/login_access_denied.html");
}
}
}
And here is a slightly modified version of the Model part,
package com.cid_org.model;
import java.sql.*;
public class LoginModelPOJO {
private String username;
private String pwd;
private Connection connection;
private boolean isValidFlag;
public LoginModelPOJO(String username, String pwd, Connection connection){
this.username = username;
this.pwd = pwd;
this.connection = connection;
isValidFlag=false;
validate();
}
private void validate(){
try {
String query = "SELECT * FROM CRIME_SOLVING_OFFICIAL where OFFICIAL_USERNAME=? and OFFICIAL_PWD=?";
PreparedStatement ps = connection.prepareStatement(query);
ps.setString(1, username);
ps.setString(2, pwd);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
// String name=rs.getString(3);
System.out.println("success");
isValidFlag = true;
} else {
System.out.println("access denied");
}
} catch (Exception e) {
System.out.println("Connection " + e);
}
}
public boolean isValid(){
return isValidFlag;
}
}
Finally ,here is the ContextListener,
package com.cid_org.listener;
import java.sql.*;
import javax.servlet.*;
/*This listener will initialize a connection and set the context
* attribute reference with a string at the time of application deployment time or
* when the ServletContext will be initialized*/
public class DatabaseServletContextListener implements ServletContextListener {
Connection connection = null;
public void contextInitialized(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
connection = DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:XE", "system", "java");
System.out.println("la la la ...");
//Set the Attribute for the connection
sc.setAttribute("connection_context_param", connection);
}
catch(Exception e){
//To be decided Later- I dislike "checked" exceptions
System.out.println("conn...bzzz "+e);
}
}
public void contextDestroyed(ServletContextEvent event) {
try {
/*Connection will be closed at the time of undeployment of the application or
* when the context is destroyed*/
connection.close();
} catch (Exception e) {
System.out.println("connection pika fucked " + e);
}
}
}
Btw: The error is still the same.
I'd recommend seeing what your username and password strings are first via:
System.out.println(username);
System.out.println(password);
Just to make sure that you're not getting nulls then run the query directly in Oracle and see if it gives an error with the code you have above i.e:
SELECT * FROM CRIME_SOLVING_OFFICIAL where OFFICIAL_USERNAME= *Your username and OFFICIAL_PASSWORD=*YourPassword
See if this gives an error if it does your SQL Syntax is the issue.
Ok so for our Uni project we are making a website to store information about churches (I know super interesting right -.-).
Basicly it just needs to have church information in a database and when a user clicks or searchs for a church it needs to pull the church information along with user comments from the database.
So far I have a HTML form that delivers a comment to the servlet/database and outputs it using a resultset. I was just wondering what the best method would be for handling multiple information as now that I'm trying to deliver both comments and the church information I'm kinda lost as to how to store it.
Thanks in advance!
Ow and here is my code for reference:
HTML
<form method="get" action="dbtest" id="form1">
<fieldset>
<p>Please enter you're Name:</p>
<input type="text" name="author" size="10" id="name"/><br />
<p>Please enter you're Email here:</p>
<input type="text" name="author_email" size="10" id="email"/><br />
<p>Please enter you're comment here:</p>
<input type="text" name="comment_text" size="10" id="comment"/><br />
<p>
<input type="submit" value="Submit" name="submit_button" />
</p>
</fieldset>
</form>
Servlet
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author mxk12ycu
*/
public class dbtest extends HttpServlet {
/**
* Processes requests for both HTTP
* <code>GET</code> and
* <code>POST</code> methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String authorName = request.getParameter("author");
String authorEmail = request.getParameter("author_email");
String commentText = request.getParameter("comment_text");
try {
//Holding SQL statement
String SQL;
String insertSQL;
//insertSQL = "INSERT INTO comments VALUES('0002')" + authorName + authorEmail + commentText + ("('29 Nov 2012','002')");
//insertSQL = "INSERT INTO comments VALUES (default,'Ryan H','Test#hotmail.com','TestComments','29 Nov 2012','1')";
//insertSQL = "INSERT INTO comments (author, author_email, comment_text, comment_date, church_id) VALUES ('" + authorName + "'," + "'" + authorEmail + "'," + "'" + commentText + "', '29 Nov 2012', '1')";
//insertSQL = "INSERT INTO comments VALUES ('Ryan Holder', 'test#hotmail.com', 'Comment here', '30 Nov 2012', 'default', '1')";
insertSQL = "INSERT INTO comments VALUES (default, " + "'" + authorName + "'," + "'" + authorEmail + "'," + "'" + commentText + "', '29 Nov 2012', '1')";
SQL = "SELECT * FROM churches, comments";
Class.forName("org.postgresql.Driver");
Connection connection = DriverManager.getConnection(
"jdbc:postgresql:ChurchSearch",
"postgres",
"*****");
Statement statement = connection.createStatement();
statement.executeUpdate(insertSQL);
ResultSet resultSet = statement.executeQuery(SQL);
/* TODO output your page here. You may use following sample code. */
out.println("<html>");
out.println("<head>");
out.println("<title>Test Comment Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet test at " + request.getContextPath() + "</h1>");
out.println("<h2>Comment Form</h2>");
while (resultSet.next()) {
out.println("<p>");
out.println(resultSet.getString("author"));
out.println("</p>");
out.println("<p>");
out.println(resultSet.getString("author_email"));
out.println("</p>");
out.println("<p>");
out.println(resultSet.getString("comment_text"));
out.println("</p>");
}
out.println("</body>");
out.println("</html>");
connection.close();
}
catch (Exception e) {
System.err.println("Error: " + e);
}
finally {
out.close();
}
}
You can to use the MVC pattern. On the other hand, you must be sure to close the connection to the database.
Connection conn = null;
try {
conn = // get connection;
// do database operations
} catch (final SQLException e) {
throw new DAOException(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (final SQLException ex) {
LOG.warning("message warning to log");
}
}
}
This releases all resources used by the connection.
About MVC, you can find more information in Integrating Servlets and JSP: The Model View Controller (MVC) Architecture. You can also use a framework like Struts, Spring MVC.
Create A DAO(database access objects) class ..Handle connections.
public class DAO {
static private Connection conn = null;
static private String URL = "jdbc:mysql://localhost/<databse name>";
static private String USERNAME = "root";
static private String PASSWORD = "root";
static private String DRIVER = "com.mysql.jdbc.Driver";
private static Connection getConnection() throws ClassNotFoundException,
SQLException {
if (conn == null) {
Class.forName(DRIVER);
System.out.println("Driver Initailizing");
conn = DriverManager.getConnection(URL, USERNAME, PASSWORD);
}
return conn;
}
public static ResultSet selectQuery(String query) throws SQLException,
ClassNotFoundException {
//Read the query from the servlet class only SQL query
System.out.println(query);
ResultSet rs = DAO.getConnection().createStatement().executeQuery(query);
//return the result set back to servlet class
return rs;
}
Thanks,
Pavan
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.