This question already has answers here:
Servlet returns "HTTP Status 404 The requested resource (/servlet) is not available"
(19 answers)
Closed 6 years ago.
Iam calling servlet from html form,servlet takes the form data and it will insert that form data into database.But when i click the submit button error page is coming.please help whats wrong in my servlet code.
my servlet code:
import javax.servlet.http.HttpServlet;
import java.io.*;
import java.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class Loginservlet extends HttpServlet {
public void doPost(HttpServletRequest req,HttpServletResponse res) throws ServletException,IOException
{
System.out.println("login servlet");
String connectionURL = "jdbc:mysql://localhost:3306/mysql";
Connection connection=null;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
String username= req.getParameter("username");
String password = req.getParameter("password");
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(connectionURL, "root", "root");
String sql = "insert into signup values (?,?)";
PreparedStatement pst = connection.prepareStatement(sql);
pst.setString(1, username);
pst.setString(2, password);
int numRowsChanged = pst.executeUpdate();
out.println(" Data has been submitted ");
pst.close();
}
catch(ClassNotFoundException e){
out.println("Couldn't load database driver: "+ e.getMessage());
}
catch(SQLException e){
out.println("SQLException caught: " + e.getMessage());
}
catch (Exception e){
out.println(e);
}
finally {
try {
if (connection != null)
connection.close();
}
catch (SQLException ignored){
out.println(ignored);
}
}
}
}
my html code:
Sign Up
<form action="servlet/Loginservlet" method="post" >
<font size='5'>Create your Account:</font><br/><br>
<label for="username" accesskey="u" style="padding-left:3px;">User Name: </label>
<input type="text" style="background-color:#ffffff;margin-left:14px;padding-top:7px;border-width:0px;margin-top:6px;padding-right:85px;" id="username" name="username" tabindex="1"><br/><br>
<label for="password" accesskey="p" style="padding-left:4px;">Password: </label>
<input type="password" style="background-color:#ffffff;margin-left:14px;padding-top:7px;border-width:0px;padding-right:85px;" id="password" name="pasword" tabindex="2"><br/><br>
<input type="submit" value="Submit" style="margin-left:164px;"/>
<input type="reset" value="Reset" style="margin-left:17px;"/>
</form>
web.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>Loginservlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
please help
check web.xml file of your project, you have to registrate your servlet there.check this also
use <form action="/login" method="post" > in html
and
in web.xml
<servlet-class>your.class.package.Loginservlet</servlet-class>
</servlet>
As you look into your servlet class, there is no package defined, which is required. And map that class with package(mean fully qualified name) in <servlet-class/> tag.
Another thing is you are setting action to url servlet/LogininServlet, but given different url in <url-pattern/> tag, which is wrong. you can simply set the form action to login
everything is fine....in the html page use action="./login".........it will work i have done the same
Related
Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 5 years ago.
Improve this question
I am writing a program in java that validate users and if the logged in user was admin he can add another user from registeration form to the database. but when I am going to register someone and press register button it shows me this error.
Here is my code:
index.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Login Application</title>
</head>
<body>
<form action="loginServlet" method="post">
<fieldset style="width: 300px">
<legend> Login to App </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>
</body>
</html>
welcome.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Register form</h3>
<form method="post" action="Register.jsp">
Name:<input type="text" name="name" /><br/>
Password:<input type="text" name="pass" /><br/>
Email:<input type="text" name="email" /><br/>
<input type="submit" value="register" />
</form>
</body>
</html>
NewFile.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Welcome <%=session.getAttribute("name")%></title>
</head>
<body>
<h3>Login successful!!! user</h3>
<h4>
Hello,
<%=session.getAttribute("name")%></h4>
</body>
</html>
LoginCheck.java:
package com.example.saeid;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
public class LoginCheck {
static Boolean isadmin = false;
public static boolean validate(String name, int pass) {
boolean isValid = false;
Connection conn = null;
ResultSet rs = null;
String db_userName = "root";
String db_Password = "uyhgbv098";
String db_Name = "my_demo_database";
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost:3306/";
PreparedStatement ps = null;
try {
Class.forName(driver);
conn = DriverManager.getConnection(url+db_Name,db_userName,db_Password);
ps =conn.prepareStatement
("select * from user_account where username=? and password=?");
ps.setString(1, name);
ps.setInt(2, pass);
rs = ps.executeQuery();
if(rs.next()) {
isValid = true;
isadmin = rs.getBoolean("isadmin");
}
}catch (Exception e) {
System.out.println(e);
} finally {
if (conn != null) {
try {
conn.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (ps != null) {
try {
ps.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
return isValid;
}
public static Boolean admin(){
return isadmin;
}
}
loginservelet.java:
package com.example.saeid;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.PrintWriter;
import com.example.saeid.LoginCheck;
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");
int p2 = Integer.parseInt(p);
HttpSession session = request.getSession(false);
if(session!=null)
session.setAttribute("name", n);
if(LoginCheck.validate(n, p2)){
if(LoginCheck.admin()){
RequestDispatcher rd=request.getRequestDispatcher("welcome.jsp");
rd.forward(request,response);
}
else{
RequestDispatcher rd=request.getRequestDispatcher("NewFile.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();
}
}
register.java:
package com.example.saeid;
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String pass1 = request.getParameter("pass");
int pass = Integer.parseInt(pass1);
String email = request.getParameter("email");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
String db_userName = "root";
String db_Password = "uyhgbv098";
String url = "jdbc:mysql://localhost:3306/";
String db_Name = "my_demo_database";
Connection con=DriverManager.getConnection
(url+db_Name,db_userName,db_Password);
PreparedStatement ps=con.prepareStatement
("insert into user_acount values(?,?,?)");
ps.setString(1, name);
ps.setInt(2, pass);
ps.setString(3, email);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are successfully registered");
}
}
catch(Exception se)
{
se.printStackTrace();
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>FirstHomework</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>com.example.saeid.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/loginServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>com.example.saeid.Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/Register</url-pattern>
</servlet-mapping>
</web-app>
You have not given the fully qualified name of Register servlet in web.xml:-
</servlet-mapping>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>Register</servlet-class> // give the full path
</servlet>
and another thing is that you are storing the password as a String in register.java but when you run the query in Loginservelet you are setting the password as Int. Please prefer password as a String in both classes.
Just as Mayank Sharma said
First, in the web.xml file, you have to specify Register servlet's full path in the servlet-class tag same way you did for LoginServlet class.
Secondly, the value of your register servlet url-pattern tag should be the same value (excluding /) given to the action attribute of the form tag in your welcome.jsp page.
Lastly, take note of Mayank Sharma's second observation.
I must suggest you have to start learning how to develop java web applications using framework. It will help you a lot.
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.
I am new to servlets and jdbc.I just created a Registration page and a HTML registration form. I don't know why I am getting error like : HTTP Status 404 and description for this as The requested page is not available. Here is my servlet, html and .xml files. Please help me with this problem. I am using tomcat 7 and jdk8, in eclipse kepler.
public class Register extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
String Name = request.getParameter("Name");
String Email = request.getParameter("Email");
String Password = request.getParameter("Pass");
try {
Class.forName("oracle.jdbc.driver.DriverManager");
Connection conn = DriverManager.getConnection(
"jdbc:oracle:thin:#localhost:1521:orcl", "scott", "tiger");
PreparedStatement ps = conn
.prepareStatement("Insert into student values(?,?,?)");
ps.setString(1, Name);
ps.setString(2, Email);
ps.setString(3, Password);
int i = ps.executeUpdate();
if (i > 0) {
pw.println("Registered Successfully");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
My Html code.
<body>
<form method="post" action="register">
Name : <input type="text" name="Name"><br/>
Email :<input type="text" name="Email"><br/>
Password :<input type="password" name="Pass"><br/>
<input type="submit" value="register"/>
</form>
and my web.xml file
<?xml version="1.0" encoding="UTF-8"?>
<web-app >
<display-name>SimpleServlet</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>register</servlet-name>
<url-pattern>/register</url-pattern>
</servlet-mapping>
</web-app>
I am able to hit servlet code using http://localhost:8080/MyWebapp/register.
In my case,Register servlet is in default package.
If your Register servlet is in a package,then in your web.xml,specify class name with package like this.
<servlet>
<servlet-name>register</servlet-name>
<servlet-class>your.package.Register</servlet-class>
</servlet>
This is my database
CREATE TABLE `Animal` ( `name` varchar(128) NOT NULL, `breed` varchar(128) NOT NULL, `age` varchar(128) NOT NULL )
register.html to fill in the data
<html>
<body>
<form action="servlet/Register" method="post">
name <input type="text" name="name"/><br/><br/>
breed <input type="password" name="breed"/><br/><br/>
age <input type="password" name="age"/><br/><br/>
<br/><br/>
<input type="submit" value="register"/>
</form>
</body>
</html>
My servlet
package animals;
import java.io.*;
import java.sql.*;
import javax.servlet.ServletException;
import javax.servlet.http.*;
public class Register extends HttpServlet {
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String name = request.getParameter("name");
String breed = request.getParameter("breed");
String age = request.getParameter("age");
try {
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/test", "root", "");
PreparedStatement ps = con.prepareStatement(
"INSERT INTO Animal (name,breed,age) VALUES(?,?,?)");
ps.setString(1, name);
ps.setString(2, breed);
ps.setString(3, age);
int i = ps.executeUpdate();
if (i > 0) {
out.print("Data successfully registered...");
}
} catch (Exception e2) {
System.out.println(e2);
}
out.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>Register</servlet-name>
<servlet-class>animals.Register</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Register</servlet-name>
<url-pattern>/servlet/Register</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>register.html</welcome-file>
</welcome-file-list>
</web-app>
When I fill in the form and submit, it send me to /register but it's blank and it doesn't add data in my database.
I'm 100% sure that my connection to the java database is working, because I have another project with a login with the same connection to the database and that one is working.
Any tips / comments are welcome
Few things you can check :
1. Debug the code & check if values are captured by the servlet.
2. Use commit() after the executeUpdate(). Maybe your config is set to auto-commit off due to some reasons.
3. Is this string printed? "Data successfully registered..."
4. Lastly, Any exceptions?
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();
}
}