Connecting Mysql with IntelliJ ultimate 2016.2.3 using JSP [duplicate] - java

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.

Related

Why isn't this code working? HTTP Status 404 – Not Found on jsp and servlet [closed]

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.

Simple authentication using Servlet and Mysql

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.

Adding a MySQL driver library to a NetBeans project

I'm pretty much new to Java EE programming, and I'm supposed to do some exercises (to finish my school pretty soon) about it.
My problem might be very simple, but I haven't found an answer whatsoever.
In one exercise, I'm supposed to be able to log in to a java/jsp/mysql-type of service.
Login.htm
<html>
<head>
<title>Login</title>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link rel="stylesheet" href="css/style.css" />
</head>
<body>
<h3>Login</h3>
<form name="login" method="post" action="ServletLogin">
<table>
<tr>
<td>Email:</td>
<td><input name="email" type="text" id="email"></td>
</tr>
<tr>
<td>Salasana</td>
<td><input name="password" type="password" id="password"></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" name="Submit" value="Log in;">
</td>
</tr>
</table>
</form>
</body>
</html>
Pretty standard login, yes. When passing the form, it should go to a ServletLogin.java to initiate the login-sequence.
Instead I'm getting this from Glassfish:
HTTP Status 500 - Internal Server Error
type Exception report
messageInternal Server Error
descriptionThe server encountered an internal error that prevented it from fulfilling this request.
exception
java.lang.NullPointerException
note The full stack traces of the exception and its root causes are available in the GlassFish Server Open Source Edition 4.1 logs.
GlassFish Server Open Source Edition 4.1
In the ServletLogin.java, our tutor has left a note that the whole project should include a MySQL driver library to avoid NullPointerException.
My question is, how do I do that with Netbeans? Netbeans tells me I already have on installed, but apparently it either isn't or it doesn't work.
Here is ServletLogin.java code:
/*
* Remember to install a MYSQL driver library
* or the file will alert
* NullPointerException.
*/
package Servlets; //the package in which the Servlet is part of.
import java.io.*;
import java.sql.*;
import javax.servlet.*;
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;
#WebServlet(name = "ServletLogin", urlPatterns = {"/ServletLogin"})
public class ServletLogin extends HttpServlet {
Connection conn = null;
/**
* Initializes the servlet.
*/
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
//Connect to database with database-class
try {
conn = Classes.SQL.openConnection();
}
catch (Exception e) {
System.out.println("Cannot connect to database " + e);
}
}
/**
* Destroys the servlet.
*/
#Override
public void destroy() {
//Closing the database connection
try {
conn.close();
} catch ( SQLException se ) {
System.out.println("Exception " + se);
}
}
//Everything is done in doPost method.
//This Servlet does not use doGet() or ProcessRequest()
/**
* Handles the HTTP <code>POST</code> method.
* #param request servlet request
* #param response servlet response
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
PrintWriter out = response.getWriter();
/*Unless there is a session, one is created.
It is used to check if the user has logged in.*/
HttpSession session = request.getSession(true);
//Reading the parameters from login form.
String email = request.getParameter("email");
String password = request.getParameter("password");
out.print(email);
//Created login_ok and set it to false by default.
boolean login_ok = false;
try {
//let's create a Statement with which the sql can be run with.
Statement stmt = conn.createStatement();
//Run SQL and save it to ResultSet rs.
ResultSet rs = stmt.executeQuery("SELECT email, password FROM clients");
//Go trough the results with while loop and next-method, which returns the value true, until we've reached last result.
while(rs.next())
{
//Reading the data
String email2 = rs.getString("email");
String salasana2 = rs.getString("password);
//If user input has been found from database,
//login_ok becomes true and looping ends.
if(email.compareTo(email2) == 0 && password.compareTo(password2) == 0)
{
login_ok = true;
break;
}
}
//If login_ok is true, save info about logging to session and guide the user to Clients.jsp
if( login_ok == true )
{
//session is informed about login
session.setAttribute("login", "ok");
//Debugging printed to console.
System.out.println("Login ok");
//Proceeding to clients
response.sendRedirect("clients.jsp");
//Return stops the servlet run.
return;
}
//Login false -> redirected to login page.
else {
response.sendRedirect("login.htm");
}
}
catch(SQLException se){
out.println("Error: " + se);
}
out.close();
}
}
Am I missing something, like in imports or?
I've installed mysql-connector-java-5.1.23-bin.jar and set it into multiple different places, with same result. All I need now is to be able to even see if the code works, but NullPointerException prevents me from doing so.
Adding the mysql-connector-java-5.1.23-bin.jar through Project Properties -> Libraries on Netbeans 8.0.2 doesn't seem to solve it, either.
Registered MySQL to GlassFish, still goes for NullPointerException.
Go to Services Tab
Select Databases
Right click and select Register MYSQL driver
Right Click libraries in project and select MYSQL from add Libraries

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

Calling servlet from HTML form, but servlet is never invoked [duplicate]

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

Categories

Resources