In 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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 |
—— 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