Java EE Tutorial 2

Java EE TutorialIn the 2nd part of my Java EE Tutorial I’ll cover Form Validation, Cover the JSTL Tags, Work with Databases and Provide Many Examples.

JSTL allows you to create variables, evaluate expressions, institute flow control, manipulate strings, format output, manage URLS, define locales and much more. If you want to learn more about MySQL look here. All of the code follows below to act as a cheat sheet and transcript.

This nearly 40 minute tutorial only contains one 5 second skippable ad. I’d greatly appreciate it if you didn’t Ad Block it, so that I can continue making free tutorials for all.

Code & Transcript

—— DisplayInfo.jsp ——

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Hello</title>
</head>
<body>
<!-- NEW Import JSTL Jar Files
1. Go to http://tomcat.apache.org/download-taglibs.cgi
2. Download taglibs-standard-spec-1.2.5.jar
3. Download taglibs-standard-impl-1.2.5.jar
4. Copy and paste into WebContent/WEB-INF/lib
5. Declare the taglib directive specifying the JSTL library
 -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<!-- String Functions -->
<%@ taglib uri = "http://java.sun.com/jsp/jstl/functions" prefix = "fn" %>

<!-- Formatting Tags -->
<%@ taglib prefix = "fmt" uri = "http://java.sun.com/jsp/jstl/fmt" %>

 <!-- NEW DATABASE EXAMPLE 
 Below we use the JSP Expression Language to access attributes 
 of the customer object
 -->
 <h3>Thank you for the Info</h3>
 <label>First Name : </label>
 ${cust.fName}<br>
 <label>Last Name : </label>
 ${cust.lName}<br>
 <label>Phone : </label>
 ${cust.phone}<br>
 
 <!-- NEW JSP Standard Tag Library (JSTL)
 Many new tags are available for performing different tasks
 Create HTML based on a condition
  -->
  <c:if test="${cust.fName.equals('Derek')}">
  <p>Hi Derek</p>
  </c:if>
  
  <!-- Print an expression -->
  <c:out value = "Calculate"/><br>
  5 + 4 = <c:out value = "${5 + 4}"/><br>
  <c:out value = "${cust.fName}"/><br>
 
 <!-- Store a value -->
 <c:set var = "dogName" scope = "session" value = "Spot"/>
 <c:out value = "${dogName}"/><br>
 
 <!-- Delete a value -->
 <c:remove var = "dogName"/>
 
 <!-- Choose works like switch or if / else block -->
 <c:set var = "age" scope = "session" value = "8"/>
 <c:choose>
 	<c:when test = "${(age >= 5) && (age <= 6)}">
    	Go to Kindergarten
    </c:when>
         
    <c:when test = "${(age >= 7) && (age <= 13)}">
            Go to Middle School
         </c:when>
         
         <c:when test = "${(age >= 14) && (age <= 18)}">
            Go to High School
         </c:when>
         
         <c:otherwise>
            Stay home
         </c:otherwise>
 </c:choose><br>
 
 <!-- Iterate over a collection -->
 <c:forEach var = "i" begin = "1" end = "5" step = "2">
 	<c:out value = "${i}"/><br>
 </c:forEach>
 
 <c:forTokens items = "Tom,Sue,Ed" delims = "," var = "x">
 	<c:out value = "${x}"/><br>
 </c:forTokens>
 
 <!-- Exception handling -->
 <c:catch var = "divideByZeroException">
 	<% int ans = 2/0; %>
 </c:catch>
 
 <c:if test = "${divideByZeroException != null }">
 	Exception : ${divideByZeroException}<br>
 	${divideByZeroException }<br>
 </c:if>
 
 <!-- Load URL and pass a parameter value-->
 <c:url value = "index.jsp" var = "theURL">
   <c:param name = "passedParam" value = "passed value"/>
</c:url>
<c:import url = "${theURL }"/>

<!-- String Manipulation
Define a string -->
<c:set var = "str1" value = "a random string"/>

<!-- Turn into an array -->
<c:set var = "arr1" value = "${fn:split(str1, ' ')}" />

<!-- Turn back into a string -->
<c:set var = "str2" value = "${fn:join(arr1, ' ')}" />

<!-- Get length -->
Length : ${fn:length(str2)}<br>

<!-- Trim whitespace on front and end -->
<c:set var = "str2" value = "${fn:trim(str2)}" />
String : ${str2}<br>

<!-- Check if string contains a string -->
<c:if test = "${fn:contains(str2, 'random')}">

<!-- Get index of string -->
<!-- See also fn:containsIgnoreCase -->
Index : ${fn:indexOf(str2, "random")}<br>

<!-- Change value in string -->
<c:set var = "str2" value = "${fn:replace(str2, 'random', 'special')}" />

<!-- Get a substring -->
<c:set var = "str3" value = "${fn:substring(str2, 2, 9)}" />

<!-- To uppercase See also ${fn:toLowerCase(str3)} -->
<c:set var = "str3" value = "${fn:toUpperCase(str3)}" />
String : ${str3}<br>

</c:if>

<!-- Formatting Tags -->
<!-- Specify the the content type of a request -->
<fmt:requestEncoding value = "UTF-8" />

<!-- Store the locale using the ISO-639 language code and ISO-3166 
country code https://docs.oracle.com/cd/E13214_01/wli/docs92/xref/xqisocodes.html -->
<fmt:setLocale value = "en_US"/>

<!-- Get time -->
<c:set var = "nowTime" value = "<%=new java.util.Date()%>" />

<!-- Format date  
value : Date to display 
type : DATE, TIME, or BOTH
timestyle : FULL, LONG, MEDIUM, SHORT
datestyle : FULL, LONG, MEDIUM, SHORT
pattern : Custom formatting 
timeZone : -->
Date : <fmt:formatDate value = "${nowTime}" 
type = "BOTH" timeStyle = "LONG" dateStyle = "LONG" /><br>

<!-- Change the time zone -->
<fmt:setTimeZone value = "GMT" />
Date : <fmt:formatDate value = "${nowTime}" 
type = "BOTH" timeStyle = "LONG" dateStyle = "LONG" /><br>

Custom Date : <fmt:formatDate pattern = "hh:mm:ss:SS a z E MMMMM dd yyyy G" 
         value = "${nowTime}" dateStyle = "LONG" /><br>
         
<!-- Parse numbers, currencies and percents -->
<c:set var = "val1" value = "5000.89" />

<fmt:parseNumber var = "val2" type = "NUMBER" value = "${val1}" />
Number : <c:out value = "${val2}" /><br>

<!-- Format currency and use different locales -->
<fmt:setLocale value="fr_FR"/>
<fmt:formatNumber value="${val2}" type="CURRENCY" /><br>
<fmt:formatNumber value="${val2}" type="PERCENT"/><br>

 
</body>
</html>

—— index.jsp ——

<!-- 
Working JSP Files
1. Right click -> New -> JSP File
2. Create ProcessInfo.java Servlet to handle this
--> 
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Testing JSP</title>
</head>
<body>

<!-- NEW Declare the taglib directive specifying the JSTL library -->
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

<h3>Enter some Info</h3>

<form action="ProcessInfo" method="post">
<label>First Name : </label>

<!-- NEW Add values that will hold data customer previously entered 
and additional data -->
<input type="text" name="fname" value="${cust.fName }"><br><br>
<label>Last Name : </label>
<input type="text" name="lname" value="${cust.lName }"><br><br>
<label>Street : </label>
<input type="text" name="street" value="${cust.street }"><br><br>
<label>City : </label>
<input type="text" name="city" value="${cust.city }"><br><br>
<label>State : </label>
<input type="text" name="state" value="${cust.state }"><br><br>
<label>Zip Code : </label>
<input type="text" name="zipcode" value="${cust.zipcode }"><br><br>
<label>Email : </label>
<input type="text" name="email" value="${cust.email }"><br><br>
<label>Password : </label>
<input type="text" name="password" value="${cust.password }"><br><br>
<label>Phone : </label>
<input type="text" name="phone" value="${cust.phone }"><br><br>
<input type="submit" value="Send">
</form>

<!-- Get passed parameter value -->
<%= request.getParameter("passedParam") %><br>

</body>
</html>






ProcessInfo.java

package com.newthinktank;

import java.io.IOException;

import java.sql.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

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("/ProcessInfo")
public class ProcessInfo extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    public ProcessInfo() {
        super();
    }

	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		doPost(request, response);
	}

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// The URL to send data to (JSP FILE)
		String url = "/DisplayInfo.jsp";
		
		// NEW Error message to display on the screen
		String errorMsg = "";
		
		// DATABASE EXAMPLE
		// NEW Add new data
		// Get the data entered on index.jsp
		String fName = request.getParameter("fname");
		String lName = request.getParameter("lname");
		String street = request.getParameter("street");
		String city = request.getParameter("city");
		String state = request.getParameter("state");
		String zipcode = request.getParameter("zipcode");
		String email = request.getParameter("email");
		String password = request.getParameter("password");
		String phone = request.getParameter("phone");
		
		if(!regexChecker("^[A-Za-z\\.\\’ \\-]{2,30}$", fName)) {
			url = "/index.jsp";
			fName = "Try again";
		}
		
		if(!regexChecker("^[A-Za-z\\.\\’ \\-]{2,30}$", lName)) {
			url = "/index.jsp";
			lName = "Try again";
		}
		
		if(!regexChecker("^[A-Za-z0-9\\.\\’ \\-]{5,50}$", street)) {
			url = "/index.jsp";
			street = "Try again";
		}
		
		if(!regexChecker("^[A-Za-z\\.\\’ \\-]{5,30}$", city)) {
			url = "/index.jsp";
			city = "Try again";
		}
		
		if(!regexChecker("^(?:(A[KLRZ]|C[AOT]|D[CE]|FL|GA|HI|I[ADLN]|K[SY]|LA|M[ADEINOST]|N[CDEHJMVY]|O[HKR]|P[AR]|RI|S[CD]|T[NX]|UT|V[AIT]|W[AIVY]))$", state)) {
			url = "/index.jsp";
			state = "Try again";
		}
		
		if(!regexChecker("^[0-9\\-]{10}$", zipcode)) {
			url = "/index.jsp";
			zipcode = "Try again";
		}
		
		if(!regexChecker("^[A-Za-z0-9._\\%-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}$", email)) {
			url = "/index.jsp";
			email = "Try again";
		}
		
		// Must have 1 uppercase, 1 lowercase, 1 number and a special
		if(!regexChecker("^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*?&])[A-Za-z\\d@$!%*?&]{8,20}$", password)) {
			url = "/index.jsp";
			password = "Try again";
		}
		
		if(!regexChecker("^([0-9]( |-)?)?(\\(?[0-9]{3}\\)?|[0-9]{3})( |-)?([0-9]{3}( |-)?[0-9]{4}|[0-9]{7})$", phone)) {
			url = "/index.jsp";
			phone = "Try again";
		}
		
		
		// NEW Update the DB
//		if(!url.equals("/index.jsp")) {
//			updateDB(fName, lName, street, city, state, zipcode, email, password, phone);
//		}
		
		// NEW Create object to pass to DisplayInfo.jsp
		Customer cust = new Customer(fName, lName, street, city, 
				state, zipcode, email, password, phone);
		request.setAttribute("cust", cust);
		
		// Forward data to DisplayInfo.jsp
		getServletContext()
			.getRequestDispatcher(url)
			.forward(request, response);
	}
	
	static boolean regexChecker(String theRegex, 
			String str2Check) {
		
		// You define the regex using pattern
		Pattern regexPattern = 
				Pattern.compile(theRegex);
				
		// Matcher searches a string for a match
		Matcher regexMatcher = 
				regexPattern.matcher(str2Check);
		
		if (regexMatcher.matches()){
			return true;
		} else {
			return false;
		}
		
	}
	
	// Setup MySQL Connector
	// Copy mysql-connector-java-8.0.15.jar into 
	// /WebContent/WEB-INF/lib/
	
	/*
	 * NEW SETUP DB
	 * mysql -u root -p
	 * CREATE DATABASE test2;
	 * USE test2;
	 * CREATE TABLE customer(
	 * fname VARCHAR(30) NOT NULL,
	 * lname VARCHAR(30) NOT NULL,
	 * street VARCHAR(50) NOT NULL,
	 * city VARCHAR(30) NOT NULL,
	 * state VARCHAR(2) NOT NULL,
	 * zipcode VARCHAR(10) NOT NULL,
	 * email VARCHAR(30) NOT NULL,
	 * password VARCHAR(20) NOT NULL,
	 * phone VARCHAR(20) NOT NULL, 
	 * cust_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY);
	 * CREATE USER 'dbadmin'@'localhost' IDENTIFIED BY 'turtledove';
	 * GRANT ALL PRIVILEGES ON test2.customer TO 
	 * 'dbadmin'@'localhost' IDENTIFIED BY 'turtledove';
	 */
	
	// Adds users to the DB
		protected void updateDB(String fName, String lName, String street, String city,
				String state, String zipcode, String email, String password,
				String phone) {
			// Connects to the DB
			Connection con;
			
			try {
				// Everything needed to connect to the DB
				Class.forName("com.mysql.cj.jdbc.Driver");
				
				// NEW Update database name
				String url = "jdbc:mysql://localhost/test2";
		        String user = "dbadmin";
		        String pw = "turtledove";
		        
		        // Used to issue queries to the DB
		        con = DriverManager.getConnection(url, user, pw);
		        
		        // Sends queries to the DB for results
		        Statement s = con.createStatement();
		        
		        // Add a new entry
		        String query = "INSERT INTO CUSTOMER " + 
		        "(fname, lname, street, city, state, zipcode, email, password, phone, cust_id) " + 
		        "VALUES ('" + fName + "', '" + lName + "', '" +
		        street + "', '" + city + "', '" + state + "', '" +
		        zipcode + "', '" + email + "', '" + password + "', '" +
		        phone + "', NULL)";
		        
		        // Execute the Query
		        s.executeUpdate(query);
		        
		        // Close DB connection
		        con.close();
			} 
			catch (ClassNotFoundException e) {
				e.printStackTrace();
			} 
			catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}

}

—— Customer.java ——

package com.newthinktank;

import java.io.Serializable;

// NEW Add street, city, state, zipcode, email, password

public class Customer implements Serializable{
	private static final long serialVersionUID = 1L;
	private String fName;
	private String lName;
	private String street;
	private String city;
	private String state;
	private String zipcode;
	private String email;
	private String password;
	private String phone;
	
	public Customer() {
		this.fName = "";
		this.lName = "";
		this.street = “";
		this.city = "";
		this.state = "";
		this.zipcode = “";
		this.email = "";
		this.password = "";
		this.phone = "";
	}
	
	public Customer(String fName, String lName, String street,
			String city, String state, String zipcode,
			String email, String password, String phone) {
		this.fName = fName;
		this.lName = lName;
		this.setStreet(street);
		this.setCity(city);
		this.setState(state);
		this.setZipcode(zipcode);
		this.setEmail(email);
		this.setPassword(password);
		this.phone = phone;
	}
	
	public String getfName() {
		return fName;
	}
	public void setfName(String fName) {
		this.fName = fName;
	}
	public String getlName() {
		return lName;
	}
	public void setlName(String lName) {
		this.lName = lName;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}

	public String getStreet() {
		return street;
	}

	public void setStreet(String street) {
		this.street = street;
	}

	public String getCity() {
		return city;
	}

	public void setCity(String city) {
		this.city = city;
	}

	public String getState() {
		return state;
	}

	public void setState(String state) {
		this.state = state;
	}

	public String getZipcode() {
		return zipcode;
	}

	public void setZipcode(String zipcode) {
		this.zipcode = zipcode;
	}

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}
	
}

CREATE TABLE customer(
fname VARCHAR(30) NOT NULL,
lname VARCHAR(30) NOT NULL,
street VARCHAR(50) NOT NULL,
city VARCHAR(30) NOT NULL,
state VARCHAR(2) NOT NULL,
zipcode VARCHAR(10) NOT NULL,
email VARCHAR(30) NOT NULL,
password VARCHAR(20) NOT NULL,
phone VARCHAR(20) NOT NULL, 
cust_id INT UNSIGNED NOT NULL AUTO_INCREMENT PRIMARY KEY);

Leave a Reply

Your email address will not be published. Required fields are marked *