Simple authentication using Servlet and Mysql - java

I am trying to create Simple login page. Here's my code:
Servlet :
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
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("/MySQLConnect")
public class MySQLConnect extends HttpServlet {
private static final long serialVersionUID = 1L;
//do post method calling
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String user = request.getParameter("user");
String pass = request.getParameter("pass");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost:3306/javademo", "root", "admin");
//prepared statement for calling query
PreparedStatement pst = conn.prepareStatement("Select user,pass from login where user=? and pass=?");
pst.setString(1, user);
pst.setString(2, pass);
ResultSet rs = pst.executeQuery();
if (rs.next()) {
out.println("Correct login credentials");
}
else {
out.println("Incorrect login credentials");
}
} catch (Exception e) {
e.printStackTrace();
}
finally{}
}
}
index.html:
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form method="post" action="MySQLConnect">
UserName :<input type="text" name="user" /><br/><br/>
Password :<input type="password" name="pass" /><br/><br/>
<input type="submit" value="Login" />
</form>
</body>
</html>
Web.xml
<display-name>AuthenticationUsingMySQL</display-name>
<servlet>
<servlet-name>MySQLConnect</servlet-name>
<servlet-class>MySQLConnect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>MySQLConnect</servlet-name>
<url-pattern>/Login</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>30</session-timeout>
</session-config>
I am trying to open the page using
http://localhost:8080/AuthenticationUsingMySQL/Login
But it is showing HTTP Status 405 - HTTP method GET is not supported by this URL

When you go to http://localhost:8080/AuthenticationUsingMySQL/Login on your browser you send GET request to your servlet which doesn't provide GET method.
Just go to http://localhost:8080/AuthenticationUsingMySQL/ and it will work.

If you are trying to open that link in your browser then that error makes sense. You need to use a tool like Fiddler, or set up a javascript test method, to test your code. It looks like you are constructing a POST method in your code. Web browsers, by default, use GET to access web resources, thus the need for a different tool which is able to perform a POST. Otherwise you will need to modify your code so it accepts GET requests.

You can't directly use te URL in the Browser as your webservlet supports POST request, so try to POST the request from JSP only or use the tools like POSTMAN, SOAPUI.

Related

Questions regarding HTTP 404 Not Found

I am currently working on A middle-size Java Web application using Netbeans & GlassFish. And everything was good until I placed all JSP fils into the folder called LoginOut, which I created it to store all specific JSP files to make my project succinct. But after I placed all JSP files into that folder, the problem came out. In detailed, the browser keeps telling me HTTP 404 Not Found. This is a very common error I believe. I put relevant screenshots below. By the way, when I put all JSP files outside LoginOut folder, my application works fine. I don't know where the error has occurred..(Here is code) Project Fils Structure
public User checkLogin(String email, String password) throws SQLException,
ClassNotFoundException {
Connection conn = getConnection();
String sql = "SELECT * FROM users WHERE email = ? and password = ?";
PreparedStatement st = conn.prepareStatement(sql);
st.setString(1, email);
st.setString(2, password);
ResultSet rs = st.executeQuery();
User user = null;
if (rs.next()) {
user = new User();
user.setFullName(rs.getString("fullname"));
user.setEmail(email);
}
conn.close();
return user;
}
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Login Page</title>
</head>
<body>
<form action="LoginServlet" method="POST">
Email: <input type="text" name="email" ><br><br>
Password: <input type="password" name="pass" ><br><br>
<input type="submit" value="Login" ><br><br>
Click here to go back.
</form>
</body>
</html>
package controller.Servlet;
import Dao.UserDao.UserDAO;
import java.io.IOException;
import java.io.PrintWriter;
import static java.lang.System.out;
import java.sql.SQLException;
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;
import model.User.User;
#WebServlet("/Login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
UserDAO userDao = new UserDAO();
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String email = request.getParameter("email");
String password = request.getParameter("pass");
try {
User user = userDao.checkLogin(email, password);
String destPage = "Login.jsp";
if (user != null) {
HttpSession session = request.getSession();
session.setAttribute("user", user);
destPage = "home.jsp";
} else {
String message = "Invalid email/password";
request.setAttribute("message", message);
}
RequestDispatcher dispatcher = request.getRequestDispatcher(destPage);
dispatcher.forward(request, response);
} catch (SQLException | ClassNotFoundException ex) {
throw new ServletException(ex);
}
}
}

404 Apache tomcat in a Java project

So this is my project:
Where Registro.java is:
package Ejer2;
import java.io.IOException;
import java.io.PrintWriter;
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;
import javax.servlet.*;
#SuppressWarnings("deprecation")
#WebServlet(urlPatterns="/Registro")
public class Registro extends HttpServlet implements SingleThreadModel{
private static final long serialVersionUID = 1L;
public Registro() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException {
HttpSession session=req.getSession(true);
Usuario miuser=(Usuario)session.getValue(session.getId());
if(miuser==null){
miuser=new Usuario(req.getParameter("user"),req.getParameter("password"));
session.putValue(session.getId(),miuser);
}
res.setContentType("text/html");
String user=req.getParameter("user");
//String pass = req.getParameter("pass");
PrintWriter toClient = res.getWriter();
toClient.println("<html>");
toClient.println("<title>REGISTRO REALIZADO</title>");
toClient.println("Usuario "+user+" registrado con exito");
toClient.println("</html>");
toClient.close();
}
}
And registro.html is:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Registro</title>
</head>
<body>
<form action="/Ejer2/Registro" method="POST">
<input type=hidden name=registro value=resultadoRegistro>
<BR><BR>Username: <input type=text name=user>
<BR><BR>Password: <input type=password name=pass>
<BR><BR><input type=submit value="Enviar"><input type=reset>
</form>
</body>
</html>
When I run registro.html everything goes as expected:
But when I enter an username and a password it doesnt work:
4
It seems as if it doesnt find the Registro.java. I have tried changing the action="/Ejer2/Registro" to many other things like just /Registro orthe full http://... but still doesnt work.
This is my web.xml:
What can be the problem?
I guess you are missing servlet mapping in your web.xml. You need to register your servlet in web.xml (open web.xml file and at the bottom change tab to see actual source code not designer) add following code and you should be good to go
<servlet>
<servlet-name>RegistroServlet</servlet-name>
<servlet-class>Ejer2.Registro</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>RegistroServlet</servlet-name>
<url-pattern>/Registro</url-pattern>
</servlet-mapping>
I also suggest you to step back and start with basic java before attemping to write web application. You have several newbie issueses with your code:
1) name of packages should start with lower case !
2) also url mapping should be with lower case like this /registro
in your form action change url to match urlmapping. In your case it's
form action="/Registro" ...
Ejer2 is name of package it has nothing to do with url mapping. Hope it helps to resolve your problem

Connecting Mysql with IntelliJ ultimate 2016.2.3 using JSP [duplicate]

This question already has answers here:
Connect Java to a MySQL database
(14 answers)
Closed 6 years ago.
Am new in JSP and the IntelliJ IDE am experiencing an error java.lang.ClassNotFoundException: com.mysql.jdbc.Driver when i try to login inside my Application. Am using IntelliJ as my IDE while developing a JSP project. How can I connect Mysql to a JSP project?
Below is LoginDao.java class
package com.huza.schooldynamic;
/**
* Created by HUZY_KAMZ on 9/8/2016.
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoginDao {
public static boolean validate(String name, String pass) {
boolean status = false;
Connection conn = null;
PreparedStatement pst = null;
ResultSet rs = null;
String url = "jdbc:mysql://localhost:3306";
String dbName = "form";
String driver = "com.mysql.jdbc.Driver";
String userName = "root";
String password = "namungoona";
try {
Class.forName(driver).newInstance();
conn = DriverManager
.getConnection(url + dbName, userName, password);
pst = conn
.prepareStatement("select * from login where user=? and password=?");
pst.setString(1, name);
pst.setString(2, pass);
rs = pst.executeQuery();
status = rs.next();
} catch (Exception e) {
System.out.println(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (pst != null) {
try {
pst.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return status;
}
}
and this is my servlet class LoginServlet.java
package com.huza.schooldynamic;
/**
* Created by HUZY_KAMZ on 9/8/2016.
*/
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;
import javax.servlet.http.HttpSession;
public class LoginServlet extends HttpServlet{
private static final long serialVersionUID = 1L;
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String n=request.getParameter("username");
String p=request.getParameter("userpass");
HttpSession session = request.getSession(false);
if(session!=null)
session.setAttribute("name", n);
if(LoginDao.validate(n, p)){
RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
rd.forward(request,response);
}
else{
out.print("<p style=\"color:red\">Sorry username or password error</p>");
RequestDispatcher rd=request.getRequestDispatcher("index.jsp");
rd.include(request,response);
}
out.close();
}
}
This is my index.jsp file
<%--
Created by IntelliJ IDEA.
User: HUZY_KAMZ
Date: 9/8/2016
Time: 5:31 PM
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>School Management System</title>
</head>
<body>
<br>
<br>
<br>
<center>
<form action="loginServlet" method="post">
<fieldset style="width: 300px">
<legend> Login here </legend>
<table>
<tr>
<td>User ID</td>
<td><input type="text" name="username" required="required" /></td>
</tr>
<tr>
<td>Password</td>
<td><input type="password" name="userpass" required="required" /></td>
</tr>
<tr>
<td><input type="submit" value="Login" /></td>
</tr>
</table>
</fieldset>
</form>
</center>
</body>
</html>
This is my welcome.jsp file
<%--
Created by IntelliJ IDEA.
User: HUZY_KAMZ
Date: 9/8/2016
Time: 6:00 PM
To change this template use File | Settings | File Templates.
--%>
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Login successful!!!</h3>
<h4>
Hello,
<%=session.getAttribute("name")%></h4>
</body>
</html>
And finally this is my web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.huza.schooldynamic.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
So currently i have tried to view Mysql in the IntelliJ IDE but it seems i don't know how to connect it to the project , when i run the app and i try ti login this error comes in the IDE java.lang.ClassNotFoundException: com.mysql.jdbc.Driver.
Below is the picture of the IDE
The ClassNotFoundException is telling you that it cannot find the class com.mysql.jdbc.Driver on your classpath. In other words, non of the library JARs you have defined in your project contain that class.
That particular class is a MySQL specific implementations of the java.sql.Driver interface. (If you do not understand what an interface is, you can start wit the Java tutorial's page on it. But you'll want to do more learning about it since interfaces are a core concept of OOP).
Your DAO class says to use this particular diver in the line String driver = "com.mysql.jdbc.Driver";. But when the code is running, it is not finding a class by that name. So you need to add that class to your classpath. By going to Advance Search Page at the Maven Central, you can search for that (or any other) class to determine what libraries have it. In this particular case, it is in the mysql-connector-java JAR; the latest version of which is v6.0.4.
So yo need to add the mysql-connector-java JAR to your classpath , that is add it as a library to your Java project. How you do that depends on how you have set up your project.
If you are using Maven, you can add the required dependency:
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>6.0.4</version>
</dependency>
If you are using Gradle, add
compile 'mysql:mysql-connector-java:6.0.4'
If you are using Ant with Ivy, add
<dependency org="mysql" name="mysql-connector-java" rev="6.0.4" />
All those declarations I copied from the information page for that JAR file at maven central.
If you are not using one of the above build tools, you will need to add the JAR to your project in another way. For example, if you are just using the Project configuration in IDEA, go to Project Structure (Ctrl+Shift+Shift+S / ⌘;) and add it a new library to the module. See the Library IntelliJ IDEA help page and the pages it references for more information.

Http status 404 -/the requested resource is not available [duplicate]

This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 7 years ago.
I have written a servlet program for login page ..am using tomcat server...after i run on the server am getting the above mentioned error...
Below is my servlet code.
package demo;
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 javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class LoginServlet
*/
public class LoginServlet extends HttpServlet {
static private String dbUrl="jdbc:mysql://localhost:3306/employee";
static private String dbUn="root";
static private String dbPwd="root";
static private Connection ConObj;
static private Statement StmtObj;
static private ResultSet RsObj;
public void service(HttpServletRequest request,HttpServletResponse response)throws IOException
{
try {
Class.forName("com.mysql.jdbc.driver");
ConObj=DriverManager.getConnection(dbUrl, dbUn, dbPwd);
StmtObj=ConObj.createStatement();
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.write("<html><body>");
out.write("<h2>");
String ActLogName=request.getParameter("Logname");
String ActPwd=request.getParameter("Pwd");
String SqlQuery="select * from users where username='"+ActLogName+"' and password='"+ActPwd+"'";
RsObj=StmtObj.executeQuery(SqlQuery);
if(RsObj.next()==true)
{
String ExpLogName=RsObj.getString("username");
String ExpPwd=RsObj.getString("password");
if(ActLogName.equals(ExpLogName)&& ActPwd.equals(ExpPwd))
{
out.write("Login Success");
}
}
else
{
out.write("Login Failed");
}
out.write("</h2>");
out.write("</body></html>");
}
catch (ClassNotFoundException|SQLException exp) {
exp.printStackTrace();
}
finally{
try {
RsObj.close();
StmtObj.close();
ConObj.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
Below is my html code
<!DOCTYPE html>
<html>
<head>
<title>login page</title>
</head>
<body>
<form action="http://localhost:8080/FlipKart/loginpage">
LoginName :<input type="text" name="Logname"><br>
Password :<input type="password" name="Pwd"><br>
<input type="submit" value="Login">
<input type="button" value="cancel">
</form>
</body>
</html>
Below is my web.xml code
<web-app>
<servlet>
<servlet-name>loginserv</servlet-name>
<servlet-class>LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginserv</servlet-name>
<url-pattern>/loginpage</url-pattern>]
</servlet-mapping>
</web-app>
Can somebody help me to the resolve this issue..
Thanks in advance..:)
You are overriding the wrong method, override doPost() instead and modify your form to include method="post" like this :
public void doPost(HttpServletRequest request,HttpServletResponse response)throws IOException
{
//...
}
and this
<form action="http://localhost:8080/FlipKart/loginpage" method="post">
Also, if you don't want to always include the full path of the context manually, you can read this.
Did you restart the server after making the package name change? Tomcat reads web.xml only on startup.
Besides, make sure your classes are under webapps/WEB-INF/classes folder.
It looks to me as though your application context needs to be changed. Perhaps it is being set to root. So it is not hitting /FlipKart
Look at this stackoverflow link for more information on setting the application context.
That is for tomcat 7. I know you can edit the META-INF/context.xml for previous versions. If you don't have that folder and file just create it.
EDIT
Check your tomcat log to see where it is getting deployed or if something caused it to not get deployed at all. If you're running from an IDE, you may be able to see from the console.
Wrong reference to class in web.xml
Use full name of Class with package name
<servlet>
<servlet-name>loginserv</servlet-name>
<servlet-class>demo.LoginServlet</servlet-class>
</servlet>

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