Link:
Create a Simple Java Web Application Using Servlet, JSP and JDBC
View more categories:
- 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
-

-
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:
-
Servlet Filter:
-
JSP:
-
JSP Standard Tag Libs (JSTL)
-
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:
-
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:
-
- Never allow users to directly access to your JSP page.
- JSP is only considered as the place to display interface.
- Servlet acts as the controller of the application flows and program logical processing.
- 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.
-

-
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:
-
12345678910111213141516171819202122232425262728293031323334
-- Create tablecreatetableUSER_ACCOUNT(USER_NAME VARCHAR2(30)notnull,GENDER VARCHAR2(1)notnull,PASSWORDVARCHAR2(30)notnull,primarykey(USER_NAME));-- Create tablecreatetablePRODUCT(CODE VARCHAR2(20)notnull,NAMEVARCHAR2(128)notnull,PRICEFLOATnotnull,primarykey(CODE)) ;-- Insert data: ---------------------------------------------------------------insertintouser_account (USER_NAME, GENDER,PASSWORD)values('tom','M','tom001');insertintouser_account (USER_NAME, GENDER,PASSWORD)values('jerry','M','jerry001');insertintoproduct (CODE,NAME, PRICE)values('P001','Java Core', 100);insertintoproduct (CODE,NAME, PRICE)values('P002','C# Core', 90);-- CommitCommit; -
MYSQL:
-
12345678910111213141516171819202122232425262728293031
-- Create tablecreatetableUSER_ACCOUNT(USER_NAMEVARCHAR(30)notnull,GENDERVARCHAR(1)notnull,PASSWORDVARCHAR(30)notnull,primarykey(USER_NAME));-- Create tablecreatetablePRODUCT(CODEVARCHAR(20)notnull,NAMEVARCHAR(128)notnull,PRICEFLOATnotnull,primarykey(CODE)) ;-- Insert data: ---------------------------------------------------------------insertintouser_account (USER_NAME, GENDER,PASSWORD)values('tom','M','tom001');insertintouser_account (USER_NAME, GENDER,PASSWORD)values('jerry','M','jerry001');insertintoproduct (CODE,NAME, PRICE)values('P001','Java Core', 100);insertintoproduct (CODE,NAME, PRICE)values('P002','C# Core', 90); -
SQL SERVER:
-
12345678910111213141516171819202122232425262728293031
-- Create tablecreatetableUSER_ACCOUNT(USER_NAMEVARCHAR(30)notnull,GENDERVARCHAR(1)notnull,PASSWORDVARCHAR(30)notnull,primarykey(USER_NAME));-- Create tablecreatetablePRODUCT(CODEVARCHAR(20)notnull,NAMEVARCHAR(128)notnull,PRICEFLOATnotnull,primarykey(CODE)) ;-- Insert data: ---------------------------------------------------------------insertintouser_account (USER_NAME, GENDER,PASSWORD)values('tom','M','tom001');insertintouser_account (USER_NAME, GENDER,PASSWORD)values('jerry','M','jerry001');insertintoproduct (CODE,NAME, PRICE)values('P001','Java Core', 100);insertintoproduct (CODE,NAME, PRICE)values('P002','C# Core', 90); -
5- Create WebApp Project
-
In Eclipse select:
-
- File/New/Other...
-

-

-

-

-
Project was created.
-

-
Add index.html
-

-
index.html12345678910111213141516171819
<!DOCTYPE html><html><head><metacharset="UTF-8"><title>Simple Web Application</title></head><body><h2>Simple Login Web Application using JSP/Servlet</h2><ul><li><ahref="home">Home</a></li><li><ahref="login">Login</a></li><li><ahref="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:
-
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:
-
Or download here:
- some-jdbc-drivers.zip (MySQL + SQL Server + Oracle) o7planning link.
-
Results downloaded:
-

-
Copy these libraries into the WEB-INF/lib:
-

-
9- Download and declare JSTL library
-
You need to download 2 JSTL libraries to be able to use them in the JSP:
-
- javax.servlet.jsp.jstl-*.jar
- javax.servlet.jsp.jslt-api-*.jar
-

-

-
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.java1234567891011121314151617181920212223242526272829303132333435363738394041
packageorg.o7planning.simplewebapp.beans;publicclassUserAccount {publicstaticfinalString GENDER_MALE ="M";publicstaticfinalString GENDER_FEMALE ="F";privateString userName;privateString gender;privateString password;publicUserAccount() {}publicString getUserName() {returnuserName;}publicvoidsetUserName(String userName) {this.userName = userName;}publicString getGender() {returngender;}publicvoidsetGender(String gender) {this.gender = gender;}publicString getPassword() {returnpassword;}publicvoidsetPassword(String password) {this.password = password;}} -
Product.java12345678910111213141516171819202122232425262728293031323334353637383940414243
packageorg.o7planning.simplewebapp.beans;publicclassProduct {privateString code;privateString name;privatefloatprice;publicProduct() {}publicProduct(String code, String name,floatprice) {this.code = code;this.name = name;this.price = price;}publicString getCode() {returncode;}publicvoidsetCode(String code) {this.code = code;}publicString getName() {returnname;}publicvoidsetName(String name) {this.name = name;}publicfloatgetPrice() {returnprice;}publicvoidsetPrice(floatprice) {this.price = price;}} -
11- Database Connection Utility classes
-

-
MySQLConnUtils.java12345678910111213141516171819202122232425262728293031323334
packageorg.o7planning.simplewebapp.conn;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLException;publicclassMySQLConnUtils {publicstaticConnection getMySQLConnection()throwsClassNotFoundException, SQLException {// Note: Change the connection parameters accordingly.String hostName ="localhost";String dbName ="mytest";String userName ="root";String password ="12345";returngetMySQLConnection(hostName, dbName, userName, password);}publicstaticConnection getMySQLConnection(String hostName, String dbName,String userName, String password)throwsSQLException,ClassNotFoundException {Class.forName("com.mysql.jdbc.Driver");// URL Connection for MySQL:// Example:// jdbc:mysql://localhost:3306/simplehrConnection conn = DriverManager.getConnection(connectionURL, userName,password);returnconn;}} -
OracleConnUtils.java12345678910111213141516171819202122232425262728293031323334353637
packageorg.o7planning.simplewebapp.conn;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLException;publicclassOracleConnUtils {publicstaticConnection getOracleConnection()throwsClassNotFoundException, SQLException {// Note: Change the connection parameters accordingly.String hostName ="localhost";String sid ="db12c";String userName ="mytest";String password ="12345";returngetOracleConnection(hostName, sid, userName, password);}publicstaticConnection getOracleConnection(String hostName, String sid,String userName, String password)throwsClassNotFoundException,SQLException {Class.forName("oracle.jdbc.driver.OracleDriver");// URL Connection for Oracle// Example:// jdbc:oracle:thin:@localhost:1521:db11g// jdbc:oracle:thin:@//HOSTNAME:PORT/SERVICENAMEString connectionURL ="jdbc:oracle:thin:@"+ hostName +":1521:"+ sid;Connection conn = DriverManager.getConnection(connectionURL, userName,password);returnconn;}} -
SQLServerConnUtils_JTDS.java12345678910111213141516171819202122232425262728293031323334353637383940
packageorg.o7planning.simplewebapp.conn;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLException;publicclassSQLServerConnUtils_JTDS {// Connect to SQLServer// (Using JDBC Driver of JTDS library)publicstaticConnection getSQLServerConnection_JTDS()//throwsSQLException, ClassNotFoundException {// Note: Change the connection parameters accordingly.String hostName ="localhost";String sqlInstanceName ="SQLEXPRESS";String database ="mytest";String userName ="sa";String password ="12345";returngetSQLServerConnection_JTDS(hostName, sqlInstanceName, database, userName, password);}// Connect to SQLServer, using JTDS libraryprivatestaticConnection getSQLServerConnection_JTDS(String hostName,//String sqlInstanceName, String database, String userName, String password)throwsClassNotFoundException, SQLException {Class.forName("net.sourceforge.jtds.jdbc.Driver");// Example:+ database +";instance="+ sqlInstanceName;Connection conn = DriverManager.getConnection(connectionURL, userName, password);returnconn;}} -
SQLServerConnUtils_SQLJDBC.java12345678910111213141516171819202122232425262728293031323334353637383940
packageorg.o7planning.simplewebapp.conn;importjava.sql.Connection;importjava.sql.DriverManager;importjava.sql.SQLException;publicclassSQLServerConnUtils_SQLJDBC {// Connect to SQL Server.// (Using JDBC Driver: SQLJDBC)publicstaticConnection getSQLServerConnection_SQLJDBC()//throwsClassNotFoundException, SQLException {// Note: Change the connection parameters accordingly.String hostName ="localhost";String sqlInstanceName ="SQLEXPRESS";String database ="mytest";String userName ="sa";String password ="12345";returngetSQLServerConnection_SQLJDBC(hostName, sqlInstanceName, database, userName, password);}// Connect to SQLServer, using SQLJDBC Library.privatestaticConnection getSQLServerConnection_SQLJDBC(String hostName,//String sqlInstanceName, String database, String userName, String password)//throwsClassNotFoundException, SQLException {Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");// Example:+";instance="+ sqlInstanceName +";databaseName="+ database;Connection conn = DriverManager.getConnection(connectionURL, userName, password);returnconn;}} -
ConnectionUtils.java1234567891011121314151617181920212223242526272829303132333435
packageorg.o7planning.simplewebapp.conn;importjava.sql.Connection;importjava.sql.SQLException;publicclassConnectionUtils {publicstaticConnection getConnection()throwsClassNotFoundException, SQLException {// Here I using Oracle Database.// (You can change to use another database.)returnOracleConnUtils.getOracleConnection();// return OracleConnUtils.getOracleConnection();// return MySQLConnUtils.getMySQLConnection();// return SQLServerConnUtils_JTDS.getSQLServerConnection_JTDS();// return SQLServerConnUtils_SQLJDBC.getSQLServerConnection_SQLJDBC();// return PostGresConnUtils.getPostGresConnection();}publicstaticvoidcloseQuietly(Connection conn) {try{conn.close();}catch(Exception e) {}}publicstaticvoidrollbackQuietly(Connection conn) {try{conn.rollback();}catch(Exception e) {}}} -
12- The utility class & manipulate data
-

-
MyUtils.java123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
packageorg.o7planning.simplewebapp.utils;importjava.sql.Connection;importjavax.servlet.ServletRequest;importjavax.servlet.http.Cookie;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importorg.o7planning.simplewebapp.beans.UserAccount;publicclassMyUtils {publicstaticfinalString ATT_NAME_CONNECTION ="ATTRIBUTE_FOR_CONNECTION";privatestaticfinalString ATT_NAME_USER_NAME ="ATTRIBUTE_FOR_STORE_USER_NAME_IN_COOKIE";// Store Connection in request attribute.// (Information stored only exist during requests)publicstaticvoidstoreConnection(ServletRequest request, Connection conn) {request.setAttribute(ATT_NAME_CONNECTION, conn);}// Get the Connection object has been stored in attribute of the request.publicstaticConnection getStoredConnection(ServletRequest request) {Connection conn = (Connection) request.getAttribute(ATT_NAME_CONNECTION);returnconn;}// Store user info in Session.publicstaticvoidstoreLoginedUser(HttpSession session, UserAccount loginedUser) {// On the JSP can access via ${loginedUser}session.setAttribute("loginedUser", loginedUser);}// Get the user information stored in the session.publicstaticUserAccount getLoginedUser(HttpSession session) {UserAccount loginedUser = (UserAccount) session.getAttribute("loginedUser");returnloginedUser;}// Store info in CookiepublicstaticvoidstoreUserCookie(HttpServletResponse response, UserAccount user) {System.out.println("Store user cookie");Cookie cookieUserName =newCookie(ATT_NAME_USER_NAME, user.getUserName());// 1 day (Converted to seconds)cookieUserName.setMaxAge(24*60*60);response.addCookie(cookieUserName);}publicstaticString getUserNameInCookie(HttpServletRequest request) {Cookie[] cookies = request.getCookies();if(cookies !=null) {for(Cookie cookie : cookies) {if(ATT_NAME_USER_NAME.equals(cookie.getName())) {returncookie.getValue();}}}returnnull;}// Delete cookie.publicstaticvoiddeleteUserCookie(HttpServletResponse response) {Cookie cookieUserName =newCookie(ATT_NAME_USER_NAME,null);// 0 seconds (This cookie will expire immediately)cookieUserName.setMaxAge(0);response.addCookie(cookieUserName);}} -
DBUtils.java123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129
packageorg.o7planning.simplewebapp.utils;importjava.sql.Connection;importjava.sql.PreparedStatement;importjava.sql.ResultSet;importjava.sql.SQLException;importjava.util.ArrayList;importjava.util.List;importorg.o7planning.simplewebapp.beans.Product;importorg.o7planning.simplewebapp.beans.UserAccount;publicclassDBUtils {publicstaticUserAccount findUser(Connection conn,//String userName, String password)throwsSQLException {String sql ="Select a.User_Name, a.Password, a.Gender from User_Account a "//+" where a.User_Name = ? and a.password= ?";PreparedStatement pstm = conn.prepareStatement(sql);pstm.setString(1, userName);pstm.setString(2, password);ResultSet rs = pstm.executeQuery();if(rs.next()) {String gender = rs.getString("Gender");UserAccount user =newUserAccount();user.setUserName(userName);user.setPassword(password);user.setGender(gender);returnuser;}returnnull;}publicstaticUserAccount findUser(Connection conn, String userName)throwsSQLException {String sql ="Select a.User_Name, a.Password, a.Gender from User_Account a "//+" where a.User_Name = ? ";PreparedStatement pstm = conn.prepareStatement(sql);pstm.setString(1, userName);ResultSet rs = pstm.executeQuery();if(rs.next()) {String password = rs.getString("Password");String gender = rs.getString("Gender");UserAccount user =newUserAccount();user.setUserName(userName);user.setPassword(password);user.setGender(gender);returnuser;}returnnull;}publicstaticList<Product> queryProduct(Connection conn)throwsSQLException {String sql ="Select a.Code, a.Name, a.Price from Product a ";PreparedStatement pstm = conn.prepareStatement(sql);ResultSet rs = pstm.executeQuery();List<Product> list =newArrayList<Product>();while(rs.next()) {String code = rs.getString("Code");String name = rs.getString("Name");floatprice = rs.getFloat("Price");Product product =newProduct();product.setCode(code);product.setName(name);product.setPrice(price);list.add(product);}returnlist;}publicstaticProduct findProduct(Connection conn, String code)throwsSQLException {String sql ="Select a.Code, a.Name, a.Price from Product a where a.Code=?";PreparedStatement pstm = conn.prepareStatement(sql);pstm.setString(1, code);ResultSet rs = pstm.executeQuery();while(rs.next()) {String name = rs.getString("Name");floatprice = rs.getFloat("Price");Product product =newProduct(code, name, price);returnproduct;}returnnull;}publicstaticvoidupdateProduct(Connection conn, Product product)throwsSQLException {String sql ="Update Product set Name =?, Price=? where Code=? ";PreparedStatement pstm = conn.prepareStatement(sql);pstm.setString(1, product.getName());pstm.setFloat(2, product.getPrice());pstm.setString(3, product.getCode());pstm.executeUpdate();}publicstaticvoidinsertProduct(Connection conn, Product product)throwsSQLException {String sql ="Insert into Product(Code, Name,Price) values (?,?,?)";PreparedStatement pstm = conn.prepareStatement(sql);pstm.setString(1, product.getCode());pstm.setString(2, product.getName());pstm.setFloat(3, product.getPrice());pstm.executeUpdate();}publicstaticvoiddeleteProduct(Connection conn, String code)throwsSQLException {String sql ="Delete From Product where Code= ?";PreparedStatement pstm = conn.prepareStatement(sql);pstm.setString(1, code);pstm.executeUpdate();}} -
13- Create Servlet Filter connect to Database
-
In JDBCFilter, I checked which requests actually referred to a Servlet, so that you can see the picture below to find it easy to understand, it describes the relationship between the concepts of Servlet.
-

-
JDBCFilter with url-pattern = /* means that all requests of users have go through this filter.
JDBCFilter will check the request to ensure that it only opens JDBC connection for the necessary request, eg for Servlet, avoid opening JDBC connection to common requests like image, css, js, html -
JDBCFilter.java123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121
packageorg.o7planning.simplewebapp.filter;importjava.io.IOException;importjava.sql.Connection;importjava.util.Collection;importjava.util.Map;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRegistration;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;importjavax.servlet.annotation.WebFilter;importjavax.servlet.http.HttpServletRequest;importorg.o7planning.simplewebapp.conn.ConnectionUtils;importorg.o7planning.simplewebapp.utils.MyUtils;@WebFilter(filterName ="jdbcFilter", urlPatterns = {"/*"})publicclassJDBCFilterimplementsFilter {publicJDBCFilter() {}@Overridepublicvoidinit(FilterConfig fConfig)throwsServletException {}@Overridepublicvoiddestroy() {}// Check the target of the request is a servlet?privatebooleanneedJDBC(HttpServletRequest request) {System.out.println("JDBC Filter");//// Servlet Url-pattern: /spath/*//// => /spathString servletPath = request.getServletPath();// => /abc/mnpString pathInfo = request.getPathInfo();String urlPattern = servletPath;if(pathInfo !=null) {// => /spath/*urlPattern = servletPath +"/*";}// Key: servletName.// Value: ServletRegistrationMap<String, ?extendsServletRegistration> servletRegistrations = request.getServletContext().getServletRegistrations();// Collection of all servlet in your Webapp.Collection<?extendsServletRegistration> values = servletRegistrations.values();for(ServletRegistration sr : values) {Collection<String> mappings = sr.getMappings();if(mappings.contains(urlPattern)) {returntrue;}}returnfalse;}@OverridepublicvoiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)throwsIOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;// Only open connections for the special requests.// (For example, the path to the servlet, JSP, ..)//// Avoid open connection for commons request.// (For example: image, css, javascript,... )//if(this.needJDBC(req)) {System.out.println("Open Connection for: "+ req.getServletPath());Connection conn =null;try{// Create a Connection.conn = ConnectionUtils.getConnection();// Set outo commit to false.conn.setAutoCommit(false);// Store Connection object in attribute of request.MyUtils.storeConnection(request, conn);// Allow request to go forward// (Go to the next filter or target)chain.doFilter(request, response);// Invoke the commit() method to complete the transaction with the DB.conn.commit();}catch(Exception e) {e.printStackTrace();ConnectionUtils.rollbackQuietly(conn);thrownewServletException();}finally{ConnectionUtils.closeQuietly(conn);}}// With commons requests (images, css, html, ..)// No need to open the connection.else{// Allow request to go forward// (Go to the next filter or target)chain.doFilter(request, response);}}} -
14- Servlet Filter reads Cookies to automatically login
-
In case, the user logined and remembered information in previous access (for example the day before). And now the user return, this Filter will check the Cookie information stored by the browser and automatic Login.
-
CookieFilter.java1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071
packageorg.o7planning.simplewebapp.filter;importjava.io.IOException;importjava.sql.Connection;importjava.sql.SQLException;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;importjavax.servlet.annotation.WebFilter;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpSession;importorg.o7planning.simplewebapp.beans.UserAccount;importorg.o7planning.simplewebapp.utils.DBUtils;importorg.o7planning.simplewebapp.utils.MyUtils;@WebFilter(filterName ="cookieFilter", urlPatterns = {"/*"})publicclassCookieFilterimplementsFilter {publicCookieFilter() {}@Overridepublicvoidinit(FilterConfig fConfig)throwsServletException {}@Overridepublicvoiddestroy() {}@OverridepublicvoiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)throwsIOException, ServletException {HttpServletRequest req = (HttpServletRequest) request;HttpSession session = req.getSession();UserAccount userInSession = MyUtils.getLoginedUser(session);//if(userInSession !=null) {session.setAttribute("COOKIE_CHECKED","CHECKED");chain.doFilter(request, response);return;}// Connection was created in JDBCFilter.Connection conn = MyUtils.getStoredConnection(request);// Flag check cookieString checked = (String) session.getAttribute("COOKIE_CHECKED");if(checked ==null&& conn !=null) {String userName = MyUtils.getUserNameInCookie(req);try{UserAccount user = DBUtils.findUser(conn, userName);MyUtils.storeLoginedUser(session, user);}catch(SQLException e) {e.printStackTrace();}// Mark checked Cookies.session.setAttribute("COOKIE_CHECKED","CHECKED");}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). -
123456789
<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.xml1234567891011121314151617181920212223242526272829
<?xmlversion="1.0"encoding="UTF-8"?>xsi:schemaLocation="http://java.sun.com/xml/ns/javaeeid="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> -
15- EncodingFilter Servlet
-
EncodingFilter.java123456789101112131415161718192021222324252627282930313233343536373839404142434445
packageorg.o7planning.simplewebapp.filter;importjava.io.IOException;importjava.sql.Connection;importjava.util.Collection;importjava.util.Map;importjavax.servlet.Filter;importjavax.servlet.FilterChain;importjavax.servlet.FilterConfig;importjavax.servlet.ServletException;importjavax.servlet.ServletRegistration;importjavax.servlet.ServletRequest;importjavax.servlet.ServletResponse;importjavax.servlet.annotation.WebFilter;importjavax.servlet.http.HttpServletRequest;importorg.o7planning.simplewebapp.conn.ConnectionUtils;importorg.o7planning.simplewebapp.utils.MyUtils;@WebFilter(filterName ="encodingFilter", urlPatterns = {"/*"})publicclassEncodingFilterimplementsFilter {publicEncodingFilter() {}@Overridepublicvoidinit(FilterConfig fConfig)throwsServletException {}@Overridepublicvoiddestroy() {}@OverridepublicvoiddoFilter(ServletRequest request, ServletResponse response, FilterChain chain)throwsIOException, ServletException {request.setCharacterEncoding("UTF-8");chain.doFilter(request, response);}} -
16- Pages reuse
-
Some JSP pages will be used to embed into other JSP page at Runtime, through the use of:
-
1234
<jsp:includepage="_header.jsp"></jsp:include><jsp:includepage="_menu.jsp"></jsp:include><jsp:includepage="_footer.jsp"></jsp:include> -

-
/WEB-INF/views/_header.jsp1234567891011121314151617
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><divstyle="background: #E0E0E0; height: 55px; padding: 5px;"><divstyle="float: left"><h1>My Site</h1></div><divstyle="float: right; padding: 10px; text-align: right;"><!-- User store in session with attribute: loginedUser -->Hello <b>${loginedUser.userName}</b><br/>Search <inputname="search"></div></div> -
/WEB-INF/views/_menu.jsp1234567891011121314
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><divstyle="padding: 5px;"><ahref="${pageContext.request.contextPath}/">Home</a>|<ahref="${pageContext.request.contextPath}/productList">Product List</a>|<ahref="${pageContext.request.contextPath}/userInfo">My Account Info</a>|<ahref="${pageContext.request.contextPath}/login">Login</a></div> -
/WEB-INF/views/_footer.jsp123456789
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><divstyle="background: #E0E0E0; text-align: center; padding: 5px; margin-top: 10px;">@Copyright o7planning.org</div> -
17- Home Page
-
When entering the default path, eg enter the site's domain name it will display the home page (Case contextPath = ""), you need to declare your home page in <welcome-file-list> of web.xml
-
Link below is showing the content of the page index.html
-
You need to design a home page as a JSP page to display dynamic information instead of a html page that contains static information.
-
web.xml1234567891011121314151617181920212223242526272829
<?xmlversion="1.0"encoding="UTF-8"?>xsi:schemaLocation="http://java.sun.com/xml/ns/javaeeid="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> -
Models of Home Page:
-

-
HomeServlet.java123456789101112131415161718192021222324252627282930313233343536373839
packageorg.o7planning.simplewebapp.servlet;importjava.io.IOException;importjavax.servlet.RequestDispatcher;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;@WebServlet(urlPatterns = {"/home"})publicclassHomeServletextendsHttpServlet {privatestaticfinallongserialVersionUID = 1L;publicHomeServlet() {super();}@OverrideprotectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, 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);}@OverrideprotectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {doGet(request, response);}} -
/WEB-INF/views/homeView.jsp123456789101112131415161718192021222324252627282930
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html><html><head><metacharset="UTF-8"><title>Home Page</title></head><body><jsp:includepage="_header.jsp"></jsp:include><jsp:includepage="_menu.jsp"></jsp:include><h3>Home Page</h3>This is demo Simple web application using jsp,servlet & Jdbc. <br><br><b>It includes the following functions:</b><ul><li>Login</li><li>Storing user information in cookies</li><li>Product List</li><li>Create Product</li><li>Edit Product</li><li>Delete Product</li></ul><jsp:includepage="_footer.jsp"></jsp:include></body></html> -
Rerun your application, and try two URLs:
-

-
NOTE: For whatever reason, the link http: //localhost:8080/SimpleWebApp/ is still displayed content of index.html, you can delete or rename the index.html file, for example, you can change it into _index.html
-
18- Login Page - LoginServlet
-
This is a model of Login function:
-

-
LoginServlet.java123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111
packageorg.o7planning.simplewebapp.servlet;importjava.io.IOException;importjava.sql.Connection;importjava.sql.SQLException;importjavax.servlet.RequestDispatcher;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importorg.o7planning.simplewebapp.beans.UserAccount;importorg.o7planning.simplewebapp.utils.DBUtils;importorg.o7planning.simplewebapp.utils.MyUtils;@WebServlet(urlPatterns = {"/login"})publicclassLoginServletextendsHttpServlet {privatestaticfinallongserialVersionUID = 1L;publicLoginServlet() {super();}// Show Login page.@OverrideprotectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {// 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.@OverrideprotectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {String userName = request.getParameter("userName");String password = request.getParameter("password");String rememberMeStr = request.getParameter("rememberMe");booleanremember ="Y".equals(rememberMeStr);UserAccount user =null;booleanhasError =false;String errorString =null;if(userName ==null|| password ==null|| userName.length() ==0|| password.length() ==0) {hasError =true;errorString ="Required username and password!";}else{Connection conn = MyUtils.getStoredConnection(request);try{// Find the user in the DB.user = DBUtils.findUser(conn, userName, password);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.jspif(hasError) {user =newUserAccount();user.setUserName(userName);user.setPassword(password);// Store information in request attribute, before forward.request.setAttribute("errorString", errorString);request.setAttribute("user", user);// Forward to /WEB-INF/views/login.jspRequestDispatcher 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);// If user checked "Remember me".if(remember) {MyUtils.storeUserCookie(response, user);}// Else delete cookie.else{MyUtils.deleteUserCookie(response);}// Redirect to userInfo page.response.sendRedirect(request.getContextPath() +"/userInfo");}}} -
UserInfoServlet.java12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
packageorg.o7planning.simplewebapp.servlet;importjava.io.IOException;importjavax.servlet.RequestDispatcher;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importjavax.servlet.http.HttpSession;importorg.o7planning.simplewebapp.beans.UserAccount;importorg.o7planning.simplewebapp.utils.MyUtils;@WebServlet(urlPatterns = {"/userInfo"})publicclassUserInfoServletextendsHttpServlet {privatestaticfinallongserialVersionUID = 1L;publicUserInfoServlet() {super();}@OverrideprotectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {HttpSession session = request.getSession();// Check User has logged onUserAccount loginedUser = MyUtils.getLoginedUser(session);// Not logged inif(loginedUser ==null) {// Redirect to login page.response.sendRedirect(request.getContextPath() +"/login");return;}// Store info to the request attribute before forwarding.request.setAttribute("user", loginedUser);// If the user has logged in, then forward to the page// /WEB-INF/views/userInfoView.jspRequestDispatcher dispatcher//=this.getServletContext().getRequestDispatcher("/WEB-INF/views/userInfoView.jsp");dispatcher.forward(request, response);}@OverrideprotectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {doGet(request, response);}} -

-
/WEB-INF/views/loginView.jsp123456789101112131415161718192021222324252627282930313233343536373839404142434445
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html><html><head><metacharset="UTF-8"><title>Login</title></head><body><jsp:includepage="_header.jsp"></jsp:include><jsp:includepage="_menu.jsp"></jsp:include><h3>Login Page</h3><pstyle="color: red;">${errorString}</p><formmethod="POST"action="${pageContext.request.contextPath}/login"><tableborder="0"><tr><td>User Name</td><td><inputtype="text"name="userName"value="${user.userName}"/> </td></tr><tr><td>Password</td><td><inputtype="text"name="password"value="${user.password}"/> </td></tr><tr><td>Remember me</td><td><inputtype="checkbox"name="rememberMe"value="Y"/> </td></tr><tr><tdcolspan="2"><inputtype="submit"value="Submit"/><ahref="${pageContext.request.contextPath}/">Cancel</a></td></tr></table></form><pstyle="color:blue;">User Name: tom, password: tom001 or jerry/jerry001</p><jsp:includepage="_footer.jsp"></jsp:include></body></html> -
/WEB-INF/views/userInfoView.jsp1234567891011121314151617181920212223
<%@ page language="java" contentType="text/html; charset=UTF-8"pageEncoding="UTF-8"%><!DOCTYPE html><html><head><metacharset="UTF-8"><title>User Info</title></head><body><jsp:includepage="_header.jsp"></jsp:include><jsp:includepage="_menu.jsp"></jsp:include><h3>Hello: ${user.userName}</h3>User Name: <b>${user.userName}</b><br/>Gender: ${user.gender } <br/><jsp:includepage="_footer.jsp"></jsp:include></body></html> -
Running your application:
-

-

-
19- Product List Page
-
Model:
-

-
ProductListServlet.java1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
packageorg.o7planning.simplewebapp.servlet;importjava.io.IOException;importjava.sql.Connection;importjava.sql.SQLException;importjava.util.List;importjavax.servlet.RequestDispatcher;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.o7planning.simplewebapp.beans.Product;importorg.o7planning.simplewebapp.utils.DBUtils;importorg.o7planning.simplewebapp.utils.MyUtils;@WebServlet(urlPatterns = {"/productList"})publicclassProductListServletextendsHttpServlet {privatestaticfinallongserialVersionUID = 1L;publicProductListServlet() {super();}@OverrideprotectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, 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 viewsrequest.setAttribute("errorString", errorString);request.setAttribute("productList", list);// Forward to /WEB-INF/views/productListView.jspRequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/views/productListView.jsp");dispatcher.forward(request, response);}@OverrideprotectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {doGet(request, response);}} -
/WEB-INF/views/productListView.jsp1234567891011121314151617181920212223242526272829303132333435363738394041424344454647
<%@ 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><metacharset="UTF-8"><title>Product List</title></head><body><jsp:includepage="_header.jsp"></jsp:include><jsp:includepage="_menu.jsp"></jsp:include><h3>Product List</h3><pstyle="color: red;">${errorString}</p><tableborder="1"cellpadding="5"cellspacing="1"><tr><th>Code</th><th>Name</th><th>Price</th><th>Edit</th><th>Delete</th></tr><c:forEachitems="${productList}"var="product"><tr><td>${product.code}</td><td>${product.name}</td><td>${product.price}</td><td><ahref="editProduct?code=${product.code}">Edit</a></td><td><ahref="deleteProduct?code=${product.code}">Delete</a></td></tr></c:forEach></table><ahref="createProduct">Create Product</a><jsp:includepage="_footer.jsp"></jsp:include></body></html> -
Rerun Application:
-

-
20- Add Product Page
-
Model:
-

-
CreateProductServlet.java1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
packageorg.o7planning.simplewebapp.servlet;importjava.io.IOException;importjava.sql.Connection;importjava.sql.SQLException;importjavax.servlet.RequestDispatcher;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.o7planning.simplewebapp.beans.Product;importorg.o7planning.simplewebapp.utils.DBUtils;importorg.o7planning.simplewebapp.utils.MyUtils;@WebServlet(urlPatterns = {"/createProduct"})publicclassCreateProductServletextendsHttpServlet {privatestaticfinallongserialVersionUID = 1L;publicCreateProductServlet() {super();}// Show product creation page.@OverrideprotectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/views/createProductView.jsp");dispatcher.forward(request, response);}// When the user enters the product information, and click Submit.// This method will be called.@OverrideprotectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {Connection conn = MyUtils.getStoredConnection(request);String code = (String) request.getParameter("code");String name = (String) request.getParameter("name");String priceStr = (String) request.getParameter("price");floatprice =0;try{price = Float.parseFloat(priceStr);}catch(Exception e) {}Product product =newProduct(code, name, price);String errorString =null;// Product ID is the string literal [a-zA-Z_0-9]// with at least 1 characterString regex ="\\w+";if(code ==null|| !code.matches(regex)) {errorString ="Product Code invalid!";}if(errorString ==null) {try{DBUtils.insertProduct(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);// If error, forward to Edit page.if(errorString !=null) {RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/views/createProductView.jsp");dispatcher.forward(request, response);}// If everything nice.// Redirect to the product listing page.else{response.sendRedirect(request.getContextPath() +"/productList");}}} -
/WEB-INF/views/createProductView.jsp12345678910111213141516171819202122232425262728293031323334353637383940414243444546
<%@ 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><metacharset="UTF-8"><title>Create Product</title></head><body><jsp:includepage="_header.jsp"></jsp:include><jsp:includepage="_menu.jsp"></jsp:include><h3>Create Product</h3><pstyle="color: red;">${errorString}</p><formmethod="POST"action="${pageContext.request.contextPath}/createProduct"><tableborder="0"><tr><td>Code</td><td><inputtype="text"name="code"value="${product.code}"/></td></tr><tr><td>Name</td><td><inputtype="text"name="name"value="${product.name}"/></td></tr><tr><td>Price</td><td><inputtype="text"name="price"value="${product.price}"/></td></tr><tr><tdcolspan="2"><inputtype="submit"value="Submit"/><ahref="productList">Cancel</a></td></tr></table></form><jsp:includepage="_footer.jsp"></jsp:include></body></html> -

-
21- Edit Product Page
-
Model:
-

-
EditProductServlet.java123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
packageorg.o7planning.simplewebapp.servlet;importjava.io.IOException;importjava.sql.Connection;importjava.sql.SQLException;importjavax.servlet.RequestDispatcher;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.o7planning.simplewebapp.beans.Product;importorg.o7planning.simplewebapp.utils.DBUtils;importorg.o7planning.simplewebapp.utils.MyUtils;@WebServlet(urlPatterns = {"/editProduct"})publicclassEditProductServletextendsHttpServlet {privatestaticfinallongserialVersionUID = 1L;publicEditProductServlet() {super();}// Show product edit page.@OverrideprotectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {Connection conn = MyUtils.getStoredConnection(request);String code = (String) request.getParameter("code");Product product =null;String errorString =null;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;}// Store errorString in request attribute, before forward to views.request.setAttribute("errorString", errorString);request.setAttribute("product", product);RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/views/editProductView.jsp");dispatcher.forward(request, response);}// After the user modifies the product information, and click Submit.// This method will be executed.@OverrideprotectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {Connection conn = MyUtils.getStoredConnection(request);String code = (String) request.getParameter("code");String name = (String) request.getParameter("name");String priceStr = (String) request.getParameter("price");floatprice =0;try{price = Float.parseFloat(priceStr);}catch(Exception e) {}Product product =newProduct(code, name, price);String errorString =null;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);// If error, forward to Edit page.if(errorString !=null) {RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/views/editProductView.jsp");dispatcher.forward(request, response);}// If everything nice.// Redirect to the product listing page.else{response.sendRedirect(request.getContextPath() +"/productList");}}} -
/WEB-INF/views/editProductView.jsp123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
<%@ 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><metacharset="UTF-8"><title>Edit Product</title></head><body><jsp:includepage="_header.jsp"></jsp:include><jsp:includepage="_menu.jsp"></jsp:include><h3>Edit Product</h3><pstyle="color: red;">${errorString}</p><c:iftest="${not empty product}"><formmethod="POST"action="${pageContext.request.contextPath}/editProduct"><inputtype="hidden"name="code"value="${product.code}"/><tableborder="0"><tr><td>Code</td><tdstyle="color:red;">${product.code}</td></tr><tr><td>Name</td><td><inputtype="text"name="name"value="${product.name}"/></td></tr><tr><td>Price</td><td><inputtype="text"name="price"value="${product.price}"/></td></tr><tr><tdcolspan="2"><inputtype="submit"value="Submit"/><ahref="${pageContext.request.contextPath}/productList">Cancel</a></td></tr></table></form></c:if><jsp:includepage="_footer.jsp"></jsp:include></body></html> -
22- Delete Product
-
Model:
-

-
DeleteProductServlet.java12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364
packageorg.o7planning.simplewebapp.servlet;importjava.io.IOException;importjava.sql.Connection;importjava.sql.SQLException;importjavax.servlet.RequestDispatcher;importjavax.servlet.ServletException;importjavax.servlet.annotation.WebServlet;importjavax.servlet.http.HttpServlet;importjavax.servlet.http.HttpServletRequest;importjavax.servlet.http.HttpServletResponse;importorg.o7planning.simplewebapp.utils.DBUtils;importorg.o7planning.simplewebapp.utils.MyUtils;@WebServlet(urlPatterns = {"/deleteProduct"})publicclassDeleteProductServletextendsHttpServlet {privatestaticfinallongserialVersionUID = 1L;publicDeleteProductServlet() {super();}@OverrideprotectedvoiddoGet(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {Connection conn = MyUtils.getStoredConnection(request);String code = (String) request.getParameter("code");String errorString =null;try{DBUtils.deleteProduct(conn, code);}catch(SQLException e) {e.printStackTrace();errorString = e.getMessage();}// If has an error, redirecte to the error page.if(errorString !=null) {// Store the information in the request attribute, before forward to views.request.setAttribute("errorString", errorString);//RequestDispatcher dispatcher = request.getServletContext().getRequestDispatcher("/WEB-INF/views/deleteProductErrorView.jsp");dispatcher.forward(request, response);}// If everything nice.// Redirect to the product listing page.else{response.sendRedirect(request.getContextPath() +"/productList");}}@OverrideprotectedvoiddoPost(HttpServletRequest request, HttpServletResponse response)throwsServletException, IOException {doGet(request, response);}} -
/WEB-INF/views/deleteProductErrorView.jsp123456789101112131415161718192021222324
<%@ 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><metacharset="UTF-8"><title>Delete Product</title></head><body><jsp:includepage="_header.jsp"></jsp:include><jsp:includepage="_menu.jsp"></jsp:include><h3>Delete Product</h3><pstyle="color: red;">${errorString}</p><ahref="productList">Product List</a><jsp:includepage="_footer.jsp"></jsp:include></body></html>
View more categories:
- Log in to post comments
Tags
