JSP

java

http://download.oracle.com/docs/cd/E13222_01/wls/docs90/webapp/configurewebapp.html - Creating and Configuring Web Applications
http://www.tutorialspoint.com/jsp/
https://spring.io/blog/2012/10/30/spring-mvc-from-jsp-and-tiles-to-thymeleaf

Debug

<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.Properties" %>
<%@ page import="javax.servlet.ServletContext" %>
<%@ page import="oracle.jdbc.driver.OracleDriver" %>
<%!
private String getConfigurationValue(String keyName) throws Exception {
    ServletContext servctxt = getServletContext();
    String fileName = servctxt.getRealPath("plugins\\CustomTask\\WEB-INF\\classes\\adminCredential.properties");

    Properties properties = new Properties();
    properties.load(new FileInputStream(new File(fileName)));
    return properties.getProperty(keyName);
}
%>
<%= auditLogCheck() %>

<%= new java.util.Date() %>

<%
  out.println(String.valueOf( date ));
%>

<%
  out.println( request.getRemoteHost() );
%>

// Conditional:
<% if (condition1) { %>
    ...HTML...
<% } else if (condition2) { %>
    ...HTML...
<% } else { %>
<% } %>

// Mixing scripts with HTML:
<%
  for ( int i = 0; i < n; i++ ) {
  %>
    <tr>
      <td>Number</td>
      <td><%= i + 1 %></td>
    </tr>
    <%
  }
%>

// Include another JSP file:
<%@ include file="hello.jsp" %>
<jsp:include page="hello.jsp"/>

// Comment:
<%-- 
    the scriptlet is now commented out
    <%
        out.println("Hello World");
    %>
--%>
<%-- JSP comment --%>

<%= request.getSession().getId() %>
<%= request.getSession().isNew() %>
<%=new Date(request.getSession().getCreationTime())%>
<%=new Date(request.getSession().getLastAccessedTime())%>
<%= request.getAttribute("name")%>

<%
request.getSession().getAttribute("Books");
List<string> listOfBooks = (List<string>) request.getSession().getAttribute("Books");
if (listOfBooks == null) {
    listOfBooks = new ArrayList<string>();
}
request.getSession().setAttribute("Books",listOfBooks);
%>

<%
  String name = request.getParameter("username");
  session.setAttribute("name",name);
%>

<jsp:useBean id="user" class="user.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>

<jsp:declaration>
    Statement stmt;
    Connection conn;
    String url = "jdbc:mysql://localhost:3306/";
</jsp:declaration>
<jsp:scriptlet>
<![CDATA[
    Class.forName("com.mysql.jdbc.Driver");
    conn = DriverManager.getConnection(url, "EastRiver", "EastRiver");
    stmt = conn.createStatement();
    stmt.executeUpdate("CREATE DATABASE articles");
    conn.close();
]]></jsp:scriptlet>
<jsp:expression> exception.getMessage() </jsp:expression>

// Implicit objects or methods:
request: HttpServletRequest
response: HttpServletResponse
session: HttpSession
out: JspWriter
application: ServletContext
config: ServletConfig
page: Object
pageContext: PageContext
_jspService
clone
destroy
doDelete

<jsp:include page="../menu.jspx"/>
<c:choose>
 <c:when test="${empty users}">
   Table is empty.
 </c:when>
 <c:otherwise>
  <table>
   <thead>
     <tr>
      <th> First Name </th>
      <th> Last name </th>
     </tr>
    </thead>
    <tbody>
    <c:forEach var="user" items="${users}">
    <tr>
      <td> <c:out value="${user.firstName}"/> </td>
      <td> <c:out value="${user.lastName}"/> </td>
    </tr>
    </c:forEach>
   </tbody>
 </table>
</c:otherwise>
</c:choose>
<jsp:include page="../footer.jspx"/>

What is JSP?

JSP abbreviates for Java Server Pages. Unlike a static HTML page, a Java Server Page is a dynamic web page, just like page generated by PHP, Perl, or any other computer language. You can take any existing HTML page and change its extension to ".jsp". After that you can embed JSP tags or Java code into your page to make it dynamic. If you wish to embed JSP tags or Java code into an existing HTML page (and keep the .html extension), you may have to re-configure your container.

<%@ page import="java.sql.*" %>
<%@ page import="java.io.*" %>
<%@ page import="java.util.Properties" %>
<%@ page import="javax.servlet.ServletContext" %>
<%@ page import="oracle.jdbc.driver.OracleDriver" %>
<%!
private String getConfigurationValue(String keyName) throws Exception {
    ServletContext servctxt = getServletContext();
    String fileName = servctxt.getRealPath("plugins\\CustomTask\\WEB-INF\\classes\\adminCredential.properties");

    Properties properties = new Properties();
    properties.load(new FileInputStream(new File(fileName)));
    return properties.getProperty(keyName);
}

private Connection getHistoryListDatabaseConnection() throws Exception {
    String url = getConfigurationValue("MSTR_HISTORY_DB_DATASOURCE_URL");
    String dbUsername = getConfigurationValue("MSTR_HISTORY_DB_DATASOURCE_USERNAME");
    String dbPassword = getConfigurationValue("MSTR_HISTORY_DB_DATASOURCE_PASSWORD");
    DriverManager.registerDriver(new oracle.jdbc.driver.OracleDriver());

    Properties connectionProps = new Properties();
    connectionProps.put("user", dbUsername);
    connectionProps.put("password", dbPassword);
    return DriverManager.getConnection(url, connectionProps);
}

private String auditLogCheck() {
    String sql = "SELECT COUNT(*) CNT FROM QUANTROS_AUDIT_LOG_LAST_RUN WHERE LAST_RUN_TIME_STAMP < SYSDATE - INTERVAL '3' HOUR";
    String result = "MSTR Audit Log check is OK";
    int cnt = 0;
    try {
        Connection conn = getHistoryListDatabaseConnection();
        PreparedStatement pstmt = conn.prepareStatement(sql);
        ResultSet rset = pstmt.executeQuery();
        while (rset.next()) {
            cnt = rset.getInt("CNT");
            if (cnt > 0) {
                break;
            }
        }
        if (cnt > 0) {
            result = "Something is wrong with the MSTRAuditLog job.";
        }
    } catch (Exception e) {
        StringWriter sw = new StringWriter();
        PrintWriter pw = new PrintWriter(sw);
        e.printStackTrace(pw);
        result = sw.toString();
    }
    return result;
}
%>
<%= auditLogCheck() %>

How can we implement conditional logic inside a JSP file?

<% if (condition1) { %>
    ...HTML...
<% } else if (condition2) { %>
    ...HTML...
<% } else { %>
<% } %>

How can we comment out a block of JSP?

To prevent JSP from executing a block of JSP or Java code, use the <%— … —%> construct:

<%-- 
    the scriptlet is now commented out
    <%
        out.println("Hello World");
    %>
--%>

How can we evaluate a JSP file and capture its output into a string?

ServletContext context = request.getSession().getServletContext();
String url = response.encodeRedirectURL("/email.jsp");
RequestDispatcher dispatcher = context.getRequestDispatcher(url);

/* must use include. With forward the RequestDispatcher seems to hold an internal state
   which prevents to do a forward after this to return to the webclient */
dispatcher.include(request, wrapper);
String email = new String(wrapper.getOutput());
System.out.println("email:" + email);

/* ... add other stuff like returning something to the webclient ... */

-------------------------------
BufferedHttpResponseWrapper source
-------------------------------

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.PrintWriter;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

/**
 * This class wraps a HttpServletResponse with a buffered output.
 * You can use this to forward or include a Servlet or JSP page
 * and capture the output from it.
 * 
 * Use getOutput to get the output which was written to the response.
 * Only buffers the Writer. Not the OutputStream !!
 *  
 * @author Joost den Boer
 */
public class BufferedHttpResponseWrapper extends HttpServletResponseWrapper {

    PrintWriter writer = null;
    ByteArrayOutputStream baos = null;

    /**
     * Constructor for BufferedHttpResponseWrapper.
     * Create a new buffered Writer
     * 
     * @param response The response object to wrap
     */
    public BufferedHttpResponseWrapper(HttpServletResponse response) {
        super(response);
        baos = new ByteArrayOutputStream();
        writer = new PrintWriter(baos);
    }

    /**
     * Return the buffered Writer
     *  
     * @see javax.servlet.ServletResponse#getWriter()
     */
    public PrintWriter getWriter() throws IOException {
        return writer;
    }

    /**
     * Return the output written to the Writer.
     * To get the output, the Writer must be flushed and closed.
     * The content is captured by the ByteArrayOutputStream.
     *  
     * @return
     */
    public String getOutput() {
        writer.flush();
        writer.close();
        return baos.toString();
    }
}

See http://www.codango.com/jsp/fnc/content-review/?id=5670110

How can we put something into the session?

request.getSession().setAttribute("key",value);

How can we work with session?

A session is an object associated with a visitor. Data can be put in the session and retrieved from it, much like a Hashtable.

Session ID: <%= request.getSession().getId() %>
Is it new: <%= request.getSession().isNew() %>
Session Create Date: <%=new Date(request.getSession().getCreationTime())%>
Session Access Date: <%=new Date(request.getSession().getLastAccessedTime())%>
request.getParamter("bookName");
request.getSession().getAttribute("Books");
List<string> listOfBooks = (List<string>) request.getSession().getAttribute("Books");
if (listOfBooks == null) {
    listOfBooks = new ArrayList<string>();
}
request.getSession().setAttribute("Books",listOfBooks);

<%
  String name = request.getParameter("username");
  session.setAttribute("name",name);
%>

How can we pass information from Java to JSP?

req.setAttribute("attributeName",  attributeValue);

<%
String attributeValue = request.getAttribute("attributeName");
%>

<%= attributeValue %>

What is the purpose of expression (<%= … %>)?

The character sequence <%= and %> enclose Java expression, which are evaluated at runtime.

Hello! The time is now <%= new java.util.Date() %>

What is the purpose of scriptlet (<% … %>)?

JSP also allows you to write blocks of Java code inside JSP. You do this by placing your Java code between <% and %> character sequence. This block of code is known as a "scriptlet". A scriptlet contains Java code that is executed every time the JSP is invoked.

<%
  // This is a scriptlet.  Notice that the "date" variable we declare here is
  // available in the embedded expression later on.
  System.out.println("Evaluating date now");
  java.util.Date date = new java.util.Date();
%>
Hello!  The time is now <%= date %>

In the above code, System.out.println output to the server log. This is a convenient way to do simple debugging.

How can a scriptlet generate HTML?

If a scriptlet wants to generate HTML, it can use a variable named "out". This variable does not need to be declared.

<%
  out.println(String.valueOf( date ));
%>

The "out" variable is of type javax.servlet.jsp.JspWriter.

How can we obtain information from the request?

The request variable is of type javax.servlet.http.HttpServletRequest. The request variable is used to obtain information from the request as sent by the browser. For instance, you can find out the IP address of the browser:

<%
  out.println( request.getRemoteHost() );
%>

How can we obtain information from the response?

The response variable can be used to affect the response being sent to the browser. For example, you can call response.sendRedirect( anotherUrl ); to send a response to the browser that it should load a different URL. This response will actually go all the way to the browser. The browser will then send a different request to "anotherUrl".

Can we mix scriptlets with HTML?

Yes.

<%
  for ( int i = 0; i < n; i++ ) {
  %>
    <tr>
      <td>Number</td>
      <td><%= i + 1 %></td>
    </tr>
    <%
  }
%>

The important thing to notice are how the %> and <% character sequences appear in the middle of the for loop, and let you drop back into HTML and then come back to the scriptlet. The concept is simple here. You can drop out of the scriptlet, write normal HTML, and get back into the scriptlet. Any control construct such as a "while" or a "for" loop, or an "if" expression will control the HTML also. If the HTML is inside a loop, it will be emitted once for each iteration of the loop.

What is the purpose of directives (<%@ … %>)?

It is possible to use the "import" statement in JSP but the syntax is a bit different from normal Java:

<%@ page import="java.util.*" %>
<%
  Date date = new Date();
%>

The first line in the above code is called a directive. This one is a "page directive". The page directive can contain a list of all imported packages. To import more than one item, separate the package names by comma:

<%@ page import="java.util.*,java.text.*" %>

How can we include the content of another JSP file?

The include directive is used to include the contents of another file. The included file can be HTML or JSP or anything else:

<%@ include file="hello.jsp" %>

What is the purpose of declaration (<%! … %>)?

The JSP that you write is turned into a class definition. All the scriptlets you write are placed inside a single method of this class. You can also add variable and method declaration to this class. You can then use these variables and methods from your scriptlets and expressions.

<%@ page import="java.util.*" %>
<%!
  Date theDate = new Date();
  Date getDate() {
    return theDate;
  }
%>
Hello!  The time is now <%= getDate() %>

The above code does not work. The date will be the same, no matter how often you reload the page. This is because these are declarations, and will only be evaluated once when the page is loaded! (Just as if you were creating a class and had variable initialization declared in it.)

Is it a good idea to use variables in a declaration?

No. In general, it is not a good idea to use variables in a declaration. JSP is usually run as multiple threads of one single instance. Different threads would interfere with variable access, because it will be the same variable for all of them. If you have to use variables in JSP, you should use synchronized access, but that hurts performance. In general, any data you need should go either in the session object or the request object.

Variables you declared inside scriptlets are fine, e.g. <% int i = 45; %> because these are declared inside the local scope and are not shared.

What is a JSP tag?

JSP tags is somewhat like HTML tags. JSP tags can have a start tag, a tag body, and an end tag. The start and end tags both use the tag name enclosed in < and > characters. The end tag starts with a / character after the < character. The tag names have an embedded colon (:) character in them. The part before the colon describes the type of the tag

If the tag does not require a body, the start and end can be conveniently merged together:

<some:tag/>

Tags can be of two types (loaded from an external tag library, or predefined tags). Predefined tags start with jsp: characters. For instance, jsp:include is a predefined tag that is used to include another page. We already seen the include directive. jsp:include tag is similar. But instead of loading the included file in the original file, it actually calls the included target at run-time. In practice, this is a simulated request rather than a full round-trip between the browser and server.

<jsp:include page="hello.jsp"/>

In order to use a tag library, we use the "taglib" directive to specify where our tag library reside:

<%@ taglib prefix="blx" uri="/blx.tld" %>

The "uri" specifies where to find the tag library description (definition). The "prefix" is unique for the tag library. This directive is saying that we will be using the tags in this library by starting them with 'blx:' prefix.

<%@ taglib prefix="blx" uri="/blx.tld" %>
<jsp:useBean id="user" class="user.UserData" scope="session"/>
<blx:getProperty name="user" property="*">

How can we process form?

The standard way of handling forms in JSP is to define a "bean". This is not a full Java bean. You just need to define a class that has field corresponding to each field in the form. The class must have "setters" and "getters" that match the names of the form fields. A "setter" method is a method that starts with "set" followed by the name of the form field. The first character of the field name is upper-cased. So if the field name is "email", its "setter" method must be "setEmail". Getter methods are defined similarly with "get" instead of "set". Note that the setter and getter methods must be public.

package user;
public class UserData {
  String username;
  String email;
  int age;
  public void setUsername( String value ) {
    username = value;
  }
  public void setEmail( String value ) {
    email = value;
  }
  public void setAge( int value ) {
    age = value;
  }
  public String getUsername() {
    return username;
  }
  public String getEmail() {
    return email;
  }
  public int getAge() {
    return age;
  }

After you defined the class, compile it and make sure it is available in the web-server's classpath. Note that we are using the package name "user", therefore, the file UserData.class must be placed in a folder name "user" under the classpath directory.

<jsp:useBean id="user" class="user.UserData" scope="session"/>
<jsp:setProperty name="user" property="*"/>

The userBean tag will look for an instance of "user.UserData" in the session. If the instance is already there, it will update the old instance. Otherwise, it will create a new instance of user.UserData, and put it in the session.

The setProperty tag will automatically collect the input data, match names against the bean method names, and place the data in the bean,

<jsp:useBean id="user" class="user.UserData" scope="session"/>
Name: <%= user.getUsername() %>

Notice that the same useBean tag is repeated. The bean is available as the variable named "user" of class "user.UserData". The data entered by the user is all collected in the bean.

How can we register a servlet?

With Java EE metadata annotations, the standard web.xml is now optional. The Servlet 2.5 specification states that annotations can be defined on certain web components, such as servlets, filters, listeners, and tag handlers. The annotations are used to declare dependencies on external resources. The container will detect annotations on such components and inject necessary dependencies before the component's life-cycle methods are invoked.

However, you can also define servlets as part of a web application entries in web.xml. The web.xml is located in the WEB-INF directory of your web application.

<servlet>
  <servlet-name>watermelon</servlet-name>
  <servlet-class>myservlets.watermelon</servlet-class>
  <init-param>
    <param-name>greeting</param-name>
    <param-value>Welcome</param-value>
  </init-param>
</servlet>
<servlet-mapping>
  <servlet-name>watermelon</servlet-name>
  <url-pattern>/fruit/summer/*</url-pattern>
</servlet-mapping>

Each web application has a default servlet. This default servlet can be a servlet that you specify. If you do not specify a default servlet, WebLogic Server use an internal servlet called the FileServlet.

How can we register a default servlet?

You can register any servlet as the default servlet. Writing your own default servlet allows you to use your own logic to decide how to handle a request that fall back to the default servlet. To set up a user-defined default servlet:

1. Defined your servlet as describe in "Configuring How a Client Accesses a Web Application"

2. Add a servlet-mapping with url-pattern = "/":

<servlet-mapping>
  <servlet-name>MyOwnDefaultServlet</servlet-name>
  <url-pattern>/myservlet/*</url-pattern>
</servlet-mapping>

3. If we still want the FileServlet to serve files with other extensions:

  • Define a servlet and give it a <servlet-name>, for example, myFileServlet
  • Define the <servlet-class> as weblogic.servlet.FileServlet.
  • Using the <servlet-mapping> element, map file extensions to the myFileServlet (in addition to the mappings for your default servlet). For example, if you want the myFileServlet to serve .gif files, map *.gif to myFileServlet

Note: The FileServlet includes the SERVLET_PATH when determining the source filename if the docHome parameter (deprecated) is not specified. As a result, it is possible to explicitly serve only files from specific directories by mapping the FileServlet to /dir/*, etc.

How can we write a simple HTTP Servlet?

import javax.servlet.*;
import javax.servlet.http.*;
import java.io.*;

public class HelloWorldServlet extends HttpServlet {
  public void service(HttpServletRequest req, HttpServletResponse res) throws IOException {
    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    out.println("<html><head><title>" + "Hello World" + "</title></head>");
    out.println("<body><h1>Hello World!</h1></body></html>");
  }
}

Implement a service() method. The main function of a servlet is to accept an HTTP request from a web browser, and return an HTTP response. This work is done by the service() method. Service methods include 'response' objects used to create output, and 'request' objects used to receive data from the client.

The doPost() and doGet() methods reply only to POST or GET requests. If you want to handle all request types from a single method, your servlet can simply implement the service() method. If you choose to implement the service() method, you cannot implement the doPost() or doGet() methods, unless you call super.service() at the beginning of the service() method.

The HTTP servlet specification describes other methods used to handle other request types. All of these methods are collectively referred to as 'service' methods.

All the service methods take the same number of arguments. An HttpServletRequest provides information about the request, and your servlet uses an HttpServletResponse to reply to the HTTP client. The service method looks like the following:

public void service(HttpServletRequest req, HttpServletResponse res) throws IOException {
}

The URL you use to call a servlet is determined by:

  1. the name of the web application containing the servlet
  2. the name of the servlet as mapped in web.xml

Request parameters can also be included in the URL used to call a servlet. Generally the URL for a servlet conforms to the following:

http://host:port/web-application-name/mapped-servlet-name?parameter

WebLogic Server provides a variety of services and APIs that you can use in your web applications. These services include Java Database Connectivity (JDBC) drivers, JDBC database connection pools, Java Messaging Service (JMS), Enterprise JavaBean (EJB), and Remote Method Invocation (RMI).

How can we configure Java Server Pages (JSPs)?

In order to deploy JSP files, we must place them in the root (or in a subdirectory below the root) of a web application. You define JSP configuration attributes in the <jsp-descriptor> element of the WebLogic-specific deployment descriptor (weblogic.xml). These attributes define the following functionality:

  • options for the JSP compilers
  • options for debugging
  • how often WebLogic Server checks for updated JSPs that need to be recompiled
  • character encoding
  • … see JSP Attribute Names and Values

How can we register JSP as a Servlet?

You can register a JSP as a servlet using the <servlet> element in web.xml. A servlet container maintains a map of servlets known to it. This map is used to resolve requests that are made to the container. Adding entries to this map is known as "registering" a servlet. You add an entries to this map by referencing a <servlet> element in web.xml through the <servlet-mapping> entry.

A JSP is a type of servlet. Registering a JSP is a special case of registering a servlet. Normally, JSPs are implicitly registered the first time you invoke them, based on the name of the JSP file. Therefore, myJSPfile.jsp would be registered as myJSPFile.jsp in the mapping table. You can implicitly register JSPs:

<servlet>
  <servlet-name>myFoo</servlet-name>
  <jsp-file>myJSPFile.jsp</jsp-file>
</servlet>
<servlet-mapping>
  <servlet-name>myFoo</servlet-name>
  <url-pattern>/main</url-pattern>
</servlet-mapping>

In the above example, we request the JSP with the name /main instead of the implicit name myJSPfile.jsp

Registering a JSP as a servlet allows you to specify the load order, initialization attributes, and security roles for a JSP, just as you would for a servlet.

How can we configure JSP tag libraries?

WebLogic Server lets you create and use custom JSP tags. Custom JSP tags are Java classes you can call from within a JSP page. To create custom JSP tags, you place them in a tag library and define their behavior in a tag library descriptor (TLD) file.

You make this TLD available to the web application containing the JSP by defining it in web.xml. It is a good idea to place the TLD file in the WEB-INF directory of your web application, because that directory is never available publicly.

In web.xml, you define a URI pattern for the tag library. This URI pattern must match the value in the taglib directive in your JSP pages. You also define the location of the TLD. For example, if the taglib directive in the JSP page is:

<%@ taglib uri="myTaglib" prefix="taglib" %>

and the TLD is located in the WEB-INF directory of your application, you would create the following entry in web.xml:

<taglib>
  <taglib-uri>myTaglib</taglib-uri>
  <taglib-location>WEB-INF/myTLD.tld</taglib-location>
</taglib>

You can also deploy a tag library as a .jar file

How can we configure the welcome page?

WebLogic Server allows you to create a page that is served by default if the requested URL is a directory. This feature can make your site easier to used, because the users do not have to type specific filename.

Welcome pages are defined at the web application level. If your server is hosting multiple web applications, you need to define welcome pages separately for each web application.

To define welcome pages, edit the web.xml:

<welcome-file-list>
  <welcome-file>/welcome.foo</welcome-file>
</welcome-file-list>

If you do not define welcome pages, WebLogic Server looks for index.html, index.htm, index.jsp and serves the first one it finds.

How can we customize HTTP error responses?

We can configure WebLogic Server to respond with your own custom web pages or other HTTP resources when particular HTTP errors or Java exception occur, instead of responding with the standard WebLogic Server error response pages.

We define custom error pages in the <error-page> element of web.xml.

How can we serve resource from the CLASSPATH with ClasspathServlet?

If you need to serve classes or other resources from the system CLASSPATH, or from the WEB-INF/classes directory of a web application, we can use a special servlet called the ClasspathServlet. The ClasspathServlet is useful for application that use applets or RMI clients and requires access to server-side classes. The ClasspathServlet is implicitly registered and available from any application.

The ClasspathServlet is always enabled by default. To disable it, set the ServerMBean parameter ClassPathServletDisabled to true.

The ClasspathServlet returns the classes or resources from the system CLASSPATH in the following order:

  1. WEB-INF/classes
  2. jar files under WEB-INF/lib/*
  3. system CLASSPATH

To serve a resource from the WEB-INF/classes directory of a web application, call the resource with a URL such as:

http://server:port/my-web-app/classes/my/resource/myClass.class

In this case, the resource is located in the following directory, relative to the root of the web application:

WEB-INF/classes/my/resources/myClass.class

Because ClasspathServlet serves any resources located in the system CLASSPATH, do not place resources that should not be publicly available in the system CLASSPATH.

Creating and Configuring Servlets

How can we establish database connection inside a JSP file?

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<%@ page errorPage="Error.jsp" %>
<%@ page import="java.sql.*" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
    <head>
        <title>BD</title>
    <style>
        * { font-size: 12px; font-family: Verdana }
    </style>
    </head>
    <body>
        <h2>BD</h2>
        <jsp:declaration>
            Statement stmt;
            Connection conn;
            String url = "jdbc:mysql://localhost:3306/";
        </jsp:declaration>
        <jsp:scriptlet>
        <![CDATA[
            Class.forName("com.mysql.jdbc.Driver");
            conn = DriverManager.getConnection(url, "EastRiver", "EastRiver");
            stmt = conn.createStatement();
            stmt.executeUpdate("CREATE DATABASE articles");
            conn.close();
        ]]></jsp:scriptlet>
        <jsp:expression> exception.getMessage() </jsp:expression>
    </body>
</html>

How can we get a request attribute from inside a JSP?

<%= request.getAttribute("name")%>

Why should we not have scriptlet code in our JSP?

It is just bad practice. Java code (business logic) should be located inside a servlet or a controller, and JSP should be used as view.

Why do we sometime create files with the .jspf extension?

The .jspf extension indicates that this is only a fragment of JSP, and is not a complete JSP file. The f abbreviate for fragment.

How can we include a JSP / JSPF file?

<%@ include file="common/header.jspf"%>

How can we import a JAR file so that we can use it in our JSP file?

<%@ page import=“java.util.List”%>

How can we include a JSP file into our current JSP file?

<%@ include file=“../common/header.jspf”%>

How can we comment out a block of code inside a JSP file?

<!-- HTML comment -->
<%-- JSP comment --%>

How can we display the value of a Java variable inside a JSP file?

<%= new Date().toString() %>
<%= request.getAttribute(“name”) %>

What is the syntax for JSP scriptlet?

<%
%>

What is the syntax for JSP expression scriptlet?

<%=
%>

What are the variables and methods that are available to our JSP page by default?

  1. request: HttpServletRequest
  2. response: HttpServletResponse
  3. session: HttpSession
  4. out: JspWriter
  5. application: ServletContext
  6. config: ServletConfig
  7. page: Object
  8. pageContext: PageContext
  9. _jspService
  10. clone
  11. destroy
  12. doDelete

These are known as implicit objects or methods, that are implicitly made available to the JSP scriptlets.

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