This question already has answers here:
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
(6 answers)
Closed 5 years ago.
This is my first time asking so im sorry in advance if i messed up.Ok so here it goes
i have this mysql table that i want to display in a jsp page and i actually got it to work but its not really a good approach since all the code(connecting to the database etc) is in the JSP.So i made a java bean that controls the connecting to database and executing sql query part , and a separate JSP page where i can display the table.
main.jsp
<%# page import="java.sql.*" %>
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<head>
<title>Welcome to Car Rental System</title>
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css"></link>
<script src="//ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>
<script src="jquery.backstretch.min.js"></script>
<link rel="stylesheet" href="style.css"></link>
<link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro" rel="stylesheet">
</head>
<body>
<p><div><center><h1><b>Car Rental System</b></h1></center></div></p>
<%
<jsp:useBean id="displayCarList" class="displayCarList.displayCarList" >
<jsp:setProperty name="displayCarList" property="*"/>
</jsp:useBean>
<%
String carbookId = request.getParameter("carbookId");
String manufacturername = request.getParameter("manufacturername");
String modelname = request.getParameter("modelname");
String price_day = request.getParameter("price_day");
%>
<table border='3' align='center'>
<tr>
<td><b>Car ID</td>
<td><b>Manufacturer</td>
<td><b>Model name</td>
<td><b>Price per day</td>
</tr>
<tr>
<td><%=displayCarList.getCarbookid()%></td>
<td><%=displayCarList.getManufacturername()%></td>
<td><%=displayCarList.getModelname()%></td>
<td><%=displayCarList.getPriceday()%></td>
</tr>
</table>
<br></br>
<form action=secondpage.jsp method="post">
<fieldset><legend>Fill in the form below :</legend>
<p><b>Name:</b> <input type="text" name="name" size="20" maxlength="40" /></p>
<p><b>Telephone number</b> <input type="text" name="phonenumber" th:field="*{phonenumber}" size="20" maxlength="40" /></p>
<p><b>Rental date:</b> <input type="date" th:field="*{rentaldate}" name="rentaldate"></p>
<p><b>Return date:</b> <input type="date" th:field="*{returndate}" name="returndate"></p>
<p><b>Car ID:</b> <input type="text" name="carID" th:field="*{carID}" size="20" maxlength="40" /></p>
<div align="left"><input type="submit" name="submit" value="Submit " /></div>
</form>
<script>
$.backstretch("background2.jpg");
</script>
</body>
</html>
The following is the java bean, displayCarList.java
package displayCarList;
import java.io.*;
import static java.lang.System.out;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.logging.Level;
import java.util.logging.Logger;
public class displayCarList {
private String carbookId, manufacturername, modelname, price_day;
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
public displayCarList(){
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(displayCarList.class.getName()).log(Level.SEVERE, null, ex);
}
con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/rentalcar","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM carlist");
while(rs.next()){
carbookId = rs.getString(1);
manufacturername= rs.getString(2);
modelname = rs.getString(3);
price_day = rs.getString(4);
}
stmt.close();
con.close();
// displaying record
} catch (SQLException e) {
System.out.println("couldnotconnecYO");
}
}
public String getCarbookid(){
return carbookId;
}
public void setCarbookid(){
this.carbookId = carbookId;
}
public String getManufacturername(){
return manufacturername;
}
public void setManufacturername(){
this.manufacturername = manufacturername;
}
public String getModelname(){
return modelname;
}
public void setModelname(){
this.modelname = modelname;
}
public String getPriceday(){
return price_day;
}
public void setPriceday(){
this.price_day = price_day;
}
}
But for some reason, only one record is displayed which is the last one , where it shouldve returned everything in the table(supposedly)
enter image description here
So i would appreciate if you guys could help me and point out what i did wrong , and help me get all the records in the table displayed like this one
enter image description here
thanks again
UPDATE
As per the instructions by Shuddh i made a few changes to the codes and yet it still doesnt work for some bloody reason
public ArrayList displayCarList(){
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(displayCarList.class.getName()).log(Level.SEVERE, null, ex);
}
con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/rentalcar","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM carlist");
while(rs.next()){
int i = 1;
while(i <= 12){
carlist.add(rs.getString(i++));
}
}
stmt.close();
con.close();
// displaying record
} catch (SQLException e) {
System.out.println("couldnotconnecYO");
}
return carlist;
}
its now returning null in every colum
The reason you are getting just last row is because you are not storing the other rows anywhere. So it overwrites the variables and this last row is being captured. Store the local variable as list and that will do the trick.
Create a List and add every resultset into that
try {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException ex) {
Logger.getLogger(displayCarList.class.getName()).log(Level.SEVERE, null, ex);
}
con =DriverManager.getConnection ("jdbc:mysql://localhost:3306/rentalcar","root","");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM carlist");
while(rs.next()){
carbookId = rs.getString(1);
manufacturername= rs.getString(2);
modelname = rs.getString(3);
price_day = rs.getString(4);
// add to list here.
}
stmt.close();
con.close();
// displaying record
} catch (SQLException e) {
System.out.println("couldnotconnecYO");
}
return List. // If you have no idea about list in java google it and learn how to use it
Write your above code in a method and not in constructor.
Related
I'm developing a simple application with Eclipse and Apache in which i display a table created with MySQL pertaining to products (with columns id, name and price) using Java, JSP and HTML. I also have a text box with a button which allows to filter the table showing only the products which have a bigger price than the one inserted on the text box.
Everything seems to be working fine including the filter. However, when i run the application for the first time, the full table isn't displayed like it should. It only displays when i use the filter. I'm not sure but there seems to be some conflict between the scriptlet for the filter elements and the table because if i comment the scriptlet for the filter elements in the JSP file, the table loads on startup like it should.
This is the code for JSP class which loads the table and the search elements (with some Bootstrap styling):
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1" import="java.sql.Connection,java.sql.ResultSet,java.sql.DriverManager,project1.components.DBConnector, project1.components.Filter"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Product</title>
<style type="text/css">
<%#include file="bootstrap/css/bootstrap.css" %>
<%#include file="bootstrap/css/bootstrap-theme.css" %>
</style>
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<script src="bootstrap/js/jquery.js"></script>
<script src="bootstrap/js/bootstrap.js"></script>
</head>
<body>
<%
DBConnector dbc = new DBConnector();
Connection conn = dbc.connect();
String query = "select * from product";
%>
</body>
<form method="post">
<div class="col-xs-2 col-xs-offset-5">
<input type="text" class="form-control" name="value" value=<%=request.getParameter("firstinput")%>>
<br><br>
<input type="submit" class="form-control" name="submit" value="Filter">
<%
if(!request.getParameter("value").isEmpty()){
String val = request.getParameter("value");
Filter ft = new Filter();
query = ft.filterByValue(val);
}
%>
</div>
<br></br>
<table class = 'table table-hover'>
<tr>
<td>Id</td>
<td>Name</td>
<td>Product</td>
</tr>
<%
try
{
ResultSet rs = dbc.obtainTable(query);
while(rs.next())
{
%><tr>
<td><%=rs.getInt("ID") %></td>
<td><%=rs.getString("NAME") %></td>
<td><%=rs.getFloat("PRICE") %></td>
</tr> <%
}
%>
</table>
<%
rs.close();
conn.close();
}
catch(Exception e)
{
e.printStackTrace();
}
%>
</form>
</html>
The Java class which connects to the database and obtains data with a given query to be loaded on the table defined in the previous JSP file:
package project1.components;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.mysql.jdbc.Connection;
import com.mysql.jdbc.Statement;
public class DBConnector {
String url = "jdbc:mysql://localhost:3306/products?autoReconnect=true&useSSL=false";
String user = "root";
String pass = "root";
public Connection connect() throws ClassNotFoundException, SQLException{
Class.forName("com.mysql.jdbc.Driver");
return (Connection) DriverManager.getConnection(url,user,pass);
}
public ResultSet obtainTable(String query) throws ClassNotFoundException, SQLException{
Connection cn = this.connect();
Statement stmt= (Statement) cn.createStatement();
return stmt.executeQuery(query);
}
}
And finally, the filter itself defined in Java:
package project1.components;
import java.sql.ResultSet;
import java.sql.SQLException;
public class Filter {
public String filterByValue(String val) throws ClassNotFoundException, SQLException{
int num = Integer.parseInt(val);
String query = null;
if(num >= 0){
query = "select * from product where price >" + val;
}
else{
query = "select * from product";
}
return query;
}
}
Any help would be really appreciated.
Could you please replace the following:
if(!request.getParameter("value").isEmpty()){
by:
if(request.getParameter("value")!=null && !request.getParameter("value").trim().isEmpty()){
and see the results?
This question already has answers here:
How to get the insert ID in JDBC?
(14 answers)
Closed 8 years ago.
How to fetch id from db using JSP servlet. This is my JSP servlet code and I need code for display id through alert message box and in my db I will gave id as auto-increment in data base. I am trying this for last two days .
How to fetch a id from the database after record inserted in db?
Kindly help me out for displaying an id like "registration is suss-your id is ........."
package controller;
import java.io.IOException;
import java.io.PrintWriter;
javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
//import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.sql.*;
import javax.servlet.*;
/**
* Servlet implementation class Register
*/
#WebServlet("/Register")
public class Register extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 2945154063362413961L;
/**
* #see HttpServlet#HttpServlet()
*/
public Register() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
/*String fname=request.getParameter("firstname");
String lname=request.getParameter("lastname");*/
//pw.println("Firstname is" +fname);
//pw.println("Firstname is" +lname);
/*System.out.println("first=="+fname);
System.out.println("last==="+lname);
*/
//String connectionURL = "jdbc:mysql://127.0.0.1:3306/newData";// newData is the database
//Connection connection;
Connection conn=null;
String url="jdbc:mysql://localhost:3306/";
String dbName="Registrationform";
String driver="com.mysql.jdbc.Driver";
String dbUserName="root";
String dbPassword="root";
try{
String Fname = request.getParameter("firstname");
String Lname = request.getParameter("lastname");
String dob = request.getParameter("dob");
String email= request.getParameter("email");
Class.forName(driver).newInstance();
System.out.println("welcome");
conn = DriverManager.getConnection(url+dbName,dbUserName, dbPassword);
System.out.println("Connection created");
PreparedStatement pst =(PreparedStatement) conn.prepareStatement("insert into event (firstname,lastname,dob,email) values(?,?,?,?)");//try2 is the name of the table
pst.setString(1,Fname);
pst.setString(2,Lname);
pst.setString(3,dob);
pst.setString(4,email);
int i = pst.executeUpdate();
System.out.println("Query updated");
PreparedStatement pstr =(PreparedStatement) conn.prepareStatement("select * from event(id);");//try2 is the name of the table
//conn.commit();
String msg=" ";
if(i!=0){
msg="You Are Succesfully Register For The Event Meet";
//alert("You Are Succesfully Register For The E;vent Meet")
// response.sendRedirect("reg.jsp");
pw.println("<font size='4' color=black font family = times new roman >" + msg + "</font>");
}
else{
msg="Failed to insert the data";
pw.println("<font size='4' color=black font family = times new roman >" + msg + "</font>");
}
pst.close();
}
catch (Exception e){
pw.println(e);
}
}
}
java script code
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link rel="stylesheet" type="text/css" href="reg.css">
<title>Event Registration From</title>
</head>
<body class= "main">
<script type="text/javascript">
function register(registerform)
{
if(registerform.firstname.value == "") {
alert("Please enter your Firstname");
registerform.firstname.focus();
return false;
}
if(registerform.lastname.value == "") {
alert("Please enter your Lastname");
registerform.lastname.focus();
return false;
}
if(registerform.dob.value == "") {
alert("Please select your DOB");
registerform.dob.focus();
return false;
}
if(registerform.email.value == "") {
alert("Please enter your Email-id");
registerform.email.focus();
return false;
}
/* var x=document.forms["form"]["email_id"].value;
var atpos=x.indexOf("#");
var dotpos=x.lastIndexOf(".");
if (atpos<1 || dotpos<atpos+2 || dotpos+2>=x.length)
{
alert("Not a valid e-mail address");
return false;
} */
return true;
}
</script>
<form name="registerform" action ="Register" method = "post">
<div>
<h3> Event Registration Form </h3>
<div>
<label for ="first" class ="label" > First Name </label>
<input type="text" id="first" name="firstname" class="text" />
</div>
<div>
<label for ="last" class ="label">Last Name</label>
<input type="text" id="last" name="lastname" class="text">
</div>
<div>
<label for ="dob" class ="label">Date Of Birth </label>
<input type="text" id="dob" name="dob" class="text">
</div>
<div>
<label for ="email" class ="label">Email_Id</label>
<input type="text" id="email" name="email" class="text">
</div>
<div><input type="submit" value ="submit" class="button" onclick="register(registerform)"></div>
</div></form>
</body>
</html>
You can try something like this with MySQL:
PreparedStatement ps = connection.prepareStatement(query, PreparedStatement.RETURN_GENERATED_KEYS);
// Get generated key.
ps.executeUpdate();
ResultSet rs = ps.getGeneratedKeys();
if (rs.next()) {
int key = rs.getInt(1);
}
Where ps is the PreparedStatement and you retrieve the key from the ResultSet object.
To get the last generated auto-increment id you can use the MySql function LAST_INSERT_ID().
Another option would be to use the MAX aggregation function to return the maximum value for the id field. Since the last inserted id is always the max MAX(id).
Because this is a standard way, this has been added to a constant, so doing:
PreparedStatement ps = con.prepareStatement(YOUR_SQL, Statement.RETURN_GENERATED_KEYS);
For some JDBC drivers like Oracle you have to specify the columns explicitly:
PreparedStatement ps = con.prepareStatement(YOUR_SQL, new String[]{"USER_ID"});
I am newbie here. I have an assignment that requires to connect mysql, servlet and java (because i want to separate java code and html code. Previously, i combined the codes to make it easier and was rejected)
So, basically, in mySql i write this,
create table login2 (username varchar (30), password varchar(30), designation varchar(10));
insert into login2 values('lala','123','A');
and i create loginDisp.java in the servlet using eclipse. This is my command
package Servlet;
import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class loginDisp extends HttpServlet {
public void service(HttpServletRequest request,
HttpServletResponse response)
throws IOException, ServletException{
// String username=request.getParameter("Username");
// String password=request.getParameter("Password");
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>Servlet JDBC</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
Class.forName("com.mysql.jdbc.Driver");
con =DriverManager.getConnection
("url/tablename","uname","pssword");
stmt = con.createStatement();
rs = stmt.executeQuery("SELECT * FROM login2");
// displaying records
while(rs.next()){
out.print(rs.getObject(1).toString());
out.print("\t\t\t");
out.print(rs.getObject(2).toString());
out.print("<br>");
}
} catch (SQLException e) {
throw new ServletException("Servlet Could not display records.", e);
} catch (ClassNotFoundException e) {
throw new ServletException("JDBC Driver not found.", e);
} finally {
try {
if(rs != null) {
rs.close();
rs = null;
}
if(stmt != null) {
stmt.close();
stmt = null;
}
if(con != null) {
con.close();
con = null;
}
} catch (SQLException e) {}
}
out.close();
}
}
When i execute, it is well displayed. Hence, i started to make the Login.jsp as i want to make a text.box for user to insert username and password. This is my code
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<body>
<center>
<div class="wrapper">
<br>
<br>
<h2>Doctor</h2>
<form name="form1" method="post" action="loginDisp" > <!-- onsubmit="return validateForm()" -->
<table width="326" border="1" align="center">
<center> <tr>
<th width="138" scope="row">Username</th>
<td width="142"><input type="text" name="Username"></td>
</tr>
</center>
<tr>
<th height="31" style="width: 162px;"><span class="style2">Password</span>
</th>
<td width="142"><input type="password" name="Password"></td>
</tr>
<tr>
</tr>
</table>
<p align="center">
<input type="submit" name="Submit" value="Submit">
</p> ${message}
</form>
</div>
</center>
</body>
</body>
</html>
and I get the data from mySQL displayed. I add another log.java in servlet because i thought when we need a data fetched from jsp to databased and displayed when be called. This is code in log.java
package Servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class log extends HttpServlet {
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//Get username and password from the JSP page
String username=request.getParameter("Username");
String password=request.getParameter("Password");
//Print the above got values in console
System.out.println("The username is" +username);
System.out.println("\nand the password is" +password);
}
}
The username and password inserted in login.jsp does not inserted automatically in mySQL, hence when i try to executed loginDisp.java , it will display only the data i inserted manually in mySQL.
You can not use the java file name as action this is defined in the web.xml file and there is servlet mapping and you can use
<servlet>
<servlet-name>log</servlet-name>
<servlet-class>loginDisplay</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>log</servlet-name>
<url-pattern>/loginDisplay</url-pattern>
</servlet-mapping>
and now you can use the action = "loginDisplay" in the action tag and by using this
I hope you did not face the problem of 404 error.
You entered a wrong action in form.
Since form's action attribute takes the path of the servlet you should give the relavent mapping specified in web.xml
action="loginDisplay.java"
should be action="/loginDisplay"
<form name="form1" method="post" action="loginDisplay.java" onsubmit="return validateForm()">
It should be
<form name="form1" method="post" action="/loginDisplay" onsubmit="return validateForm()">
If /loginDisplay is not the exact mapping in your web.xml check the web.xml file and see the mapping for loginDisplay and give that path as action.
A quick example
Create a new package (called dao or model) where you put your logic to access to the DB.
Then create a Java Bean Object where store the results of your DB and instanciate your class of the logic in the servlet, then access to the properties of the Bean and show it in the WEB.
package model:
class DaoAccess (methods to connect with DB)
class Login (properties of the table with getXXX and setXXX of each one)
package Servlet.
class loginDisplay:
public class loginDisplay extends HttpServlet {
public void service(HttpServletRequest request, HttpServletResponse response)
throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<html>");
out.println("<head><title>Servlet JDBC</title></head>");
out.println("<body>");
out.println("<h1>loginDisplay</h1>");
out.println("</body></html>");
// connecting to database
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
DaoAccess dao = new DaoAccess();
List<Login> list = dao.readAll();
for(Login obj: list){
out.write(obj.getName());
out.write(obj.getPassword());
}
out.close();
}
}
I am trying to pass username and password from a jsp page to Authenticate Method in a Java class (LogMeIn.java), but I am getting 'false' as a result. However when I hard code values (abc/abc) I do get 'pass' result. ie. it's successful.
Please can you advise why it's not accepting the parameters passed through jsp?
--LogMeIn.java--
package org.cms.model;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.PreparedStatement;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.sql.DataSource;
public class LogMeIn {
public boolean Authenticate( String username, String password ) {
Connection connection = null;
// Statement statement = null;
ResultSet resultSet = null;
PreparedStatement pst = null;
String query;
boolean result = false;
try {
Context initCtx = new InitialContext();
Context envCtx = (Context) initCtx.lookup("java:comp/env");
DataSource ds = (DataSource) envCtx.lookup("jdbc/TestDB");
connection = ds.getConnection();
//statement = connection.createStatement();
query = "select name from account where name= ? and password = ?";
pst = connection.prepareStatement(query);
pst.setString(1, username);
pst.setString(2, password);
resultSet = pst.executeQuery();
int count=0;
if(resultSet.next())
{
count++;
}
if(count>0)
{
result = true;
}
else
{
result = false;
}
}
catch (SQLException e){
e.printStackTrace();
}
catch (Exception e){
e.printStackTrace();
}
finally {
if (resultSet != null) try { resultSet.close(); } catch (SQLException logOrIgnore) {}
if (connection != null) try { connection.close(); } catch (SQLException logOrIgnore) {}
}
return result;
}
}
---LoginServlet---
package org.cms.controller;
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 org.cms.model.LogMeIn;
/**
* Servlet implementation class LoginServlet
*/
#WebServlet("/LoginServlet")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username;
String password;
username = request.getParameter("user");
password = request.getParameter("pass");
LogMeIn a = new LogMeIn();
boolean result = a.Authenticate(username, password);
System.out.println(result);
if (result) {
request.setAttribute("loginresult","Pass");
RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
else {
request.setAttribute("loginresult","Failed");
RequestDispatcher dispatcher = request.getRequestDispatcher("Login.jsp");
dispatcher.forward(request, response);
}
}
}
---Login.jsp---
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%# taglib uri="http://java.sun.com/jsp/jstl/functions" prefix="fn" %>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<title>Login</title>
<link rel="stylesheet" href="css/style.css" type="text/css"></link>
<script language="JavaScript" type="text/JavaScript" src="validate.js"> </script>
</head>
<body>
<form enctype="multipart/form-data" onSubmit="return validate(this)" method="post" action="LoginServlet" class="form">
<table border = "0">
<tr align="left" valign="top">
<td>User Name:</td>
<td><input type="text" name ="user" class="inputbox"/></td>
</tr>
<tr align="left" valign="top">
<td>Password:</td>
<td><input type="password" name ="pass" class="inputbox" /></td>
</tr>
<tr align="left" valign="top">
<td></td>
<td><input type="submit" name="submit"
value="submit" class="fb8"/></td>
</tr>
</table>
<c:out value="${loginresult}" > </c:out>
</form>
</body>
</html>
Many Thanks
use setAttribute() method. This method sets the value of the attribute for the request which is retrieved later in the servlet by passing the request object through the dispatcher method. The set value of the attribute is retrieved by the getAttribute() method of the request object.
http://www.roseindia.net/servlets/request-parameter.shtml
http://www.roseindia.net/tutorial/servlet/passParameters.html
Hello i'm new to hava and i'm having a problem viewing my records from an arraylist in JSP page,
whenever i load the page i get:
[content.animalBean#1e8614a, content.animalBean#14b52aa, content.animalBean#2026f3, content.animalBean#dd20b6, content.animalBean#18eb00c] 1 which is not the database records
here is my code:
selectAnimalServlet:
package content;
import java.util.Iterator;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class selectAnimalServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
try
{
List<animalBean> beans = DAO.selectListAnimal();
request.setAttribute("beans", beans);
request.getRequestDispatcher("checkAnimal.jsp").forward(request, response);
}
catch (Throwable theException)
{
System.out.println(theException);
}
}
}
AnimalBean:
package content;
public class animalBean {
private String animalName;
private String animalDob;
private String animalGender;
private String animalSource;
private String animalBreed;
private String animalRemark;
public String getAnimalName() {return animalName;}
public String getAnimalDob() {return animalDob;}
public String getAnimalGender() {return animalGender;}
public String getAnimalSource() {return animalSource;}
public String getAnimalBreed() {return animalBreed;}
public String getAnimalRemark() {return animalRemark;}
public void setAnimalName(String animalName) {this.animalName = animalName;}
public void setAnimalDob(String animalDob) {this.animalDob = animalDob;}
public void setAnimalGender(String animalGender) {this.animalGender = animalGender;}
public void setAnimalSource(String animalSource) {this.animalSource = animalSource;}
public void setAnimalBreed(String animalBreed) {this.animalBreed = animalBreed;}
public void setAnimalRemark(String animalRemark) {this.animalRemark = animalRemark;}
}
DAO class:
package content;
import java.sql.*;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class DAO
{
static Connection currentCon = null;
static ResultSet rs = null;
public static loginAuth login(loginAuth bean) {
//preparing some objects for connection
Statement stmt = null;
String username = bean.getUsername();
String password = bean.getPassword();
String searchQuery =
"select * from user where username='"
+ username
+ "' AND password='"
+ password
+ "'";
// "System.out.println" prints in the console; Normally used to trace the process
System.out.println("Your user name is " + username);
System.out.println("Your password is " + password);
System.out.println("Query: "+searchQuery);
try
{
//connect to DB
currentCon = dbConnection.getConnection();
stmt=currentCon.createStatement();
rs = stmt.executeQuery(searchQuery);
boolean more = rs.next();
// if user does not exist set the isValid variable to false
if (!more)
{
System.out.println("Sorry, you are not a registered user! Please sign up first");
bean.setValid(false);
}
//if user exists set the isValid variable to true
else if (more)
{
String firstName = rs.getString("FirstName");
String lastName = rs.getString("LastName");
System.out.println("Welcome " + firstName);
bean.setfname(firstName);
bean.setlname(lastName);
bean.setValid(true);
}
}
catch (Exception ex)
{
System.out.println("Log In failed: An Exception has occurred! " + ex);
}
//some exception handling
finally
{
if (rs != null) {
try {
rs.close();
} catch (Exception e) {}
rs = null;
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception e) {}
stmt = null;
}
if (currentCon != null) {
try {
currentCon.close();
} catch (Exception e) {
}
currentCon = null;
}
}
return bean;
}
public static List<animalBean> selectListAnimal() throws SQLException {
Statement stmt = null;
List<animalBean> beans = new ArrayList<animalBean>();
try {
currentCon = dbConnection.getConnection();
String animalSearchQuery = "select a.aname ,a.dob, a.gender , a.source, s.sname, a.remark from animal as a , specie as s where a.specie_id = s.specie_id and a.available ='y'";
stmt=currentCon.createStatement();
rs = stmt.executeQuery(animalSearchQuery);
while (rs.next()) {
animalBean bean = new animalBean();
bean.setAnimalName(rs.getString("aname"));
bean.setAnimalDob(rs.getString("dob"));
bean.setAnimalGender(rs.getString("gender"));
bean.setAnimalSource(rs.getString("source"));
bean.setAnimalBreed(rs.getString("sname"));
bean.setAnimalRemark(rs.getString("remark"));
beans.add(bean);
}
} finally {
if (rs != null) try { rs.close(); } catch (SQLException logOrIgnore) {}
if (stmt != null) try { stmt.close(); } catch (SQLException logOrIgnore) {}
if (currentCon != null) try { currentCon.close(); } catch (SQLException logOrIgnore) {}
}
return beans;
}
}
and last the JSP page animalCheck.jsp:
<%# page language="java"
contentType="text/html; charset=windows-1256"
pageEncoding="windows-1256"
import="content.animalBean"
import="content.DAO"
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=windows-1256">
<title>Animal list</title>
<link rel="stylesheet"
href="./css/styles.css"
type="text/css"/>
</head>
<body>
<table class="title">
<tr><th>Zoo keeper</th></tr>
</table>
<h1>Animal list</h1>
<center>
<table width="100 % " id='table1' border="1" cellspacing="2" cellpadding="2">
<tr class="tab-highlighted-2">
<td class="tab-highlighted-2" width="15">
<div align="left">Name</div>
</td>
<td class="tab-highlighted-2" width="20">
<div align="left">Age</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Gender</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Status</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Breed</div>
</td>
<td class="tab-highlighted-2" width="15">
<div align="left">Remarks</div>
</td>
</tr>
<c:forEach items="${beans}" var="view">
<tr>
<td>${view.animalName} </td>
<td>${view.animalDob}</td>
<td>${view.animalGender}</td>
<td>${view.animalSource}</td>
<td>${view.animalBreed}</td>
<td>${view.animalRemark}</td>
</tr>
</c:forEach>
</table>
</center>
</body></html>
I've been struggeling on this since 2 days and i checked many websites and followed many guides but still nothing worked for me :(
I appreciate any kind of help
You forgot to declare the JSTL core taglib. Add the following to top of your JSP:
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
See also:
Our JSTL wiki page - contains information about how to install and use JSTL
Show JDBC ResultSet in HTML in JSP page using MVC and DAO pattern
How to avoid Java code in JSP files?
Unrelated to the concrete problem, there are several other problems in your code:
You should never declare DB resources as static. This is not threadsafe and is prone to resource leaking. Declare them inside the very same method block as you're executing the SQL query.
You have a SQL injection hole in login() method. Use PreparedStatement.
You don't need to use #page import in your JSP if you aren't using any scriptlets.
Classnames are supposed to start with uppercase.
Can you try something like this on top of your page
<% List<animalBean> animals = (animalBean)request.getAttribute("beans"); %>
and then change your c:forEach tag to point it to animals instead of beans?