JSP basics
JSP Scripting Elements:
- JSP expression: Object(new String("adf")), Math expression(3 * 4), boolean(4 < 5)
- JSP Scriptlet: insert 1 to many lines of java code; use out.println(...) to include content in the page. this would return the code to HTML page. So for example: "<br/> I really Iuv2code: ", do not forget the <br/> HTML tags.
- JSP Declaration: Declare a method in the JSP page. And then you can use this method in other place in JSP page.
best practice:
Both for JSP Scriptlet and JSP Declaration, you should minimize the number of lines in those modules. Refactor this into a separate Java class, and make use of MVC.
how to implement the above best practice?
call Java Class from JSP
create java package in the java resources / src, establish a java file, then in the JSP file, we can invoke the method:
fun: <%= com.luv2code.jsp.FunUtils.makeItLower("FUN FUN FUN") %> or <%@ page import="com.luv2code.jsp.FunUtils, java.util.ArrayList" %> fun: <%= FunUtils.makeItLower("FUN FUN FUN") %>
JSP built-in objects
- request / response / out/ session / application 直接用
- eg. <%= request.getHeader("User-Agent") %> -> information about the browser
- eg. <%= request.getLocale() %> -> information about the language
how to include files in the JSP?
<jsp:include page="my-header.html"/>
<jsp:include page="my-footer.jsp"/>
Reading HTML forms with JSP (form tag)
- how to read basic HTML forms with JSP
first way:
HTML file:
First name: <input type="text" name="firstName" />
Last name: <input type="text" name="lastName" />
JSP file:
The student is confirmed:
<%= request.getParameter(“firstName”) %> <%= request.getParameter(“lastName”) %>
alternative way: (preferred one)
The student is confirmed: ${param.firstName} ${param.lastName}
- Dropdown list (select tag) 下拉单选
<select name="country"> <!-- select tag for dropdown list -->
<option>Brazil</option>
<option>France</option>
<option>Germany</option>
<option>India</option>
<option>Turkey</option>
<option>United Kingdom</option>
<option>United States of America</option>
</select>
The student's country: ${param.country}
- radio button (input type="radio" ... ) 单选
HTML file:
<input type="radio" name="favoriteLanguage" value="Java"> Java
...
JSP file:
The student's favorite programming language: ${param.favoriteLanguage} // param.name
- check boxes (input type="checkbox" ... ) 多选
HTML file:
<input type="checkbox" name="favoriteLanguage" value="Java"> Java
...
JSP file: // pay attention: different from previous one
String[] langs = request.getParameterValues("favoriteLanguage");
...
note: <!-- ...--> is the comment of the HTML
<!-- display list of "favoriteLanguage" -->
<ul>
<%
String[] langs = request.getParameterValues("favoriteLanguage");
if (langs != null) { // pay attention: should check if customer didn't check any option.
for (String tempLang : langs) {
out.println("<li>" + tempLang + "</li>");
}
}
%>
</ul>
note: "ul" is short for "unordered list" "ol" is short for "ordered list", they are both used together with li tag to list some things.
State Management with JSP
difference between sessions and cookies
Most modern sites use the second approach, i.e. saving the identifier in a Cookie instead of passing it in a URL (which poses a security risk). Translating that to Web Servers: The server will store the pertinent information in the session object, and create a session ID which it will send back to the client in a cookie. When the client sends back the cookie, the server can simply look up the session object using the ID. So, if you delete the cookie, the session will be lost.
- session tracking (server-side files)
List<String> items = new ArrayList<>();
session.setAttribute(“myToDoList”, items);
List<String> myStuff = (List<String>)session.getAttribute(“myToDoList”);
getId(): return String // return the id of the session
invalidate(): void // clear all the session information
<!-- step 1: create html form -->
<form action="todo-demo.jsp"> // point to the file itself
Add new item: <input type="text" name="theItem" />
<input type="submit" value="Submit" />
</form>
<!-- step 2: add new item to "to do" list -->
<%
// get the to do items from the session
List<String> items = (List<String>) session.getAttribute("myToDoList");
// if the to do items doesn't exist, then create a new one
if (items == null) {
items = new ArrayList<String>();
session.setAttribute("myToDoList", items);
}
// see if there is form data to add
String theItem = request.getParameter("theItem");
if (theItem != null && theItem.length() != 0) {
items.add(theItem);
}
%>
<!-- step 3: display all "to do" item from session -->
<hr>
<b>To List Items:</b> <br/>
<ol>
<%
for (String temp : items) {
out.println("<li>" + temp + "</li>");
}
%>
</ol>
PageContext has a set of attributes that are different from the Session object.
The attributes set on PageContext are only available for a given page. The attributes are not available to other pages or servlets in the application.
Session attributes are created per each user's session. The session attributes are unique to a given session id. Session attributes are available to other pages and servlets in the application for a given session id.
- Cookie (client-side files)
Cookie class defined in package:javax.servlet.http
Cookie is simply a key/value pair and Browser will only send cookies that match the server’s domain name.
create cookie:
<html>
<head>
<title>Confirmation</title>
</head>
<%
// read form data
String favLang = request.getParameter("favoriteLanguage");
// create the cookie
Cookie theCookie = new Cookie("myApp.favoriteLanguage", favLang);
// set the life span total number of seconds
theCookie.setMaxAge(60*60*24*365); // for one year
// send cookie to the browse
response.addCookie(theCookie);
%>
<body>
Thanks! we set your favorite language to: ${param.favoriteLanguage}
<br/>
<br/>
<a href="cookies-homepage.jsp"></a>
</body>
</html>
read cookie:
<html>
<body>
<h3>Training Portal</h3>
<!-- read the favorite programming language cookie -->
<%
// the default ... if there are no cookies
String favLang = "Java";
// get the cookies from the browser request
Cookie[] theCookies = request.getCookies();
// find our favorite language cookie
if (theCookies != null) {
for (Cookie t : theCookies) {
if ("myApp.favoriteLanguage".equals(t.getName())) {
favLang = t.getValue();
break;
}
}
}
%>
<!-- now show a personalized page .. use -->
<h4>New Books for <%= favLang %></h4>
<ul>
<li>balasdasdf</li>
<li>balasdasdf</li>
<li>balasdasdf</li>
</ul>
<hr> // pay attention: a horitontal line
<a href="cookies-personalize-form.html">Personalize this page</a>
</body>
</html>
think further: How to deal with the situation where cookie values exist whitespace?
Basically, with Version 0 cookies, values should not contain white space, brackets, parentheses, equals signs, commas, double quotes, slashes, question marks, at signs, colons, and semicolons. Empty values may not behave the same way on all browsers. To support MSIE as well, you really need to URL-encode and URL-decode the cookie value yourself if it contains possibly characters which are invalid for version 0.
JSP Tags --> JSP Standard Tag Library (JSTL)
Oracle create a specification for standard tags
- Core
- Message Formatting I18N
- Function
- XML
JSTL setup and a simple test
- go to website, and download the tag library, and copy them to the project/WebContent/WEB-INF/lib/
- oracle tag tutorial
declare the directive in the beginning: <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %> how to use: <c:set var="stuff" value="<%= new java.util.Date()%>" /> Time on the server is ${stuff}
- how to download a jar from maven directly without any scripts
Note: This answer is for downloading the jars directly from maven without any scripts [That is how Google directed me here] Assuming mvn dependency is like this: <dependency> <groupId>com.zaxxer</groupId> <artifactId>HikariCP</artifactId> <version>2.4.7</version> </dependency> Goto http://search.maven.org and search for g:"com.zaxxer" AND a:"HikariCP" AND v:"2.4.7" (simply searching for HikariCP also works. You may need to select the appropriate GroupId and Version from the results) In the Search Results -> Download column, you should see: jar javadoc.jar sources.jar available for direct download
JSTL core
- looping with forEach
<% // just create some sample data ... normally provided by MVC String[] cities = {"Mumbai", "Singapore", "Philadelphia"}; pageContext.setAttribute("myCities", cities); %> <body> <c:forEach var="tempCity" items="${myCities}"> ${tempCity} <br/> </c:forEach> </body>
:building a HTML table
<table border="1"> <tr> <th>First Name</th> <th>Last Name</th> <th>Gold Customer</th> </tr> <c:forEach var="tempStudent" items="${myStudents}"> <tr> <td>${tempStudent.firstName}</td> <td>${tempStudent.lastName}</td> <td> ${tempStudent.goldCustomer}</td> </tr> </c:forEach> </table>
- note that, An HTML table is defined with the<table>tag. Each table row is defined with the<tr>tag. A table header is defined with the<th>tag. By default, table headings are bold and centered. A table data/cell is defined with the<td>tag
other tag: JSTL if tag (no else if)
simple if expression, but no else if ....
<td>
<c:if test="${tempStudent.goldCustomer}">
Special Discount
</c:if>
<c:if test="${not tempStudent.goldCustomer}">
-
</c:if>
</td>
other tag: JSTL choose tag similar to the switch expression. and
<c:choose>
<c:when test="${tempStudent.goldCustomer}">
Special Discount
</c:when>
// can add other when...
<c:otherwise>
-
</c:otherwise>
</c:choose>