why i can't load data from database to jsp file? [duplicate] - java

This question already has an answer here:
Submitting form to Servlet which interacts with database results in blank page
(1 answer)
Closed 2 years ago.
Hello i am learning java servlet and i am coding a web ecommerce and i want to load data product form databse to jsp file i got some issues.My list product can't show on the jsp file.Pls help me
this is my class HomeController
package com.WebBanHang.controller;
import java.io.IOException;
import java.util.ArrayList;
import com.WebBanHang.model.Product;
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.WebBanHang.dao.Dao;
#WebServlet("/home")
public class HomeController extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//b1: get data from dao
Dao dao = new Dao();
ArrayList<Product> list = dao.getAllProduct();
//b2: set data to jsp
request.setAttribute("listP", list);
request.getRequestDispatcher("/view/Home.jsp").forward(request, response);
}
}
this is my class Dao to get product from database
package com.WebBanHang.dao;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;
import com.WebBanHang.model.Product;
public class Dao {
public Dao() {
super();
// TODO Auto-generated constructor stub
}
Connection conn = null;
PreparedStatement ps = null;
ResultSet rs = null;
public ArrayList<Product> getAllProduct(){
ArrayList<Product> list = new ArrayList<>();
String query = "select * from tblProduct";
try {
conn = new DbConnection().getConnection();
ps = conn.prepareStatement(query);
rs = ps.executeQuery();
while(rs.next()) {
list.add(new Product(rs.getString(1),
rs.getString(2),
rs.getDouble(3),
rs.getString(4),
rs.getString(5)));
}
} catch (Exception e) {
// TODO: handle exception
}
return list;
}
}
and this is my jsp file
<c:forEach items="${listP}" var="o">
<div class="row wow fadeIn">
<!--Fourth column-->
<div class="col-lg-3 col-md-6 mb-4">
<!--Card-->
<div class="card">
<!--Card image-->
<div class="view overlay">
<img src="${o.image}" class="card-img-top" alt="">
<a>
<div class="mask rgba-white-slight"></div>
</a>
</div>
<!--Card image-->
<!--Card content-->
<div class="card-body text-center">
<!--Category & Title-->
<a href="" class="grey-text">
<h5>${o.name}</h5>
</a>
<h5>
<strong>
${o.description}
</strong>
</h5>
<h4 class="font-weight-bold blue-text">
<strong>${o.price}</strong>
</h4>
</div>
<!--Card content-->
</div>
<!--Card-->
</div>
<!--Fourth column-->
</div>
<!--Grid row-->
</c:forEach>
When i run class HomeController my jsp file not show my list product
Help me pls.Thank you

when reading requests attributes you need to use the object requestScope.
Example:
<c:forEach items="${requestScope.listP}" var="o">

Related

Getting form data in a jsp and retrieve that data from servlet with of mvc from sql database and show the result table in another jsp?

Well as I described I have a MVC model implementation using glassfish and NetBeans support. I am fairly new into this area of learning and finding it difficult to understand how to implement a search bar in the web app and retrieve that data using the servlet and model and daos . The coding is as follow:
JSP file where search textbox is placed :
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Doctor Dashboard</title>
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<script src="https://kit.fontawesome.com/0afbc9b86d.js" crossorigin="anonymous"></script>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/css/styles.css" />
</head>
<body id="body">
<div class="container">
<nav class="navbar">
<div class="nav_icon" onclick="toggleSidebar()">
<i class="fa fa-bars" aria-hidden="true"></i>
</div>
<div class="navbar__left">
<a class="active_link" href="#">Profile</a>
</div>
<div class="navbar__right">
<a href="#">
<i class="fa fa-search" aria-hidden="true"></i>
</a>
<a href="#">
<i class="fa fa-clock-o" aria-hidden="true"></i>
</a>
<a href="#">
<img width="30" src="assets/avatar.svg" alt="" />
<!-- <i class="fa fa-user-circle-o" aria-hidden="true"></i> -->
</a>
</div>
</nav>
<main>
<div class="main__container">
<form method="POST" action="<%=request.getContextPath()%>/Dreport/patientrecordinfo" style="align-items:center">
<div style="align-items: center;">
<h1>Patient Records</h1>
<p style="margin-top: 2rem; align-items: center">Enter the Patient ID:</p>
//Place where the data to be retrieved from
<input style=" width:20%; height:40px; display: inline-block; background:whitesmoke;"type="text" placeholder="Patient ID..." name="patientid" required><br>
<input style="margin-top:2rem;" required type="checkbox" name="confirm" style="margin-bottom:15px"> Agree to Protect Customer privacy
<br>
<div class="clearfix">
<button style="background-color:blueviolet; color: white; padding: 14px 20px; margin: 8px 0; border: none; cursor: pointer;width: 30%;
opacity: 0.9;" type="submit" class="signupbtn">Search</button>
</div>
</div>
</form>
</main>
<div id="sidebar">
<div class="sidebar__title">
<div class="sidebar__img">
<img src="${pageContext.request.contextPath}/imgs/Doctor.png" style="border-radius: 50%;" alt="logo" />
<h1> Welcome Doctor,<br>
Nimesh Kottawatta
</h1>
</div>
<i
onclick="closeSidebar()"
class="fa fa-times"
id="sidebarIcon"
aria-hidden="true"
></i>
</div>
<!--SIDE_BAR-->
<div class="sidebar__menu">
<div class="sidebar__link ">
<i class="fas fa-tachometer-alt"></i>
Dashboard
</div>
<div class="sidebar__link active_menu_link">
<i class="fa fa-line-chart"></i>
Check Report
</div>
<div class="sidebar__link">
<i class="fa fa-list-alt"></i>
Update Report
</div>
<div class="sidebar__logout">
<i class="fa fa-power-off"></i>
Log out
</div>
</div>
</div>
</div>
<script src="js/script.js"></script>
</body>
</html>
And the Servlet :
package com.primavera.controllers;
import com.primavera.Managers.StaffManager;
import com.primavera.entities.Patient;
import java.io.IOException;
import java.sql.ResultSet;
import java.util.ArrayList;
import java.util.List;
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;
#WebServlet(name = "Dreport", urlPatterns = {"/Dreport","/Dreport/Dashboard","/Dreport/reportupdate","/Dreport/patientrecordinfo"})
public class Dreport extends HttpServlet {
//Default constructor
public Dreport(){}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
RequestDispatcher dispatcher=null;
// 1. Get data from the Model
if (request.getServletPath().contains("/Dashboard")) {
dispatcher= request.getRequestDispatcher("/DoctorDashboard.jsp");
} else if (request.getServletPath().contains("/reportupdate")){
dispatcher= request.getRequestDispatcher("/DUpdateReport.jsp");
}else if (request.getServletPath().contains("/patientrecordinfo")){
//1.Get data info from model
int user_Id=Integer.parseInt(request.getParameter("patientid"));//Taking doctor inserting id
List<Patient> list = new ArrayList<Patient>();//Creating a list to hold data
list=StaffManager.getInstance().getPatientInfo(user_Id);//MVC method implementation for Searching patient
request.setAttribute("list", list);
//view
RequestDispatcher rd= request.getRequestDispatcher("records.jsp");
rd.forward(request, response);
}
else {
dispatcher= request.getRequestDispatcher("/DReport.jsp");
}
// 2. Forwarding to View
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
The model: Manager class :
package com.primavera.Managers;
import com.primavera.daos.PatientDao;
import com.primavera.entities.Doctor;
import com.primavera.entities.Nurse;
import com.primavera.entities.Patient;
import java.util.ArrayList;
import java.util.Date;
import java.sql.ResultSet;
import java.util.List;
import java.util.List;
import java.util.ArrayList;
import java.util.List;
public class StaffManager {
//Creating a singletance instance
private static StaffManager instance = new StaffManager();
private static PatientDao dao= new PatientDao();
private StaffManager() {
}
public static StaffManager getInstance() {
return instance;
}
//Method implementations
public List <Patient> getPatientInfo(int user_Id) {
return dao.getPatient(user_Id);
}
}
And the Dao is :
package com.primavera.daos;
import com.primavera.entities.Patient;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
public class PatientDao {
DatabaseConnection db= new DatabaseConnection();
Patient patient = new Patient();
//Method implemetation for getting Patient records by Doctor
public List <Patient> getPatient(int user_Id) {
List <Patient> list = new ArrayList<Patient>();
ResultSet rs=null;
try{
PreparedStatement pst =db.conn().prepareStatement("SELECT * FROM patient WHERE user_id = ?"); // ? = placeholder
pst.setInt(1, user_Id); // Bind the value to the placeholder
rs = pst.executeQuery();
while(rs.next()){
patient.setName(rs.getString("user_name"));
patient.setGender(rs.getString("user_gender"));
list.add(patient);
}
}
catch(SQLException e){
e.printStackTrace();
}
return list;
}
}
And the another jsp for now i would the data to be visible in :
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Patient Report</title>
</head>
<body>
<c:if test="${list!=null}">
<table>
<c:forEach items="${list}" var="record">
<tr>
<td>${record.patient_Id}</td>
<td>${record.name }</td>
<td>${record.gender }</td>
<td>${record.DOB }</td>
<td>${record.phone }</td>
</tr>
</c:forEach>
</table>
</c:if>
</body>
</html>
Thank you so much in advance for that supports me to solve it .
Well I discovered my errors there were few first I had tried to retrieve data from the doGet method in servlet and not the doPost which was a huge error since the method that form uses to send data is POST, some basic correction were as below :
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
if (request.getServletPath().contains("patientrecordinfo")) {
// Calling doPost to retrieve form data
int user_Id=Integer.parseInt(request.getParameter("patientid"));//Taking doctor inserting id
List list = new ArrayList<>();//Creating a list to hold data
list = StaffManager.getInstance().getPatientInfo(user_Id);//MVC method implementation for Searching patient
request.setAttribute("list", list);
request.getRequestDispatcher("/records.jsp").forward(request, response);
}
}
And class implementations were :
Manager class method :
public List getPatientInfo(int user_Id) {
return dao.getPatient(user_Id);
}
And DAO:
public List getPatient(int user_Id) {
List list = new ArrayList();
ResultSet rs = null;
try {
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/hms", "root", "");
PreparedStatement pst = conn.prepareStatement("SELECT * FROM patient WHERE user_id = ?"); // ? = placeholder
pst.setInt(1, user_Id); // Bind the value to the placeholder
rs = pst.executeQuery();
if (rs != null) {
while (rs.next()) {
Patient patient = new Patient();
patient.setPatient_Id(rs.getString("user_id"));
patient.setName(rs.getString("user_name"));
patient.setGender(rs.getString("user_gender"));
patient.setDOB(rs.getDate("user_DOB"));
patient.setPhone(rs.getInt("phone"));
patient.setSickness(rs.getString("user_sickeness"));
patient.setAllegeries(rs.getString("user_allergies"));
patient.setSymptoms(rs.getString("user_specail_request"));
patient.setAddress(rs.getString("user_address"));
list.add(patient);
}
}
} catch (SQLException e) {
e.printStackTrace();
}
return list;
}
Hope someone would benefit as myself I'm a beginner to java MVC might not be the most elegant way , would love for anyone ideas to improve as well.

Servlet is not printing anything with PrintWriter object

This is my JSP code, i am using get method to send data to go to servlet , servlet name is googleser.
<body>
<div class="formdiv">
<h1 align="center">Shikhar Google</h1>
<form action="googleser" method="get" align="center">
<input type="text" name="search1" class="search1"><br>
<input type="submit" class="submitbtn">
</form>
</div>
</body>
This is my servlet code . I tired printing every option related with printwriter method , but none of these worked.
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;
public class googleser extends HttpServlet
{
public void doGet(HttpServletRequest request,HttpServletResponse response) throws IOException
{
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3307/shikhar","root","");
Statement st = con.createStatement();
ResultSet rs= st.executeQuery("select * from student");
PrintWriter out=response.getWriter();
while(rs.next())
{
out.print(rs.getString(2));
}
String a= request.getParameter("search1");
out.print("<h1>Shikhar</h1>");
out.print("sddsdssdsd");
}
catch(Exception ex)
{
// System.out.print("yes yes yes");
}
}
}
please call the flush method after writing content into the response.
out.flush();

error in session build in a servlet

There is a problem in the session.
In create.html when i click on createdepartment the createdepartment.jsp page opens i copy its url1 after i submit the data , i again copy the url2 and then i logout after logging out when i paste url2 in the browser it gives message that Please login first and opens login.html but when i paste url1 in the browser it opens it but it shouldn't. Why is this happening?
I have given the code please could someone correct it?
LoginServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet {
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
String name=request.getParameter("name");
String password=request.getParameter("password");
boolean status=false;
try{
Connection con=ConnectionProvider.getCon();
String sql="select * from roles where name='" + name + "' and pass='" + password + "'";
PreparedStatement stmt =con.prepareStatement(sql);
String role="admin";
ResultSet rs=stmt.executeQuery();
if(rs.next())
{
status=true;
role=rs.getString("role");
}
if(status){
out.print("Welcome, "+name);
HttpSession session=request.getSession();
session.setAttribute("name",name);
if(role!=null && role.equals("admin") ){
request.getRequestDispatcher("create.html").include(request, response);
}
else {
request.getRequestDispatcher("create1.html").include(request, response);
}
}
else{
out.print("Sorry, username or password error!");
request.getRequestDispatcher("login.html").include(request, response);
}
}catch( SQLException | ServletException | IOException e){}
}
}
}
create.html
Logout
Create Department
Create Users
<hr/>
department.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<h1>Create Department</h1>
<br>
<form action="DepartmentServlet">
<table border="1">
<tbody>
<tr>
<td>Company Name :</td>
<td><input type="text" name="company" value="" size="50" /></td>
</tr>
<tr>
<td>Department Name</td>
<td><input type="text" name="department" value="" size="50" /> </td>
</tr>
<tr>
<td>Head Office :</td>
<td><input type="text" name="place" value="" size="50" /></td>
</tr>
</tbody>
</table>
<input type="reset" value="Clear" name="Clear" />
<input type="submit" value="Submit" name="Submit" />
</form>
</body>
</html>
DepartmentServlet.java
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class DepartmentServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession(false);
if(session!=null){
String name=(String)session.getAttribute("name");
boolean status=false;
try{
String department=request.getParameter("department");
String company=request.getParameter("company");
String place=request.getParameter("place");
Connection con=ConnectionProvider.getCon();
String sql="insert into department(departmentname,company,place) values (?,?,?)";
PreparedStatement pstmt =con.prepareStatement(sql);
pstmt.setString(1,department);
pstmt.setString(2,company);
pstmt.setString(3,place);
int rs=pstmt.executeUpdate();
if(rs>0){status=true;}
}catch(Exception e){}
if(status){
out.print("Values have been inserted,"+name);
request.getSession();}
else
{
out.print("failed");
}
request.getRequestDispatcher("department.jsp").include(request, response);
}
else{
out.print("Please login first");
request.getRequestDispatcher("login.html").include(request, response);
}
}
}
}
Logout.Servlet
package bean;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
public class LogoutServlet extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
try (PrintWriter out = response.getWriter()) {
request.getRequestDispatcher("link.html").include(request, response);
HttpSession session=request.getSession();
session.invalidate();
out.print("You are successfully logged out!");
}
}
}
http://mytechsoft.jimdo.com/exclusive-projects
above link is for your problem, refer first 2 photos in it
LogoutServlet.java code might has problem.
You haven't mentioned its code.
Logout procedure includes 2 important things..
Remove all attributes attached to that session object
Make session object null (by making session.invalidate(); )
doing this makes session eligible for Garbage Collection, and reference of object (object stored in heap memory) is deleted (reference is stored in stack ).
In your case, I guess (because LogoutServlet.java is not there), most likely the reason for error is that
"You might be creating a new session Object and then you are copying the reference of old session object, now you would be deleting this new session by "session.invalidate();".
The above process deletes new reference but old one is still there because it's copy available in new object is deleted not the original one.
For More Specific and correct answer, please attach your LogoutServlet.java source code too.
Your logout servlet should have request.getSession(false)..This will not return new session if one already exists..Also clear your browser cache before running it.
HttpSession session=request.getSession(false);
session.invalidate();

Tomcat error HTTP Status 405 - HTTP method GET is not supported by this URL

This is my jsp page
<html>
<head>
<link rel = "stylesheet" href="main.css"/>
<title>Login Page</title> </head>
<body>
<div class ="RegWrap">
<div class ="Set">
<form name="actionForm" action="Connecter" method ="Get">
<table>
<tr><td>Enter your Username: </td>
<td><input type="text" name="userName"/></td></tr>
<tr><td>Enter your Password: </td>
<td><input type="password" name="password"/></td></tr>
<tr><td colspan="2" align="center"><input type="submit" value="login"> </td></tr>
</table>
</form>
</div>
</div>
</body>
</html>
This is my Connecter class :
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;`
public class Connecter extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException{
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
String p=request.getParameter("password");
if(LoginDao.validate(n, p)){
RequestDispatcher rd=request.getRequestDispatcher("welcom");
rd.forward(request,response);`
}
else {
out.print("Sorry username or password error");
RequestDispatcher rd=request.getRequestDispatcher("Sign up.jsp");
rd.include(request,response);
}
out.close();
}`
This is my Welcome page
import java.io.IOException;`
import java.io.PrintWriter;`
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;`
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class welcom extends HttpServlet {
public class WelcomeServlet extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("userName");
out.print("Welcome "+n);
out.close();
}
}
}
This is my Dao page
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
public class LoginDao {
public static boolean validate(String userName,String password){
boolean status=false;
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection
("jdbc:mysql://localhost:3306 /autolube","root","mehar");
PreparedStatement ps=con.prepareStatement
("select * from person where userName=?and password=?");
ps.setString(1,userName);
ps.setString(2,password);`ResultSet rs=ps.executeQuery();
status=rs.next();`}catch(Exception e){System.out.println(e);
}
return status;
}
}
In your servlet add the below line. As I commented I think its a problem with web.xml. If you are using servlet 3.0 you can use the below ammotation or map in web.xml.
#WebServlet("/Connecter")
public class Connecter extends HttpServlet
if url-pattern is /Connector then add /Connector in your form tag of index.html.

How to properly display Mysql tables using servlets and java?

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();
}
}

Categories

Resources