Personal notes on Java
For other technologies like HTML, CSS, .NET, PHP, etc. check my other blog

NOTE: Deprecated! JSP+Servlet has been replaced by JSF+facelets technologies

It was replaced by JSF Facelets in the new JavaEE 6 tutorial. This official tutorial states:
The term Facelets refers to the view declaration language for JavaServer Faces technology. JavaServer Pages (JSP) technology, previously used as the presentation technology for JavaServer Faces, does not support all the new features available in JavaServer Faces 2.0. JSP technology is considered to be a deprecated presentation technology for JavaServer Faces 2.0. Facelets is a part of the JavaServer Faces specification and also the preferred presentation technology for building JavaServer Faces technology-based applications.
Some opinions:

In the same way you may now use stateful session beans to store client state, read some opinions:




JSP Tips:

  • Your servlet container (i.e., GlassFish) converts JSP pages into servlets before running them as part of a project [1]. In NetBeans you can view the generated servlet for a JSP page by right-clicking the page node in the Projects window and choosing View Servlet. Of course, you first need to run the project so that the servlet is generated. Taking the index.jsp file as an example, when you choose View Servlet, the IDE displays a read-only copy of the generated servlet, index_jsp.java, in the editor. The servlet exists on the server at: <gf-install-dir>/glassfish/domains/domain1/generated/jsp/AffableBean/org/apache/jsp/index_jsp.java

POST vs GET

Download sample application PostGetTest (Netbeans project - JavaEE Web Application).
Common knowledge:
  • When you write a URL in the browser or click a link in a page the browser sends a GET request to the server;
  • If you submit a URL with a query string that specifies values for the form fields it will automatically complete the form fields (it doesnt matter if the form is using method GET or POST);
    ex1: https://www.google.com/?q=sometext
    ex2: (test with this application) http://localhost:8080/PostGetTest/teste?name=hello&age=world
  • Remember that the forms attribute action="" means that the form will submit to the same page where the form resides;
  • When you click a button in a form the browser can either send a GET or a POST request to the server, depending on the forms "method" configuration (if method="get" or method="post")
Things to test with this application:
  • Check the server log: This app uses a servlet that acts has a controller (in MVC). This servlet (Controller.java) prints to the server log if the request is of type GET or POST.
  • Manually edit "thetestpage.jsp" and experiment changing the form "method" attribute between "get" and "post". Compile and deploy to test changes
     Note that when using GET, the form will post the forms fields has a querystring (ex: name=hello&age=world&hiddenVar=someValue)

Notes:
  • access form parameters in JSP, ex.: <input type="text" name="name" value="${param.name}" />
  • access form parameters in a Servlet, ex.: request.getParameter("name") 

Jsp Notes

NOTE:
Much of the information from here on-words is just a reminder for old JSP syntax (prior to JSP 2.0) and is already deprecated! 

Its just a reminder for the old JSP syntax since there's a lot of legacy systems out there.

When programming in newer versions of JSP (2.0) you should access beans through the EL (Expression language) so that your views have only declarative code, i.e. they're absent of any java code (the logic should be in servlets and beans).

A better approach with JSP 2.0 is using the "MVC approach" (aka "Model 2 approach"): look it up in the servlets section from the side bar ---->

All the information that follows, but also the Model 2/MVC approach, can be found on this great JSP tutorial

The Need for JSP

With servlets, it is easy to:
– Read form data
– Read HTTP request headers
– Set HTTP status codes and response headers
– Use cookies and session tracking
– Share data among servlets
– Remember data between requests
– Get fun, high-paying jobs

But, it sure is a pain to:
– Use those println statements to generate HTML
– Maintain that HTML

The JSP Framework
Idea:
– Use regular HTML for most of page
– Mark servlet code with special tags
– Entire JSP page gets translated into a servlet (once), and servlet is what actually gets invoked (for each request)

Benefits of JSP

Although JSP technically can’t do anything servlets can’t do, JSP makes it easier to:
– Write HTML
– Read and maintain the HTML

JSP makes it possible to:
– Use standard HTML tools such as DreamWeaver
– Have different members of your team do the HTML layout than do the Java programming

JSP encourages you to
– Separate the (Java) code that creates the content from the (HTML) code that presents it

Higher-Level Alternative to JSP: JSF 2

Servlets and JSP
– Well-established standard
– Used by google.com, ebay.com, walmart.com, and thousands of other popular sites
– Relatively low level by today’s standards

JSF (JavaServer Faces) Version 2
– Now an official part of Java EE 6
– Higher-level features: integrated Ajax support, page templating, third-party rich component libraries, etc.
– Not yet as widely used, but recommended for many or most new projects
Covered here

Design Strategy: Limit Java Code in JSP Pages
You have two options:
– Put 25 lines of Java code directly in the JSP page
– Put those 25 lines in a separate Java class and put 1 line in the JSP page that invokes it

Comments in JSP
<%-- Comment --%>
These are not sent to client

Types of Scripting Elements

Expressions
– Format: <%= expression %>
– Evaluated and inserted into the servlet’s output.
I.e., results in something like out.print(expression)
Example:

Current time: <%= new java.util.Date() %>
Your hostname: <%= request.getRemoteHost() %>


Scriptlets
– Format: <% code %>
– Inserted verbatim into the servlet’s _jspService method (called by service)
Example:

<% String queryData = request.getQueryString(); %>
Attached GET data: <%= queryData %>
<% response.setContentType("text/plain"); %>

You can use Scriptlets to Make Parts of the JSP File Conditional
Example:
<% if (Math.random() < 0.5) { %>
    Have a <B>nice</B> day!
<% } else { %>
   Have a <B>lousy</B> day!
<% } %>


Declarations
– Format: <%! code %>
– Inserted verbatim into the body of the servlet class, outside of any existing methods
Example:
<%! private int someField = 5; %>
<%! private void someMethod(...) {...} %>
and after the declaration you can call them anywhere on the jsp page using expressions like:
<%= someMethod() %>

Note: Fields are clearly useful. For methods, it is usually better to define the method in a separate Java class.

JSP/Servlet Correspondence

Original JSP:
<H1>A Random Number</H1>
<%= Math.random() %>

Representative resulting servlet code (auto-generated from the JSP):
public void _jspService(HttpServletRequest request,
        HttpServletResponse response)
        throws ServletException, IOException {
    response.setContentType("text/html");
    HttpSession session = request.getSession();
    JspWriter out = response.getWriter();
    out.println("<H1>A Random Number</H1>");
    out.println(Math.random());
    ...
}

Predefined Variables (each one corresponding to similar ones used in servlets)


variable nameDescription
requestThe HttpServletRequest (1st argument to service/doGet)
responseThe HttpServletResponse (2nd arg to service/doGet)
outThe Writer (a buffered version of type JspWriter) used to send output to the client
sessionThe HttpSession associated with the request (unless disabled with the session attribute of the page directive)
applicationThe ServletContext (for sharing data) as obtained via getServletContext()

Using Beans in JSP [2]

Build a new bean

<jsp:useBean 
id="beanName" 
class="package.Class" />
(Purpose: Allow instantiation of Java classes without explicit Java programming)
NOTES:
<jsp:useBean 
id="book1" 
class="coreservlets.Book" />

can be thought of as equivalent to the scriptlet
<% coreservlets.Book book1 = new coreservlets.Book(); %>

But jsp:useBean has two additional advantages:
 - It is easier to derive object values from request parameters
 - It is easier to share objects among pages or servlets
Beans must always be in packages!

NOTE:
the <jsp:usebean> tag is JSP 1.2, in newer versions of JSP, and in a MVC context, its more common to create the beans in a Servlet, store them in the required scope (page, request, application or session) and then access the values in the jsp trough  EL to render the information.
Example:
Servlet
Customer myCustomer = ...;
request.setAttribute("customer", myCustomer);
RequestDispatcher dispatcher =  
    request.getRequestDispatcher
      ("/WEB-INF/SomePage.jsp");
dispatcher.forward(request, response);

JSP 2.0
${customer.firstName}

JSP 1.2
<jsp:useBean
    id="customer"
    type="somePackage.Customer"
    scope="request" />
<jsp:getProperty
    name="customer"
    property="firstName"/>


Sharing beans

The scope attribute of the <jsp:usebean> tag lets you share beans in 4 different ways:
Ex.: <jsp:useBean id="foo" class="…" scope="application"/>

Values of the scope Attribute:
valuedescription
pageThis is the default value. Unshared (page-scoped) beans. Bean object should be placed in the PageContext object for the duration of the current request. Methods in same servlet can access bean.
applicationData stored in the servlet context is visible to all users and all pages in the application. Rarely used.
Application-scoped (i.e., ServletContext-scoped) beans. Bean will be stored in ServletContext (available through the application variable or by call to getServletContext()). ServletContext is shared by all servlets in the same Web application (or all servlets on server if no explicit Web applications are defined). Access the bean later: Use jsp:getProperty in a request that does not include request parameters and thus does not invoke jsp:setProperty. Whether this request is from the same client or a different client (regardless of the session timeout), the previously modified value is seen.
sessionData stored in the request is visible to the servlet and to the page the servlet forwards to. Data can be seen on other pages or later in time if it is the same user. Data cannot be seen by other users. Moderately common.
Session-scoped beans Bean will be stored in the HttpSession object associated with the current request, where it can be accessed from regular servlet code with getAttribute and setAttribute, as with normal session objects. Access the bean later: Use jsp:getProperty in a request that does not include request parameters and thus does not invoke jsp:setProperty. If this request is from the same client (within the session timeout), the previously modified value is seen. If this request is from a different client (or after the session timeout), a newly created bean is seen.
requestData stored in the request is visible to the servlet and to the page the servlet forwards to. Data cannot be seen by other users or on other pages. Most common scope.
Bean object should be placed in the ServletRequest object for the duration of the current request, where it is available by means of getAttribute

Conditional Bean Operations


Bean conditionally created:

  • jsp:useBean results in new bean being instantiated only if no bean with same id and scope can be found.
  • If a bean with same id and scope is found, the preexisting bean is simply bound to variable referenced by id.


Bean properties conditionally set

  • <jsp:useBean ... /> replaced by <jsp:useBean ...>statements</jsp:useBean>
  • The statements (jsp:setProperty elements) are executed only if a new bean is created, not if an existing bean is found.

Ex.:
<jsp:useBean id="counter"
    class="coreservlets.AccessCountBean"
    scope="application">
    <jsp:setProperty name="counter"
        property="firstPage"
        value="SharedCounts1.jsp" />
</jsp:useBean>

Setting bean properties

<jsp:setProperty> tag: this element modifies a bean property (i.e., calls a setBlah method).
Ex.:
<jsp:setProperty 
name="book1" 
property="title" 
value="Core Servlets and JavaServer Pages" />

is equivalent to the following scriptlet
<% book1.setTitle("Core Servlets and JavaServer Pages"); %>


You can set properties in many different ways:

  • using jsp expressions directly:
    <jsp:setProperty
    name="myBean" 
    property="discountCode" 
    value="<%= discountCode %>" /> 
  • associating individual properties with Input Parameters (value should come from specified request parameter, i.e. the form's input names):
    <jsp:setProperty
    name="myBean" 
    property="itemID" 
    param="itemID" /> 
  • associate all properties with input parameters (Use "*" for the value of the property attribute of jsp:setProperty to indicate that Value should come from request parameter whose name matches property name):
    <jsp:setProperty 
    name="myBean" 
    property="*" />

    Note: This is extremely convenient for making "form beans" - objects whose properties are filled in from a form submission. You can even divide the process up across multiple forms, where each submission fills in part of the object.

Accessing Bean properties

This element reads and outputs the value of a bean property.
Ex.:
<jsp:getProperty 
name="book1" 
property="title" />

is equivalent to the following JSP expression
<%= book1.getTitle() %>
todo
todo

References

[1] - The NetBeans E-commerce Tutorial - Connecting the Application to the Database
[2] - Using JavaBeans Components in JSP Documents

Sem comentários:

Enviar um comentário