07planning Good Java
07planning Good Java
All Tutorials
Java
o Java Basic
o Advanced Java
o Eclipse Technology
SWT
Eclipse RCP
Eclipse RAP
Eclipse Plugin Tools
o Java API for HTML & XML
o Java Open source libraries
o Java Application Servers
Maven
Gradle
Servlet/Jsp
Thymeleaf
Spring
o Spring Boot
o Spring Cloud
Struts2
Hibernate
Java Web Service
JavaFX
SWT
Oracle ADF
Android
Python
Swift
C#
C/C++
Ruby
Batch
Database
o Oracle
o MySQL
o SQL Server
o PostgreSQL
o Other Databases
Oracle APEX
Report
Client
ECMAScript / Javascript
NodeJS
ReactJS
AngularJS
HTML
CSS
Bootstrap
OS
o Ubuntu
o Solaris
o Mac OS
Git
SAP
Others
o Uncategorized
o Software
o VirtualBox
o VmWare
Table Of Content
1- Introduction
2- The principle when programming Servlet + JSP
3- View Demo of Web Application will do
4- Prepare database
5- Create WebApp Project
6- Configuring the runtime environment
7- Run application for first time
8- Download and declare JDBC library
9- Download and declare JSTL library
10- Javabean classes simulated tables in the database
11- Database Connection Utility classes
12- The utility class & manipulate data
13- Create Servlet Filter connect to Database
14- Servlet Filter reads Cookies to automatically login
15- EncodingFilter Servlet
16- Pages reuse
17- Home Page
18- Login Page - LoginServlet
19- Product List Page
20- Add Product Page
21- Edit Product Page
22- Delete Product
Java Servlet/Jsp Tutorials
1- Introduction
This document is based on:
Eclipse 4.5 MARS
Tomcat 8.x
In this document, I will guide step by step how to create a simple web application with
the combiantion of Servlet + JSP + Filter + JSP EL + JDBC. Make sure that you've
mastered Servlet, JSP and Filter and JDBC before the start. If not, you can refer to:
Servlet:
Java Servlet Tutorial for Beginners
Servlet Filter:
Java Servlet Filter
JSP:
Java JSP Tutorial for Beginners
JSP Standard Tag Libs (JSTL)
Java JSP Standard Tag Library (JSTL)
JDBC
Java JDBC
NOTE: In this post I only introduce about CRUD, "Login" and "Remember
Me" function. And do not handle the security of the pages. If you want to have an
application, secure each page, please refer to the article below:
Create a simple Login application and secure pages with Java Servlet
Filter
2- The principle when programming Servlet + JSP
These are the principles that you should keep in mind to be able to build a Web
application using Servlet + JSP satisfying criteria: code is simple, easy to understand
and easy to maintain.
The principles:
1. Never allow users to directly access to your JSP page.
2. JSP is only considered as the place to display interface.
3. Servlet acts as the controller of the application flows and program logical
processing.
4. Open the JDBC connection and transaction management in Filter (Optional).
According to the principle 1:
Never allow users to directly access to your JSP page, it means that all user's requests are:
Another source of static data (images, css, js, ...)
Or a servlet.
Therefore, you must hide your JSP files in a place where the user can not access. For
instance, set it in the WEB-INF folder or its subdirectories. In this example, I hide the jsp
files in the WEB-INF/views.
When the user requests to a Servlet, it will dispose user's requirements, such insert,
update and query the data, eventually forward to the JSP page to display the data. Thus,
each servlet has 0 or multiple corresponding JSP pages (Usually only need 1).
Principle 2:
JSP is only considered as the place to display data, which means that you should not
handle the application logic on the JSP, such as update, insert, delete, .., and not navigate
on the JSP page.
3- View Demo of Web Application will do
You can preview Demo Web application will do:
4- Prepare database
In this document, I instruct you to work with one of 3 databases: Oracle, MySQL or
SQL Server. You need to run scripts to create some tables and necessary data for this
example.
ORACLE:
-- Create table
create table USER_ACCOUNT
(
USER_NAME VARCHAR2(30) not null,
GENDER VARCHAR2(1) not null,
PASSWORD VARCHAR2(30) not null,
primary key (USER_NAME)
);
-- Create table
create table PRODUCT
(
CODE VARCHAR2(20) not null,
NAME VARCHAR2(128) not null,
PRICE FLOAT not null,
primary key (CODE)
) ;
-- Insert data:
---------------------------------------------------------------
-- Commit
Commit;
MYSQL:
-- Create table
create table USER_ACCOUNT
(
USER_NAME VARCHAR(30) not null,
GENDER VARCHAR(1) not null,
PASSWORD VARCHAR(30) not null,
primary key (USER_NAME)
);
-- Create table
create table PRODUCT
(
CODE VARCHAR(20) not null,
NAME VARCHAR(128) not null,
PRICE FLOAT not null,
primary key (CODE)
) ;
-- Insert data:
---------------------------------------------------------------
-- Create table
create table PRODUCT
(
CODE VARCHAR(20) not null,
NAME VARCHAR(128) not null,
PRICE FLOAT not null,
primary key (CODE)
) ;
-- Insert data:
---------------------------------------------------------------
index.html
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Simple Web Application</title>
</head>
<body>
<ul>
<li><a href="home">Home</a></li>
<li><a href="login">Login</a></li>
<li><a href="productList">Product List</a>
</ul>
</body>
</html>
6- Configuring the runtime environment
The application needs to run on a WebServer, such as Tomcat Server, you can refer
to download and declaration instructions of Server Tomcat in Eclipse at:
Installing and Configuring Tomcat Server in Eclipse
Right-click the SimpleWebApp select Properties.
7- Run application for first time
Right-click on SimpleWebApp, select:
Run As/Run on Server
Application has been run:
OK, here everything is fine. We'll start programming a real Web application.
8- Download and declare JDBC library
You have to download JDBC library to driving the connection with the Database. In this
document, I download both of 3 JDBC libraries for Oracle, MySQL, SQL Server, in
practice, you only need JDBC library corresponding to the type of database you are
using.
You can see download instruction of JDBC driver at:
JDBC Driver Libraries for different types of database in Java
Or download here:
some-jdbc-drivers.zip (MySQL + SQL Server + Oracle) o7planning link.
Results downloaded:
http://mvnrepository.com/artifact/javax.servlet.jsp.jstl/javax.servlet.jsp.jstl-api
Copy 2 jar files that you just downloaded into the / WEB-INF/lib:
10- Javabean classes simulated tables in the database
Create 2 JavaBean classes, wherein each class simulated a table in the database:
UserAccount.java
package org.o7planning.simplewebapp.beans;
public class UserAccount {
public UserAccount() {
}
Product.java
package org.o7planning.simplewebapp.beans;
public Product() {
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Class.forName("com.mysql.jdbc.Driver");
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
Class.forName("oracle.jdbc.driver.OracleDriver");
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
// Connect to SQLServer
// (Using JDBC Driver of JTDS library)
public static Connection getSQLServerConnection_JTDS() //
throws SQLException, ClassNotFoundException {
Class.forName("net.sourceforge.jtds.jdbc.Driver");
// Example:
//
jdbc:jtds:sqlserver://localhost:1433/simplehr;instance=SQLEXPRESS
String connectionURL = "jdbc:jtds:sqlserver://" + hostName +
":1433/" //
+ database + ";instance=" + sqlInstanceName;
}
SQLServerConnUtils_SQLJDBC.java
package org.o7planning.simplewebapp.conn;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
return getSQLServerConnection_SQLJDBC(hostName,
sqlInstanceName, database, userName, password);
}
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
// Example:
//
jdbc:sqlserver://ServerIp:1433/SQLEXPRESS;databaseName=simplehr
String connectionURL = "jdbc:sqlserver://" + hostName +
":1433" //
+ ";instance=" + sqlInstanceName +
";databaseName=" + database;
}
ConnectionUtils.java
package org.o7planning.simplewebapp.conn;
import java.sql.Connection;
import java.sql.SQLException;
// return OracleConnUtils.getOracleConnection();
// return MySQLConnUtils.getMySQLConnection();
// return
SQLServerConnUtils_JTDS.getSQLServerConnection_JTDS();
// return
SQLServerConnUtils_SQLJDBC.getSQLServerConnection_SQLJDBC();
// return PostGresConnUtils.getPostGresConnection();
}
import java.sql.Connection;
import javax.servlet.ServletRequest;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.o7planning.simplewebapp.beans.UserAccount;
// Get the Connection object that has been stored in attribute of the
request.
public static Connection getStoredConnection(ServletRequest request) {
Connection conn =
(Connection)request.getAttribute(ATT_NAME_CONNECTION);
return conn;
}
// Delete cookie.
public static void deleteUserCookie(HttpServletResponse response) {
Cookie cookieUserName = new Cookie(ATT_NAME_USER_NAME, null);
// 0 seconds (This cookie will expire immediately)
cookieUserName.setMaxAge(0);
response.addCookie(cookieUserName);
}
}
DBUtils.java
package org.o7planning.simplewebapp.utils;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import org.o7planning.simplewebapp.beans.Product;
import org.o7planning.simplewebapp.beans.UserAccount;
if (rs.next()) {
String gender = rs.getString("Gender");
UserAccount user = new UserAccount();
user.setUserName(userName);
user.setPassword(password);
user.setGender(gender);
return user;
}
return null;
}
ResultSet rs = pstm.executeQuery();
if (rs.next()) {
String password = rs.getString("Password");
String gender = rs.getString("Gender");
UserAccount user = new UserAccount();
user.setUserName(userName);
user.setPassword(password);
user.setGender(gender);
return user;
}
return null;
}
public static List<Product> queryProduct(Connection conn) throws
SQLException {
String sql = "Select a.Code, a.Name, a.Price from Product a ";
ResultSet rs = pstm.executeQuery();
List<Product> list = new ArrayList<Product>();
while (rs.next()) {
String code = rs.getString("Code");
String name = rs.getString("Name");
float price = rs.getFloat("Price");
Product product = new Product();
product.setCode(code);
product.setName(name);
product.setPrice(price);
list.add(product);
}
return list;
}
ResultSet rs = pstm.executeQuery();
while (rs.next()) {
String name = rs.getString("Name");
float price = rs.getFloat("Price");
Product product = new Product(code, name, price);
return product;
}
return null;
}
pstm.setString(1, product.getName());
pstm.setFloat(2, product.getPrice());
pstm.setString(3, product.getCode());
pstm.executeUpdate();
}
pstm.setString(1, product.getCode());
pstm.setString(2, product.getName());
pstm.setFloat(3, product.getPrice());
pstm.executeUpdate();
}
pstm.setString(1, code);
pstm.executeUpdate();
}
import java.io.IOException;
import java.sql.Connection;
import java.util.Collection;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import org.o7planning.simplewebapp.conn.ConnectionUtils;
import org.o7planning.simplewebapp.utils.MyUtils;
public JDBCFilter() {
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
@Override
public void destroy() {
// Key: servletName.
// Value: ServletRegistration
Map<String, ? extends ServletRegistration>
servletRegistrations = request.getServletContext()
.getServletRegistrations();
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.o7planning.simplewebapp.beans.UserAccount;
import org.o7planning.simplewebapp.utils.DBUtils;
import org.o7planning.simplewebapp.utils.MyUtils;
public CookieFilter() {
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
@Override
public void destroy() {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
HttpServletRequest req = (HttpServletRequest) request;
HttpSession session = req.getSession();
chain.doFilter(request, response);
}
}
NOTE:
JDBCFilter & CookieFilter have the same url-pattern =/*, you must be
configured to ensure that JDBCFilter is executed first. Therefore, you need to
declare the order in web.xml (There is no way to declare the order by Annotation).
<filter-mapping>
<filter-name>jdbcFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>cookieFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
See full web.xml:
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-
app_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>SimpleWebApp</display-name>
<filter-mapping>
<filter-name>jdbcFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>cookieFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>home</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
import java.io.IOException;
import java.sql.Connection;
import java.util.Collection;
import java.util.Map;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import org.o7planning.simplewebapp.conn.ConnectionUtils;
import org.o7planning.simplewebapp.utils.MyUtils;
public EncodingFilter() {
}
@Override
public void init(FilterConfig fConfig) throws ServletException {
@Override
public void destroy() {
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding("UTF-8");
chain.doFilter(request, response);
}
</div>
</div>
</body>
</html>
/WEB-INF/views/_menu.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
PageEncoding="UTF-8"%>
<a href="${pageContext.request.contextPath}/">Home</a>
|
<a href="${pageContext.request.contextPath}/productList">Product
List</a>
|
<a href="${pageContext.request.contextPath}/userInfo">My Account
Info</a>
|
<a href="${pageContext.request.contextPath}/login">Login</a>
</div>
/WEB-INF/views/_footer.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<div
style="background: #E0E0E0; text-align: center; padding: 5px; margin-
top: 10px;">
@Copyright o7planning.org
</div>
<filter-mapping>
<filter-name>jdbcFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<filter-mapping>
<filter-name>cookieFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>home</welcome-file>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
</web-app>
Models of Home Page:
HomeServlet.java
package org.o7planning.simplewebapp.servlet;
import java.io.IOException;
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;
@WebServlet(urlPatterns = { "/home"})
public class HomeServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public HomeServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
// Forward to /WEB-INF/views/homeView.jsp
// (Users can not access directly into JSP pages placed in WEB-
INF)
RequestDispatcher dispatcher =
this.getServletContext().getRequestDispatcher("/WEB-
INF/views/homeView.jsp");
dispatcher.forward(request, response);
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doGet(request, response);
}
}
/WEB-INF/views/homeView.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Home Page</title>
</head>
<body>
<jsp:include page="_header.jsp"></jsp:include>
<jsp:include page="_menu.jsp"></jsp:include>
<h3>Home Page</h3>
<jsp:include page="_footer.jsp"></jsp:include>
</body>
</html>
Rerun your application, and try two URLs:
http://localhost:8081/SimpleWebApp/
http://localhost:8081/SimpleWebApp/home
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.o7planning.simplewebapp.beans.UserAccount;
import org.o7planning.simplewebapp.utils.DBUtils;
import org.o7planning.simplewebapp.utils.MyUtils;
@WebServlet(urlPatterns = { "/login" })
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
// Forward to /WEB-INF/views/loginView.jsp
// (Users can not access directly into JSP pages placed in
WEB-INF)
RequestDispatcher dispatcher //
=
this.getServletContext().getRequestDispatcher("/WEB-
INF/views/loginView.jsp");
dispatcher.forward(request, response);
// When the user enters userName & password, and click Submit.
// This method will be executed.
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
String userName = request.getParameter("userName");
String password = request.getParameter("password");
String rememberMeStr = request.getParameter("rememberMe");
boolean remember = "Y".equals(rememberMeStr);
if (user == null) {
hasError = true;
errorString = "User Name or password
invalid";
}
} catch (SQLException e) {
e.printStackTrace();
hasError = true;
errorString = e.getMessage();
}
}
// If error, forward to /WEB-INF/views/login.jsp
if (hasError) {
user = new UserAccount();
user.setUserName(userName);
user.setPassword(password);
// Forward to /WEB-INF/views/login.jsp
RequestDispatcher dispatcher //
=
this.getServletContext().getRequestDispatcher("/WEB-
INF/views/loginView.jsp");
dispatcher.forward(request, response);
}
// If no error
// Store user information in Session
// And redirect to userInfo page.
else {
HttpSession session = request.getSession();
MyUtils.storeLoginedUser(session, user);
}
UserInfoServlet.java
package org.o7planning.simplewebapp.servlet;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.o7planning.simplewebapp.beans.UserAccount;
import org.o7planning.simplewebapp.utils.MyUtils;
@WebServlet(urlPatterns = { "/userInfo" })
public class UserInfoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public UserInfoServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
HttpSession session = request.getSession();
// Not logged in
if (loginedUser == null) {
// Redirect to login page.
response.sendRedirect(request.getContextPath() +
"/login");
return;
}
// Store info to the request attribute before forwarding.
request.setAttribute("user", loginedUser);
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doGet(request, response);
}
}
/WEB-INF/views/loginView.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Login</title>
</head>
<body>
<jsp:include page="_header.jsp"></jsp:include>
<jsp:include page="_menu.jsp"></jsp:include>
<h3>Login Page</h3>
<p style="color: red;">${errorString}</p>
<jsp:include page="_footer.jsp"></jsp:include>
</body>
</html>
/WEB-INF/views/userInfoView.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>User Info</title>
</head>
<body>
<jsp:include page="_header.jsp"></jsp:include>
<jsp:include page="_menu.jsp"></jsp:include>
<h3>Hello: ${user.userName}</h3>
<jsp:include page="_footer.jsp"></jsp:include>
</body>
</html>
Running your application:
http://localhost:8080/SimpleWebApp/login
19- Product List Page
Model:
ProductListServlet.java
package org.o7planning.simplewebapp.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
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 org.o7planning.simplewebapp.beans.Product;
import org.o7planning.simplewebapp.utils.DBUtils;
import org.o7planning.simplewebapp.utils.MyUtils;
@WebServlet(urlPatterns = { "/productList" })
public class ProductListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public ProductListServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
Connection conn = MyUtils.getStoredConnection(request);
String errorString = null;
List<Product> list = null;
try {
list = DBUtils.queryProduct(conn);
} catch (SQLException e) {
e.printStackTrace();
errorString = e.getMessage();
}
// Store info in request attribute, before forward to views
request.setAttribute("errorString", errorString);
request.setAttribute("productList", list);
// Forward to /WEB-INF/views/productListView.jsp
RequestDispatcher dispatcher = request.getServletContext()
.getRequestDispatcher("/WEB-
INF/views/productListView.jsp");
dispatcher.forward(request, response);
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doGet(request, response);
}
}
/WEB-INF/views/productListView.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Product List</title>
</head>
<body>
<jsp:include page="_header.jsp"></jsp:include>
<jsp:include page="_menu.jsp"></jsp:include>
<h3>Product List</h3>
<jsp:include page="_footer.jsp"></jsp:include>
</body>
</html>
Rerun Application:
http://localhost:8080/SimpleWebApp/productList
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.o7planning.simplewebapp.beans.Product;
import org.o7planning.simplewebapp.utils.DBUtils;
import org.o7planning.simplewebapp.utils.MyUtils;
@WebServlet(urlPatterns = { "/createProduct" })
public class CreateProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public CreateProductServlet() {
super();
}
// When the user enters the product information, and click Submit.
// This method will be called.
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
Connection conn = MyUtils.getStoredConnection(request);
if (errorString == null) {
try {
DBUtils.insertProduct(conn, product);
} catch (SQLException e) {
e.printStackTrace();
errorString = e.getMessage();
}
}
}
/WEB-INF/views/createProductView.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Create Product</title>
</head>
<body>
<jsp:include page="_header.jsp"></jsp:include>
<jsp:include page="_menu.jsp"></jsp:include>
<h3>Create Product</h3>
</body>
</html>
http://localhost:8080/SimpleWebApp/createProduct
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.o7planning.simplewebapp.beans.Product;
import org.o7planning.simplewebapp.utils.DBUtils;
import org.o7planning.simplewebapp.utils.MyUtils;
@WebServlet(urlPatterns = { "/editProduct" })
public class EditProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public EditProductServlet() {
super();
}
try {
product = DBUtils.findProduct(conn, code);
} catch (SQLException e) {
e.printStackTrace();
errorString = e.getMessage();
}
// If no error.
// The product does not exist to edit.
// Redirect to productList page.
if (errorString != null && product == null) {
response.sendRedirect(request.getServletPath() +
"/productList");
return;
}
// After the user modifies the product information, and click Submit.
// This method will be executed.
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
Connection conn = MyUtils.getStoredConnection(request);
try {
DBUtils.updateProduct(conn, product);
} catch (SQLException e) {
e.printStackTrace();
errorString = e.getMessage();
}
// Store infomation to request attribute, before forward to
views.
request.setAttribute("errorString", errorString);
request.setAttribute("product", product);
}
/WEB-INF/views/editProductView.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Edit Product</title>
</head>
<body>
<jsp:include page="_header.jsp"></jsp:include>
<jsp:include page="_menu.jsp"></jsp:include>
<h3>Edit Product</h3>
<jsp:include page="_footer.jsp"></jsp:include>
</body>
</html>
DeleteProductServlet.java
package org.o7planning.simplewebapp.servlet;
import java.io.IOException;
import java.sql.Connection;
import java.sql.SQLException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.o7planning.simplewebapp.utils.DBUtils;
import org.o7planning.simplewebapp.utils.MyUtils;
@WebServlet(urlPatterns = { "/deleteProduct" })
public class DeleteProductServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public DeleteProductServlet() {
super();
}
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
Connection conn = MyUtils.getStoredConnection(request);
try {
DBUtils.deleteProduct(conn, code);
} catch (SQLException e) {
e.printStackTrace();
errorString = e.getMessage();
}
}
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse
response)
throws ServletException, IOException {
doGet(request, response);
}
}
/WEB-INF/views/deleteProductErrorView.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Delete Product</title>
</head>
<body>
<jsp:include page="_header.jsp"></jsp:include>
<jsp:include page="_menu.jsp"></jsp:include>
<h3>Delete Product</h3>
<jsp:include page="_footer.jsp"></jsp:include>
</body>
</html>
View more Tutorials:
Java Servlet/Jsp Tutorials
report this ad
Java Servlet/Jsp Tutorials
Installing and Configuring Tomcat Server in Eclipse
Installing and configuring Glassfish Web Server
Installing and configuring Oracle WebLogic Server
Java Servlet Tutorial for Beginners
Java Servlet Filter
Java JSP Tutorial for Beginners
Java JSP Standard Tag Library (JSTL)
Install Web Tools Platform into Eclipse
Create a simple Login application and secure pages with Java Servlet Filter
Create a Simple Java Web Application Using Servlet, JSP and JDBC
Uploading and downloading files stored to hard drive with Java Servlet
Uploading and downloading files from Database using Java Servlet
Displaying Image from Database with Java Servlet
Redirect 301 Permanent redirect in Java Servlet
How to automatically redirect http to https in a Java Web application?
Using Google reCAPTCHA with Java Web Application
Run Maven Java Web Application in Tomcat Maven Plugin
Run Maven Java Web Application in Jetty Maven Plugin
Run background task in Java Servlet Application
report this ad
Newest Documents
Understanding Generic Family Names in CSS
The keywords min-content, max-content, fit-content, stretch in CSS
CSS @font-face
CSS Backgrounds
CSS Cursors
Bootstrap Grid System
CSS Float and Clear
CSS visibility
HTML Col, Colgroup
CSS Fonts
report this ad
report this ad
o7planning.org