I have taken reference from ->
https://www.quora.com/How-can-I-make-my-first-JSP-page-using-MySQL-database
At first jsp file is opening , i can input data but after clicking at submit , it gives error as in the image provided.
i m using tomcat v7.0 and it works correct for all other projects !
code->
Login.jsp file
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Register form</title>
</head>
<body>
<form method="post" action="register">
Name:<input type="text" name="name" /><br/>
Email ID:<input type="text" name="email" /><br/>
Password:<input type="text" name="pass" /><br/>
<input type="submit" value="register" />
</form>
</body>
</html>
Register.java file
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.*;
public class Register extends HttpServlet {
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 email = request.getParameter("email");
String pass = request.getParameter("pass");
try{
//loading drivers for mysql
Class.forName("com.mysql.jdbc.Driver");
//creating connection with the database
Connection con=DriverManager.getConnection
("jdbc:mysql:/
/localhost:3306/test","username","password");
PreparedStatement ps=con.prepareStatement
("insert into Student values(?,?,?)");
ps.setString(1, name);
ps.setString(2, email);
ps.setString(3, pass);
int i=ps.executeUpdate();
if(i>0)
{
out.println("You are sucessfully registered");
}else{
out.println("Invalid User");
}
}
catch(Exception se)
{
se.printStackTrace();
}
}
}
You forgot to add web.xml as in tutorial the servlet
<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>
Related
I am writing a JSP and Servlet project to register a user using their name, surname and password in Eclipse. When I enter the values in the webpage everything is ok, but when i check the database afterwards, the table values are not being updated(the table is still empty). Tomcat webserver was used. The code segments for MVC files used are as follows:
UserDAO.java
'''
public int registerUser(Users users) throws ClassNotFoundException{
String query = "INSERT INTO users" + "(id, name, surname, password) VALUES" + "(?, ?, ?, ?);"; int result = 0;
Class.forName("com.mysql.jdbc.Driver");
try (Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/churchdb","root","");
//Step 2:Create a statement using connection object
PreparedStatement stmt = con.prepareStatement(query)){
stmt.setInt(1, 1);
stmt.setString(2, users.getUserName());
stmt.setString(3,users.getSurname());
stmt.setString(4, users.getPassword());
System.out.println(stmt);
//Step 3: Execute the query or update query
result = stmt.executeUpdate();
}
catch(SQLException e){
//process sql exception
e.printStackTrace();
}
return result;
}
'''
UserServlet.java
'''
private UserDAO userDao = new UserDAO();
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws
ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/userregistration.jsp");
dispatcher.forward(request, response);
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String userName = request.getParameter("userName");
String surname = request.getParameter("surname");
String password = request.getParameter("password");
Users users = new Users();
users.setUserName(userName);
users.setSurname(surname);
users.setPassword(password);
try{
userDao.registerUser(users);
}catch(ClassNotFoundException e){
e.printStackTrace();
}
RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/views/userdetails.jsp");
dispatcher.forward(request, response);
}
}
'''
Userregistration.php
'''
<%# 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>Register</title>
<link href="bootstrap/css/bootstrap.css" rel="stylesheet" type="text/css"/>
<link href="bootstrap/css/bootstrap.min.css" rel="stylesheet" type="text/css"/>
</head>
<body>
<div align="center">
<h1>User Registration form</h1>>
<form action="<%= request.getContextPath() %>/register" method="post">
<table style="with: 80%">
<tr>
<td>Name</td>
<td><input type="text" name="userName" /></td>
</tr>
<tr>
<td>Surname</td>
<td><input type="text" name="surname"/></td>
</tr>
<tr>
<td>Password</td>
<td><input type="text" name=password/></td>
</tr>
</table>
<input type="submit" value="Submit" />
</form>
</div>
</body>
</html>
'''
NB: There is also javabean file
i want to add person in database using ibatis in j2EE application.
I have a table person in mySQL, servlet,SqlMapConfix.xml,Person.xml and Person.java.
i did many tests but i had the same error.
java.lang.RuntimeException: Error occurred. Cause: com.ibatis.common.xml.NodeletException: Error parsing XML. Cause: java.lang.RuntimeException: Error parsing XPath '/sqlMapConfig/sqlMap'. Cause: java.io.IOException: Could not find resource config/Person.xml
here the code :
index.html
<html>
<head>
<title>TODO supply a title</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width">
</head>
<body>
<form action="Controller" >
<input type="text" name="nom">
<input type="text" name="pren">
<input type="submit" value="ok">
</form>
</body>
servlet: Controller.java
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
String a = request.getParameter("nom");
String b = request.getParameter("pren");
try{
Reader rd;
rd = Resources.getResourceAsReader("config/SqlMapConfig.xml");
SqlMapClient smc;
smc = SqlMapClientBuilder.buildSqlMapClient(rd);
out.println("Going to insert record.....");
Person em = new Person(a, b);
smc.insert("Person.insert", em);
out.println("Record Inserted Successfully ");
}catch(SQLException e)
{e.printStackTrace();}
}
Person.java
package controleur;
public class Person {
String nom,prenom;
public Person(String nom, String prenom) {
this.nom = nom;
this.prenom = prenom;
}
public String getNom() {
return nom;
}
public void setNom(String nom) {
this.nom = nom;
}
public String getPrenom() {
return prenom;
}
public void setPrenom(String prenom) {
this.prenom = prenom;
}
}
Person.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMap PUBLIC "-//ibis.apache.org//DTD SQL Map 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-2.dtd">
<sqlMap namespace="Person">
<insert id="insert" parameterClass="controleur.Person" >
insert into person(nom, pren)values(#nom#, #prenom#)
</insert>
</sqlMap>
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE sqlMapConfig
PUBLIC "-//ibatis.apache.org//DTD SQL Map Config 2.0//EN" "http://ibatis.apache.org/dtd/sql-map-config-2.dtd">
<settings useStatementNamespaces="true"></settings>
<transactionManager type="JDBC">
<dataSource type="simple">
<property name="JDBC.Driver" value="com.mysql.jdbc.Driver"/>
<property name="JDBC.ConnectionURL" value="jdbc:mysql://localhost:3306/parc"/>
<property name="JDBC.Username" value="root"/>
<property name="JDBC.Password" value=""/>
</dataSource>
</transactionManager>
<sqlMap resource="config/Person.xml "/>
i used two package: package config contains *.xml files and package controleur contains the servlet and the java class.
thanks
Moved the xml file to where the Pojo was located, in your example move it under controleur package where Person.java is located then update the sqlMap as follows.
<sqlMap resource="controleur/Person.xml" />
I'm trying to insert an image in a MySQL database using Servlet and JSP in Tomcat 7. When I click on the save button, it displays null. I am not getting any errors.
Also I set commons-fileupload.jar file and commons-io.jar file. If you have some demonstration code, please give me.
<%# 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>File Upload to Database Demo</title>
</head>
<body>
<center>
<h1>File Upload to Database Demo</h1>
<form method="post" action="FileUploadDBServlet" enctype="multipart/form-data">
<table border="0">
<tr>
<td>First Name: </td>
<td><input type="text" name="firstName" size="50"/></td>
</tr>
<tr>
<td>Last Name: </td>
<td><input type="text" name="lastName" size="50"/></td>
</tr>
<tr>
<td>Portrait Photo: </td>
<td><input type="file" name="photo" size="50"/></td>
</tr>
<tr>
<td colspan="2">
<input type="submit" value="Save">
</td>
</tr>
</table
</form>
</center>
</body>
</html>
FileUploadDBServlet.java:
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet("/FileUploadDBServlet")
#MultipartConfig(maxFileSize = 16177215) // upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {
// database connection settings
private String dbURL = "jdbc:mysql://localhost:3306/AppDB";
private String dbUser = "root";
private String dbPass = "root";
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// gets values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
// obtains input stream of the upload file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
conn = DriverManager.getConnection(dbURL,dbUser,dbPass);
String sql =("INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)");
PreparedStatement statement = conn.prepareStatement(sql);
statement.setString(1, firstName);
statement.setString(2, lastName);
if (inputStream != null) {
// fetches input stream of the upload file for the blob column
statement.setBlob(3, inputStream);
}
// sends the statement to the database server
int row = statement.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
} catch (Exception ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
ex.printStackTrace();
}
}
// sets the message in request scope
request.setAttribute("Message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp").forward(request, response);
}
}
}
web.xml:
<web-app>
<servlet>
<servlet-name>FileUploadDBServlet</servlet-name>
<servlet-class>FileUploadDBServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadDBServlet</servlet-name>
<url-pattern>/FileUploadDBServlet</url-pattern>
</servlet-mapping>
</web-app>
The following code explains how to store/retrieve an image to/from db.
First create a table in your db using following code
CREATE TABLE contacts (
contact_id int PRIMARY KEY AUTO_INCREMENT,
first_name varchar(45) DEFAULT NULL,
last_name varchar(45) DEFAULT NULL,
photo` mediumblob);
Create a jsp file for input parameters.
Upload.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>File Upload to Database</title>
</head>
<body>
<h1>File Upload to Database</h1>
<form name="fileform" method="post" action="uploadServlet" enctype="multipart/form-data">
<label for="firstName">First Name:</label>
<input type="text" name="firstName" size="50" placeholder="Enter Your FirstName" required/><br><br>
<label for="lastName">Last Name: </label>
<input type="text" name="lastName" size="50" placeholder="Enter Your LastName" required/><br><br>
<label for="photo"> Portrait Photo: </label>
<input type="file" name="photo" size="50" placeholder="Upload Your Image" required/><br><br>
<input type="submit" value="Save">
</form>
</body>
</html>
Next create controller for uploading image. In this case, I'm using a servlet.
FileUploadDbServlet.java:
package com.fileupload.attach;
import java.io.IOException;
import java.io.InputStream;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.sql.Blob;
import java.sql.ResultSet;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#MultipartConfig(maxFileSize = 16177215)
// upload file's size up to 16MB
public class FileUploadDBServlet extends HttpServlet {
private static final int BUFFER_SIZE = 4096;
// database connection settings
private String dbURL = "jdbc:mysql://localhost:3306/mysql";
private String dbUser = "root";
private String dbPass = "arun";
//naive way to obtain a connection to database
//this MUST be improved, shown for
private Connection getConnection() {
Connection conn = null;
try {
DriverManager.registerDriver(new com.mysql.jdbc.Driver());
conn = DriverManager.getConnection(dbURL, dbUser, dbPass);
} catch (Exception e) {
//wrapping any exception and rethrowing it
//inside a RuntimeException
//so the method is silent to exceptions
throw new RuntimeException("Failed to obtain database connection.", e);
}
return conn;
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
//get values of text fields
String firstName = request.getParameter("firstName");
String lastName = request.getParameter("lastName");
InputStream inputStream = null; // input stream of the upload file
// obtains the upload file part in this multipart request
Part filePart = request.getPart("photo");
if (filePart != null) {
// prints out some information for debugging
System.out.println(filePart.getName());
System.out.println(filePart.getSize());
System.out.println(filePart.getContentType());
//obtains input stream of the upload file
//the InputStream will point to a stream that contains
//the contents of the file
inputStream = filePart.getInputStream();
}
Connection conn = null; // connection to the database
String message = null; // message will be sent back to client
try {
// connects to the database
conn = getConnection();
// constructs SQL statement
String sql = "INSERT INTO contacts (first_name, last_name, photo) values (?, ?, ?)";
//Using a PreparedStatement to save the file
PreparedStatement pstmtSave = conn.prepareStatement(sql);
pstmtSave.setString(1, firstName);
pstmtSave.setString(2, lastName);
if (inputStream != null) {
//files are treated as BLOB objects in database
//here we're letting the JDBC driver
//create a blob object based on the
//input stream that contains the data of the file
pstmtSave.setBlob(3, inputStream);
}
//sends the statement to the database server
int row = pstmtSave.executeUpdate();
if (row > 0) {
message = "File uploaded and saved into database";
}
String filepath = "D:/Dev/JavaWorkSpaceNew/FileUploadDatabase/WebContent/FromDb.jpg";
//Obtaining the file from database
//Using a second statement
String sql1 = "SELECT photo FROM contacts WHERE first_name=? AND last_name=?";
PreparedStatement pstmtSelect = conn.prepareStatement(sql1);
pstmtSelect.setString(1, firstName);
pstmtSelect.setString(2, lastName);
ResultSet result = pstmtSelect.executeQuery();
if (result.next()) {
Blob blob = result.getBlob("photo");
InputStream inputStream1 = blob.getBinaryStream();
OutputStream outputStream = new FileOutputStream(filepath);
int bytesRead = -1;
byte[] buffer = new byte[BUFFER_SIZE];
while ((bytesRead = inputStream1.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
inputStream1.close();
outputStream.close();
System.out.println("File saved");
}
} catch (SQLException ex) {
message = "ERROR: " + ex.getMessage();
ex.printStackTrace();
} finally {
if (conn != null) {
// closes the database connection
try {
conn.close();
} catch (SQLException ex) {
//silent
}
}
// sets the message in request scope
request.setAttribute("message", message);
// forwards to the message page
getServletContext().getRequestDispatcher("/Message.jsp")
.include(request, response);
}
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app>
<display-name>servletFileUpload</display-name>
<welcome-file-list>
<welcome-file>Upload.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>FileUploadDBServlet</display-name>
<servlet-name>FileUploadDBServlet</servlet-name>
<servlet-class>com.fileupload.attach.FileUploadDBServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FileUploadDBServlet</servlet-name>
<url-pattern>/uploadServlet</url-pattern>
</servlet-mapping>
</web-app>
Message.jsp:
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Message</title>
</head>
<body>
<h3>Result of the operation: ${message}</h3>
</body>
</html>
Jsp Page
Save this page with any name
<%#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>
<form action="abc" method="post" enctype="multipart/form-data"> <br><br>
<table>
<tr>
<td>UserName: </td>
<td width='10px'></td>
<td><input type="text" name="name"/></td>
</tr>
<tr>
<td>Upload: </td>
<td width='10px'></td>
<td><input type="file" name="file" value="Upload"/></td>
</tr>
<tr>
<td><input type="submit" value="submit"></td>
</tr>
</table>
</form>
</body>
</html>
Servlet page and save this page as abc.java
source code
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
#WebServlet(urlPatterns = {"/abc"})
#MultipartConfig(fileSizeThreshold = 1024 * 1024 * 10, maxFileSize = 1024 * 1024 * 50, maxRequestSize = 1024 * 1024 * 100)
public class abc extends HttpServlet {
// this if directory name where the file will be uploaded and saved
private static final String SAVE_DIR = "images";
// this is the method which is created by system it self
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
// this tyr is created by me for the connection of database
try {
// this is the path provide by me to save the image
String savePath = "C:" + File.separator + SAVE_DIR;
/*in place of C: you can place a path wher you need to save the image*/
// this comment will picup the image file and have convert it into file type
File fileSaveDir = new File(savePath);
if (!fileSaveDir.exists()) {
fileSaveDir.mkdir();
}
// this two comment will take the name and image form web page
String name = request.getParameter("name");
Part part = request.getPart("file");
// this comment will extract the file name of image
String fileName = extractFileName(part);
// this will print the image name and user provide name
out.println(fileName);
out.println("\n" + name);
/*if you may have more than one files with same name then you can calculate
some random characters and append that characters in fileName so that it will
make your each image name identical.*/
part.write(savePath + File.separator + fileName);
/*
You need this loop if you submitted more than one file
for (Part part : request.getParts()) {
String fileName = extractFileName(part);
part.write(savePath + File.separator + fileName);
}*/
// connectio to database
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection("url", "host -name", "password");
// query to insert name and image name
String query = "INSERT INTO image_link (name,photourl) values (?, ?)";
PreparedStatement pst;
pst = con.prepareStatement(query);
pst.setString(1, name);
String filePath = savePath + File.separator + fileName;
pst.setString(2, filePath);
pst.executeUpdate();
} catch (Exception ex) {
out.println("error" + ex);
}
}
}
// the extractFileName() is method used to extract the file name
private String extractFileName(Part part) {
String contentDisp = part.getHeader("content-disposition");
String[] items = contentDisp.split(";");
for (String s : items) {
if (s.trim().startsWith("filename")) {
return s.substring(s.indexOf("=") + 2, s.length() - 1);
}
}
return "";
}
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
This question already has an answer here:
Authentication filter and servlet for login
(1 answer)
Closed 7 years ago.
I have created a simple login page in which user will give an username and password. After clicking on submit button it will show welcome user. But it is not giving any result
This is my index page
This is my index login page :
<%# 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">
<link rel="stylesheet" type="text/css" href="style.css"/>
<title>Login</title>
</head>
<body>
<%
String error_msg = "";
Object error = request.getAttribute("error");
if (error != null) error_msg = error.toString();
%>
<div id="Container">
<div id="Header">
<h1>Online File Management System</h1>
</div>
Home
<div id="Content">
<div id="Login">
<form action="login">
<table align = "center" bgcolor=#66CCFF>
<tr><td align = "left">Username: </td>
<td rowspan="7" valign="middle">
<font color="red"> <%= error_msg %> </font>
<p>You can also Login using Google</p>
<p class="Google"><input name="Submit" type="Submit" value="Login with Google Account"></p>
</td>
</tr>
<tr>
<td><input name="username" type="text" size="30"></td>
<td></td>
</tr>
<tr><td align = "left">Password:</td></tr>
<tr><td><input name="password" type="password" size="30"></td></tr>
<tr><td align = "left">Forgot your password?</td></tr>
<tr><td align = "left">Remember me <input type="checkbox" name="checkbox" value="checkbox"></td></tr>
<tr><td align = "left"><input type="Submit" value="LOGIN"></td></tr>
</table>
</form>
<hr>
</div>
</div>
<div id="Footer">
Copyright © 2014 Office of the Vice Chancellor.
</div>
</div>
</body>
</html>
This is my Database conectivity page :
package org.form.login;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import org.apache.catalina.connector.Request;
public class database {
#SuppressWarnings("null")
public String validateUserLogin (String username, String password) throws SQLException{
Connection connection = null;
ResultSet resultset = null;
Statement statement = null;
String fullname = "";
String DRIVER = "com.mysql.jdbc.Driver";
String URL = "jdbc:mysql://localhost:3306/onfms";
String USER = "root";
String PASS = "";
String QUERY = "SELECT * FROM tblUser WHERE fldUser_Name = '"+
username+"' AND fldPassword = '"+password+"' ";
try {
Class.forName(DRIVER);
connection = DriverManager.getConnection(URL,USER,PASS);
resultset = statement.executeQuery(QUERY);
} catch (Exception e){
e.printStackTrace();
} finally {
if (resultset != null)
resultset.close();
if (statement != null)
statement.close();
if (connection != null)
connection.close();
}
}
}
This is my login servlet page:
package org.form.login;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.form.login.database;
/**
* Servlet implementation class login
*/
#WebServlet("/login")
public class login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public login() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String url = "/main.jsp";
String user = request.getParameter("username");
String pass = request.getParameter("password");
if (user == null || user.length() == 0 ||pass == null || pass.length() == 0) {
url = "/index.jsp";
request.setAttribute("error", "Username & Password must not be empty.");
}else{
try {
String fullname = new database().validateUserLogin(user, pass);
request.setAttribute("fullname", fullname);
if (fullname != null || fullname.length() != 0){
request.setAttribute("sucess", "Sucessfull Connection");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
ServletContext context = getServletContext();
RequestDispatcher dispatcher = context.getRequestDispatcher(url);
dispatcher.forward(request, response);
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
This is my final Page where I display my result
<%# 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>Desk Board</title>
</head>
<body>
Hello
<%
String sucess_message ="";
Object sucess = request.getAttribute("sucess");
if (sucess != null ) sucess_message = sucess.toString();
%>
<%= sucess_message %>
</body>
</html>
use this code it is working
// index.jsp or login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>
</body>
</html>
// authentication servlet class
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
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;
public class auth extends HttpServlet {
private static final long serialVersionUID = 1L;
public auth() {
super();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
try {
Class.forName("com.mysql.jdbc.Driver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
String username = request.getParameter("username");
String pass = request.getParameter("pass");
String sql = "select * from reg where username='" + username + "'";
Connection conn = null;
try {
conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
"root", "");
Statement s = conn.createStatement();
java.sql.ResultSet rs = s.executeQuery(sql);
String un = null;
String pw = null;
String name = null;
/* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */
PrintWriter prwr1 = response.getWriter();
if(!rs.isBeforeFirst()){
prwr1.write("<h1> No Such User in Database<h1>");
} else {
/* Conditions to be executed after at least one row is returned by query execution */
while (rs.next()) {
un = rs.getString("username");
pw = rs.getString("password");
name = rs.getString("name");
}
PrintWriter pww = response.getWriter();
if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
// use this or create request dispatcher
response.setContentType("text/html");
pww.write("<h1>Welcome, " + name + "</h1>");
} else {
pww.write("wrong username or password\n");
}
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
You Can simply Use One Jsp Page To accomplish the task.
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>JSP Page</title>
</head>
<body>
<%
String username=request.getParameter("user_name");
String password=request.getParameter("password");
String role=request.getParameter("role");
try
{
Class.forName("com.mysql.jdbc.Driver");
Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
Statement st=con.createStatement();
String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
ResultSet rs=st.executeQuery(query);
while(rs.next())
{
session.setAttribute( "user_name",rs.getString(2));
session.setMaxInactiveInterval(3000);
response.sendRedirect("homepage.jsp");
}
%>
<%}
catch(Exception e)
{
out.println(e);
}
%>
</body>
I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.
I tried to create a simple login form which takes username&password,checks with the mysql database table.Pardon me I'm a beginner to this java stuff...If its matches its re-directed to home page.But i can't execute it.can somebody help me out with this.Thanks for the quick reply.The tomcat error i'm getting is The requested resource (/UserDemo/firstserv) is not available.And i know there are more errors in it.Thats y i'm posting it here....help me out....
SerExam.java
package myPack;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.*;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletConfig;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SerExam extends HttpServlet
{
Connection con;
PreparedStatement ps;
ResultSet rs;
public void init(ServletConfig config)throws ServletException
{
try
{
Class.forName("oracle.jdbc.driver.OracleDriver");
con=DriverManager.getConnection("jdbc:oracle:thin:#localhost:1521:xe","system","tiger");
}
catch (ClassNotFoundException e)
{
System.out.println(e);
}
catch (SQLException e)
{
System.out.println(e);
}
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
doPost(request, response);
{
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
String username=request.getParameter("username");
String password=request.getParameter("password");
pw.println("<html><body>");
try
{
ps=con.prepareStatement("select * from loginvalidation where username=? and password=?");
ps.setString(1, username);
ps.setString(2, password);
rs=ps.executeQuery();
if(rs.next())
{
pw.println("<h3>welcome " +" " + username +"</h3>");
RequestDispatcher rd1=request.getRequestDispatcher("./home.html");
rd1.include(request,response);
//or
//response.sendRedirect("./home.html");
pw.println("<form method=\"post\" action=\"Login.html\">");
pw.println("<input type=\"submit\" name=\"logout\" " + "value=\"Logout\">");
pw.println("</form>");
}
else
{
pw.println("<center><h3>invalid username/password Enter Correct username/password</h3></center>");
RequestDispatcher rd2=request.getRequestDispatcher("./Login.html");
rd2.include(request,response);
//or
//response.sendRedirect("./Login.html");
}
}
catch (SQLException e)
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
}
}
login.html
<!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>Login page</title>
</head>
<body>
<center>
<form action="./firstserv" method="post">
username
<input type="text" name="username" />
<br>
<br>
password
<input type="password" name="password"></input><br><br>
<input type="submit" value="login"></input>
new user
</form>
</center>
</body>
</html>
reg.html
<!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>Registration Form</title>
</head>
<body>
registration page under construction...............
</body>
</html>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
<display-name>UserDemo</display-name>
<servlet>
<description>
</description>
<display-name>SerExam</display-name>
<servlet-name>SerExam</servlet-name>
<servlet-class>
myPack.SerExam</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>SerExam</servlet-name>
<url-pattern>/home.html</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
Change your servlet mapping tag as
<servlet-mapping>
<servlet-name>SerExam</servlet-name>
<url-pattern>/MyServlet</url-pattern>
</servlet-mapping>
And then you can use MyServlet as the action parameter of your form so that the request with the form parameters is sent to you servlet SerExam as per above servlet mapping.
<form action="MyServlet" method="post">
and as you are using POST method inside form then your servlets doPost method will be called and I can see from your code that you have not written any code inside your doPost method.
Remove that doPost(request,response); (that is the first line inside your doGet method.
So change your servlet code as :
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
//your existing code inside doGet with that doPost call removed
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException{
doGet(request,response);
}
Still there are many things you will require to be done before your code works well.
So I would request you to look at our Servlet wiki so that you can get the basic understanding.
Your servlet is mapped to /home.html:
<servlet-mapping>
<servlet-name>SerExam</servlet-name>
<url-pattern>/home.html</url-pattern>
</servlet-mapping>
while you are accessing firstserv:
<form action="./firstserv" method="post">
Side note:
Never, ever store passwords in plain text in your database:
ps=con.prepareStatement("select * from loginvalidation where username=? and password=?");
ps.setString(1, username);
ps.setString(2, password);