JSP

Preface

All tags are case sensitive. A pair of single quotes is equivalent to a pair of double quotes. Spaces are not allowed between an equals sign and an attribute value.

The elements in a JSP page can be expressed in JSP syntax or XML syntax but JSP and XML syntax cannot be mixed within a page.

Actions (or Tags)

Actions provide JSP runtime behavior. JSP Actions consist of a typical (XML-based) prefix of "jsp" followed by a colon, followed by the action name followed by one or more attribute parameters.

Directives

While actions provide runtime behavior, with Directives you tell the JSP engine to create features in the JSP before it is assembled. For example this is a page directive: <%@page language="java"%>

Scripting (Scriptlets, Declarations and Expressions)

Scripting incorporates actual Java code directly into the generated JSP Servlet. So, scripting acts very similar to a directive - modifying what goes into the JSP Servlet. Since a scripting creates code directly, it could have been called the "direct directive." Or maybe the "code directive." But it isn't. It's called "scripting." There are three forms of scripting: scriptlets, declarations, and expressions. A scriptlet looks like this: <% Some Java code ; %>

Summary

Name Desc Syntax Example
comments Documents the JSP page but is not inserted into the response <%— comment — %> <%— This comment will not be included in the response —%>
Declaration Declares a variable or method valid in the scripting language used in the JSP page. You must end the declaration with a semicolon (the same rule as for a Scriptlet, but the opposite of an Expression) <%! declaration;%> <%! Circle a = new Circle(2.0); %>
Expression Contains an expression valid in the scripting language used in the JSP page that is evaluated, converted to a String, and inserted into the response where the expression appears in the JSP page. <%= expression %> <input type="hidden" name="message" value="<%= request.getParameter("message")%>" />
Scriptlet Contains a code fragment valid in the page scripting language. <% code fragment %> <% String name = null;%>
Include Directive Includes a static file in a JSP page. An include directive inserts a file of text or code in a JSP page at translation time, when the JSP page is compiled. The include process is static. The relative URL is just the path segment of an URL, without a protocol, port, or domain name. <%@ include file="relativeURL" %> <%@ include file="date.jsp" %>
Page Directive Defines attributes that apply to an entire JSP page page and any of its static include files.The page directive does not apply to any dynamic resources. <%@ page [ language="java" ] … %> <%@ page import="java.util.*, java.lang.*" %> <%@ page buffer="5kb" autoFlush="false" %>
Taglib Directive Defines a tag library and prefix for the custom tags used in the JSP page. <%@ taglib {uri="URI" | tagdir="/WEB-INF/tags[/subdir]+"} prefix="tagPrefix" %> <%@ taglib uri="http://www.jspcentral.com/tags" prefix="public" %> <public:loop> … </public:loop>
<jsp:include> Includes a static or dynamic file or the result from another web component. <jsp:include page="{relativeURL | '${' Expression '}' | <%= expression %>}" … </jsp:include> <jsp:include page="scripts/login.jsp" />
<jsp:useBean> It locates or instantiates a JavaBeans component. It first attempts to locate an instance of the bean. If the bean does not exist then it instantiates it from a class or serialized template. <jsp:useBean id="cart" scope="session" class="session.Carts" />
<jsp:setProperty> sets the value of one or more properties in a bean, using the bean's setter methods. You must declare the bean with <jsp:useBean> before you set a property value <jsp:setProperty name="mybean" property="username" value="Steve" /> OR use this to copy all: <jsp:setProperty name="helperBean" property="*"/>

Upload File

<form method="post" action="fileManager.htm?method=upload" ENCTYPE="multipart/form-data">
    <input type="file" name= "uploadFile"><br/>
    New Name: <input type="text" name= "filename">
    <input type="submit" value="Upload">
</form>
 
//This code is from spring but can be change to a normal servlet easily:
 
public ModelAndView upload(HttpServletRequest request, HttpServletResponse response) throws Exception {
    MultipartHttpServletRequest reqt = (MultipartHttpServletRequest)request;  
        MultipartFile file = reqt.getFile("uploadFile");  
 
        log.debug("File size = " + file.getSize());
        log.debug("File name = " + file.getOriginalFilename());
 
        if(file != null) {  
 
            File dest = new File(file.getOriginalFilename());
            file.transferTo(dest);
 
        }  
    return new ModelAndView("uploadPhoto");
}

Show a photo (coming from a Servlet) on JSP

You can point the "src" attribute of "img" tag to point to your servlet:

<img src="photoManager.htm?method=getImage"/>

Where the Servlet looks like this:

public void getImage(HttpServletRequest request, HttpServletResponse response) throws Exception {
        //first we need to read the file to an array
    File file = new File("c:/LOGO.JPG");
    InputStream is = new FileInputStream(file);
 
        // Get the size of the file
        long length = file.length();
 
        if (length > Integer.MAX_VALUE) {
            // File is too large
        }
 
        // Create the byte array to hold the data
        byte[] bytes = new byte[(int)length];
 
        // Read in the bytes
        int offset = 0;
        int numRead = 0;
        while (offset < bytes.length
               && (numRead=is.read(bytes, offset, bytes.length-offset)) >= 0) {
            offset += numRead;
        }
 
        // Ensure all the bytes have been read in
        if (offset < bytes.length) {
            throw new IOException("Could not completely read file "+file.getName());
        }
 
        // Close the input stream and return bytes
        is.close();
 
        // conversion to array is done now
    response.setContentType("image/jpeg");
    response.setContentLength(bytes.length);
    response.getOutputStream().write(bytes);
    response.flushBuffer();
}

Submit Checkboxes

<input type="checkbox" name="selectedPromos" value="${p.id}"/> ${p.displayName}
 
and in the code:
String selectedPromoId[] = request.getParameterValues("selectedPromos");

Pagination

Integer pages = (Integer)request.getAttribute("noOfPages");
String catId = request.getParameter("categoryId");
Integer curr = (Integer)request.getAttribute("curr");
 
for (int i=1; i<= pages ; i++){
    if(i == curr.intValue()){
    %>    <c:out value="<%=i%>"/> <%
    }else{
%>
 
    <a style="font-weight: bold;" href="showAd.htm?method=showAdsForCategoryId&categoryId=<%=catId%>&page=<%=i%>"><c:out value="<%=i%>"/></a>
 
<%}}%>

JSP 2.0 Reference

http://java.sun.com/products/jsp/syntax/2.0/syntaxref20.html

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License