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
Related
I am try to search my database using jstl tags but it is not working.
So far what I manage is to make it display a null message.
I am very new to this side of java, so please if you have any suggestion try to explain in details.
Thanks
Image Description
My codes are as follows:
user-list.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/fmt" prefix="fmt"%>
<%# taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>
<%# page isELIgnored="false"%>
<html>
<head>
<title>User Management Application</title>
<link rel="stylesheet"
href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css"
integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T"
crossorigin="anonymous">
</head>
<sql:setDataSource var="snapshot" driver="com.mysql.jdbc.Driver"
url="jdbc:mysql://localhost:3306/dbname2?allowPublicKeyRetrieval=true&useSSL=false"
user="root" password="root"/>
<body>
<header>
<nav class="navbar navbar-expand-md navbar-dark"
style="background-color: tomato">
<div>
<a href="" class="navbar-brand"> User
Management App </a>
</div>
<ul class="navbar-nav">
<li><a href="<%=request.getContextPath()%>/list"
class="nav-link">Users</a></li>
</ul>
</nav>
</header>
<br>
<div class="row">
<!-- <div class="alert alert-success" *ngIf='message'>{{message}}</div> -->
<div class="container">
<h3 class="text-center">List of Users</h3>
<hr>
<div class="container text-left">
<a href="<%=request.getContextPath()%>/new" class="btn btn-success">Add
New User</a>
</div>
<form name="userForm" action="user-list.jsp" method="post">
<div class="container text-center">
<input type="text" class="form-group" name="search" value="<%=request.getParameter("id")%>" placeholder="Name" style="width: 400px;">
<INPUT TYPE ="submit">
</div>
</form>
<br>
<table class="table table-bordered">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Date</th>
<th>Time</th>
<th>Email</th>
<th>Country</th>
<th>Actions</th>
</tr>
</thead>
<tbody>
<sql:query var="user" dataSource="${snapshot}">
select *from users where
id like '%<%=request.getParameter("id")%>%'
</sql:query>
<c:forEach var="user" items="${listUser}">
<tr>
<td><c:out value="${user.id}" /></td>
<td><c:out value="${user.name}" /></td>
<td><c:out value="${user.date}" /></td>
<td><c:out value="${user.time}" /></td>
<td><c:out value="${user.email}" /></td>
<td><c:out value="${user.country}" /></td>
<td>Edit
Delete</td>
</tr>
</c:forEach>
<!-- } -->
</tbody>
</table>
</div>
</div>
UserDAO class
package com.project.usermanagement.dao;
import java.sql.Connection;
import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Time;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.ArrayList;
import java.util.List;
import com.project.usermanagement.model.User;
public class UserDAO {
public static Date getSQLDate(LocalDate date) {
return java.sql.Date.valueOf(date);
}
public static LocalDate getUtilDate(Date sqlDate) {
return sqlDate.toLocalDate();
}
public static Time getSQLTime(LocalTime time) {
return java.sql.Time.valueOf(time);
}
public static LocalTime getUtilTime(Time sqlTime) {
return sqlTime.toLocalTime();
}
private String jdbcURL = "jdbc:mysql://localhost:3306/dbname2?allowPublicKeyRetrieval=true&useSSL=false";
private String jdbcUsername = "root";
private String jdbcPassword = "root";
private static final String INSERT_USERS_SQL = "INSERT INTO users" + " (name, date ,time ,email , country) VALUES " +
" (?, ?, ?, ?, ?);";
private static final String SELECT_USER_BY_ID = "select id,name, date, time, email,country from users where id =?";
private static final String SELECT_ALL_USERS = "select * from users";
private static final String DELETE_USERS_SQL = "delete from users where id = ?;";
private static final String UPDATE_USERS_SQL = "update users set name = ?, date=?, time=?, email= ?, country =? where id = ?;";
public UserDAO() {}
protected Connection getConnection() {
Connection connection = null;
try {
Class.forName("com.mysql.jdbc.Driver");
connection = DriverManager.getConnection(jdbcURL, jdbcUsername, jdbcPassword);
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return connection;
}
public void insertUser(User user) throws SQLException {
System.out.println(INSERT_USERS_SQL);
// try-with-resource statement will auto close the connection.
try (Connection connection = getConnection(); PreparedStatement preparedStatement = connection.prepareStatement(INSERT_USERS_SQL)) {
preparedStatement.setString(1, user.getName());
preparedStatement.setDate(2, getSQLDate(user.getDate()));
preparedStatement.setTime(3, getSQLTime(user.getTime()));
preparedStatement.setString(4, user.getEmail());
preparedStatement.setString(5, user.getCountry());
System.out.println(preparedStatement);
preparedStatement.executeUpdate();
} catch (SQLException e) {
printSQLException(e);
}
}
public User selectUser(int id) {
User user = null;
// Step 1: Establishing a Connection
try (Connection connection = getConnection();
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(SELECT_USER_BY_ID);) {
preparedStatement.setInt(1, id);
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
ResultSet rs = preparedStatement.executeQuery();
// Step 4: Process the ResultSet object.
while (rs.next()) {
String name = rs.getString("name");
LocalDate date = rs.getDate("date").toLocalDate();
LocalTime time = rs.getTime("time").toLocalTime();
String email = rs.getString("email");
String country = rs.getString("country");
user = new User(id, name, date, time , email, country);
}
} catch (SQLException e) {
printSQLException(e);
}
return user;
}
public List < User > selectAllUsers() {
// using try-with-resources to avoid closing resources (boiler plate code)
List < User > users = new ArrayList < > ();
// Step 1: Establishing a Connection
try (Connection connection = getConnection();
// Step 2:Create a statement using connection object
PreparedStatement preparedStatement = connection.prepareStatement(SELECT_ALL_USERS);) {
System.out.println(preparedStatement);
// Step 3: Execute the query or update query
ResultSet rs = preparedStatement.executeQuery();
// Step 4: Process the ResultSet object.
while (rs.next()) {
int id = rs.getInt("id");
String name = rs.getString("name");
LocalDate date = rs.getDate("date").toLocalDate();
LocalTime time = rs.getTime("time").toLocalTime();
String email = rs.getString("email");
String country = rs.getString("country");
users.add(new User(id, name, date, time, email, country));
}
} catch (SQLException e) {
printSQLException(e);
}
return users;
}
public boolean deleteUser(int id) throws SQLException {
boolean rowDeleted;
try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(DELETE_USERS_SQL);) {
statement.setInt(1, id);
rowDeleted = statement.executeUpdate() > 0;
}
return rowDeleted;
}
public boolean updateUser(User user) throws SQLException {
boolean rowUpdated;
try (Connection connection = getConnection(); PreparedStatement statement = connection.prepareStatement(UPDATE_USERS_SQL);) {
statement.setString(1, user.getName());
statement.setDate(2, getSQLDate(user.getDate()));
statement.setTime(3, getSQLTime(user.getTime()));
statement.setString(4, user.getEmail());
statement.setString(5, user.getCountry());
statement.setInt(6, user.getId());
rowUpdated = statement.executeUpdate() > 0;
}
return rowUpdated;
}
private void printSQLException(SQLException ex) {
for (Throwable e: ex) {
if (e instanceof SQLException) {
e.printStackTrace(System.err);
System.err.println("SQLState: " + ((SQLException) e).getSQLState());
System.err.println("Error Code: " + ((SQLException) e).getErrorCode());
System.err.println("Message: " + e.getMessage());
Throwable t = ex.getCause();
while (t != null) {
System.out.println("Cause: " + t);
t = t.getCause();
}
}
}
}
}
UserServlet class
package com.project.usermanagement.web;
import java.io.IOException;
import java.sql.SQLException;
import java.time.LocalDate;
import java.time.LocalTime;
import java.util.List;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.project.usermanagement.dao.UserDAO;
import com.project.usermanagement.model.User;
#WebServlet("/")
public class UserServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
private UserDAO userDAO;
public void init() {
userDAO = new UserDAO();
}
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getServletPath();
try {
switch (action) {
case "/new":
showNewForm(request, response);
break;
case "/insert":
insertUser(request, response);
break;
case "/delete":
deleteUser(request, response);
break;
case "/edit":
showEditForm(request, response);
break;
case "/update":
updateUser(request, response);
break;
default:
listUser(request, response);
break;
}
} catch (SQLException ex) {
throw new ServletException(ex);
}
}
private void listUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException, ServletException {
List < User > listUser = userDAO.selectAllUsers();
request.setAttribute("listUser", listUser);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-list.jsp");
dispatcher.forward(request, response);
}
private void showNewForm(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
dispatcher.forward(request, response);
}
private void showEditForm(HttpServletRequest request, HttpServletResponse response)
throws SQLException, ServletException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
User existingUser = userDAO.selectUser(id);
RequestDispatcher dispatcher = request.getRequestDispatcher("user-form.jsp");
request.setAttribute("user", existingUser);
dispatcher.forward(request, response);
}
private void insertUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
String name = request.getParameter("name");
String email = request.getParameter("email");
String country = request.getParameter("country");
User newUser = new User(name, LocalDate.now(), LocalTime.now(), email, country);
userDAO.insertUser(newUser);
response.sendRedirect("list");
}
private void updateUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
LocalDate date = LocalDate.parse(request.getParameter("date"));
LocalTime time = LocalTime.parse(request.getParameter("time"));
String email = request.getParameter("email");
String country = request.getParameter("country");
User book = new User(id, name, date, time, email, country);
userDAO.updateUser(book);
response.sendRedirect("list");
}
private void deleteUser(HttpServletRequest request, HttpServletResponse response)
throws SQLException, IOException {
int id = Integer.parseInt(request.getParameter("id"));
userDAO.deleteUser(id);
response.sendRedirect("list");
}
}
You can send value to be search using form .Then , get that value using ${param.yourinputname} and pass same to your query .Currently , you have incorrect input name i.e : name="search" but you are getting same using id which will return null as you can see in your added output as well .So, your form like below :
<form name="userForm" action="user-list.jsp" method="post">
<!--change value-->
<input type="text" class="form-group" name="search" value="${param.search}" placeholder="Name" style="width: 400px;">
<input type ="submit">
</form>
Now , when form will get submitted get that the value which is typed by user and pass same to your query . i.e :
<sql:query var="user" dataSource="${snapshot}">
select *from users where id LIKE '%' ? '%'
<sql:param value="${param.search}" />
</sql:query>
And get result from query using below code :
<c:forEach var="listUser" items="${user.rows}">
<tr>
<td><c:out value="${listUser.id}" /></td>
<td><c:out value="${listUser.name}" /></td>
<!--same for other fields as well-->
</tr>
</c:forEach>
trying to display data from server in the page in a table. but unfortunately it is not working. I can display it using out.println. Code samples are attached. Thank you very much.
ajax1 handles the ajax part and ajax2 is the file for java code.
...
Ajax1.jsp
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
<script>
$(document).ready(function(){
$("#users").change(function(){
var value = $(this).val();
$.get("ajax2.jsp",{q:value},function(data){
$("#javaquery").html(data);
});
});
});
</script>
</head>
<body>
<select id = "users">
<option value="">Select Account ID</option>
<option value="calicut">calicut</option>
<option value="kochi">kochi</option>
<option value="Admin">Admin</option>
</select>
<br />
<div id="javaquery"><b>Name will be displayed here</b></div>
</body>
</html>
Ajax2.jsp
<%#page import="java.text.SimpleDateFormat"%>
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.util.*,java.sql.*,java.io.*" %>
<%#page import="javax.servlet.*" %>
<%#page import="javax.servlet.http.*" %>
<%# page import="java.sql.*" %>
<%# page import="java.util.*" %>
<%# page import="java.io.*" %>
<%# page import="javax.sql.*" %>
<%# page import="javax.naming.*,javax.swing.*,java.sql.Date.*,java.text.SimpleDateFormat.*,java.util.Date.*" %>
<html> <head> <meta http-equiv="Content-Type"
content="text/html; charset=UTF-8"> <title></title> </head>
<body>
<%
InitialContext ctx;
DataSource ds;
Connection conn;
ResultSet rs;
Statement stmt;
String name = "";
String ename="";
try {
ctx=new InitialContext();
ds=(DataSource) ctx.lookup("java:app/jdbc/SalesDB");
conn=ds.getConnection();
String q = request.getParameter("q");
stmt = conn.createStatement(); //Create Statement to interact
rs = stmt.executeQuery("select * from employees where Username='"+q+"'");
while (rs.next()) {
name = rs.getString("Role_")+rs.getString("username");
ename=rs.getString("username");
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
%>
Name:<%out.print(name);%>
eName:<%out.print(ename);%>
</body> </html>
.............................................
.................................................
<script>
$(document).ready(function(){
$("#users").change(function(){
var value = $(this).val();
$.get("AjaxServlet",{q:value},function(data){
$("#javaquery").html(data);
});
});
});
</script>
Remove java code from 2nd jsp and add it to a servlet called "AjaxServlet" with url mapping "/AjaxServlet"
AjaxServlet:
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String q = request.getParameter("q"); //q value
InitialContext ctx;
DataSource ds;
Connection conn;
ResultSet rs;
Statement stmt;
String name = "blank name";
String ename="";
try {
ctx=new InitialContext();
ds=(DataSource) ctx.lookup("java:app/jdbc/SalesDB");
conn=ds.getConnection();
String q = request.getParameter("q");
stmt = conn.createStatement(); //Create Statement to interact
rs = stmt.executeQuery("select * from employees where Username='"+q+"'");
while (rs.next()) {
name = rs.getString("Role_")+rs.getString("username");
ename=rs.getString("username");
}
rs.close();
stmt.close();
conn.close();
} catch (Exception e) {
e.printStackTrace();
}
response.setContentType("text/plain"); // Set content type of the response so that jQuery knows what it can expect.
response.setCharacterEncoding("UTF-8"); // You want world domination, huh?
response.getWriter().write(name); // Write response body.
}
More info on how to do ajax with servlets here:
How to use Servlets and Ajax?
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>
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.