Monday 25 May 2015

OCEJWCD.- 7.Developing JSP pages

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification
7.1. Undestand the origins, benefits, and weaknesses of JSPs
  • JSP combines static HTML with dynamic content.
  • JSP contains the view separately from logic.
  • JSP are compiled as servlet when requested
  • Using tags java beans can be managed, without complex logic code.
  • Tag libraries can be customized
7.2. Describe JSP technology, the conversion of JSPs to servlets, and the lifecycle of JSPs

JSP lifecycle in detail in this post: ocewcd-2-introduction-to-java-server

7.3. Understand JSP scripting elements, declarations and directives

Directives:
-Page <%@ page ... %> instructions in the current JSP
-include <%@ include ... %> include a file during translation phase
-tab library <%@ taglib ... %> define custom JSP tags

7.4. Use JSP implicit variables
  • application -- servletContext
  • config -- servletConfig
  • exception -- Exception object
  • out -- PrintWriter
  • page -- this
  • request -- HttpServletRequest
  • response -- HttpServletResponse
  • session -- HttpSession
7.5. Understand and use jsp:tags


OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

Sunday 24 May 2015

OCEJWCD.- 6. More view facilities (part2)

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

6.4. Create and use arithmetic expressions in EL.
The expressions inside EL are evaluated at execution time and sent to the output stream.
Inside the brackets we can evaluate conditions or calculate an arithmetic result.

Examples: 
${3+7}  --> returns 10
${2*(5%3)} --> returns 4

Rules with EL
- EL is null friendly. In case of null or unknown values the page still displays.
- EL treats null value as "zero" in arithmetic expressions.
- EL treats null value as "false" in boolean expression.

6.5. Identify the need for iteration and selection in the view, and use JSTL tags to address those needs.
Example: Creating a servlet that adds a list of elements to the request. Then a list  iteration is displayed in the browser.

1) Include servlet declaration in deployment descriptor (web.xml)
  <servlet>
    <servlet-name>Listado</servlet-name>
    <servlet-class>example.Listado</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Listado</servlet-name>
    <url-pattern>/List</url-pattern>
  </servlet-mapping>

2) Define method get in servlet class 3) JSP using JSTL iteration Then writing the following url in the browser: http://localhost:8080/ExampleServlets/List a selection list is displayed:

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

Thursday 21 May 2015

OCEJWCD.- 6. More view facilities (part1)

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification
6.1. Understand the four data scopes.

The scopes in a JSP are four:
  • Page scope -- pageContext
  • Request scope -- request
  • Session scope -- session
  • Application scope -- application
Note: The scopes in a servlet are three: request(request), session(request.getSession()) and application(getServletContext()).

6.2. Understand and use EL dot and array access operators with Java Beans, arrays and collections.

EL (expression language) was introduced in JSP 2.0.  Some basics of EL are explained in this post:
ocewcd-3-implementing-mvc-design-part2

Features of EL:
  • There is not typecasting
  • Conversions are usually done implicitly
  • Double and single quotes are equivalent
  • Dot and array access operators
${object.property}     --> object can be a map or a bean
${object["property"]} --> object can be: map, bean, List or array. Inside the brackets is the key of the map, the attribute of the bean, the position of the list or array.

Example : to access property name from object user we can use these 3 different notations:
${user.name}
${user["name"]}
${user['name']}

More examples of EL (accessing bean and implicit variable):
6.3. Understand and use EL implicit objects.

EL Implicit objects:
  • pageScope - gets attribute from Page scope
  • requestScope  - get request attributes
  • sessionScope - get session object attributes
  • applicationScope - get application level attributes
  • param - servletRequest.getParameter()
  • paramValues - servletRequest.getParameterValues() 
  • header - get request header
  • headerValues - get request headers
  • cookie -  get Cookie objects
  • initParam - get context initialization parameters
  • pageContext - same as JSP pageContext
Examples:
${param.name}
${paramValues.name[0]} 
${header.host}

We can see in  detail how to access a parameter from a request (in a form that we want to submit). Then we can access the values using EL by param implicit object.
<form action="login.do" method="post">  
Enter user:<input type="text" name="user"/><br/><br/>  
Password  :<input type="password" name="password"/><br/><br/>  
<input type="submit" value="login"/>
User name is ${param.name}
User password is ${param.password}
See next post : More view facilities (part2)

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

Sunday 17 May 2015

OCEJWCD - 5.Container facilities for servlets and JSPs (part2)

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

5.3. Create and use context and init parameters
  • Application init parameters
The class that the container will use at application level is ServletContext.

Defining init parameters in deployment descriptor:
<context-param>
  <param-name>name1</param-name>
  <param-value>value1</param-value>
</context-param>

Retrieving init parameters:
getServletContext().getInitParameter("parameter1");

For the initialization process in an application the ServletContextListener can be defined (this code will run before the rest of the application for example to get the init parameters and create a database connection,..etc).
<context-param>
<param-name>name1</param-name>
<param-value>value1</param-value>
</context-param>
<listener>
  <listener-class>example.MyServletContextListener</listener-class>
</listener>

Example: The servletContextListener class will retrieve the init parameters, in this case a property "blogName", and then servletContext will be accessed to display the property.


This can be useful when we define properties as user, password, urls, driver and we want to create a database connection (at application level), and it will be perform before any servlet is initialized. It can be useful to access to properties file or other resources (IO operations) to retrieve global parameters.


  • Servlet init parameters
The class that the container will use to init the servlet is ServletConfig.

ServletConfig methods:
-Parameters: getInitParameter(String name), getInitParameterNames()
-Context : getServletContext()

To use init parameters there are 2 options:
  • By deployment descriptor
  • By annotations 
Note: In case of using both for the same parameters, the deployment descriptor will have precedence.
 <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>example.MyServlet</servlet-class>
    <init-param>
      <param-name>parameter1</param-name>
      <param-value>value1</param-value>
    </init-param>
    <init-param> 
      <param-name>parameter2</param-name>
      <param-value>value2</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyServlet</url-pattern>
  </servlet-mapping>

The url-pattern can be:
  • a complete path: /name/MyName.do
  • a directory: /name/*
  • an extension: *.do
The way to retrieve the init parameter in the code is:
getServletConfig().getInitParameter("parameter1");


5.4. Use annotations to configure servlets

From the specification Servlets3.0 is possible to declare servlets by annotations (an alternative to deployment descriptor)

@WebServlet(name="MyServlet",
urlPatterns={"/MyServlet"},
initParams={@WebInitParam(name="parameter1", value="value1"),
@WebInitParam(name="parameter2", value="value2")})

public class MyServlet extends HttpServlet {

WebListener annotation:
@WebListener
public class MyServletContextListener implements ServletContextListener {

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

Thursday 14 May 2015

OCEJWCD - 5.Container facilities for servlets and JSPs (part1)

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

5.1. Understand the purpose and structure of deployment descriptors

Deployment descriptor(web.xml) is a XML file that contains the configuration parameters for an application. This file is a JavaEE standard that describes the contents of a WAR file.

Note: a WAR file is a Web Application Archive, is basically a JAR file used to contain JSPs, servlets, java classes,XML, tag libraries, and all the resources that constitute a web application.

The web.xml file is located directly under WEB-INF directory.

Basic structure of the deployment descriptor (web.xml):

Namespace declaration and schema location
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 xmlns="http://java.sun.com/xml/ns/javaee" 
 xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
 http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0">

Welcome files
A welcome file is invoked automatically by the server if no file name is specified. By default the list is as follows:
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>

Session timeout
<session-config>
  <session-timeout>30</session-timeout>
</session-config>

Mime mapping
When serving static resources, ther server generates a content-type header based on these mappings.

<mime-mapping>
  <extension>abs</extension>
  <mime-type>audio/x-mpeg</mime-type>
</mime-mapping>
In the following topics we will include more attributes that are defined in DD.

5.2. Control context root and servlet mapping

The context root for an application is determined by how it is deployed. 
A context root identifies a web application in a JavaEE server.

<module>
  <web>
    <web-uri>myWebapp.war</web-uri>
    <context-root>myapp</context-root>
  </web>
</module>

The context root is specified when the web module is deployed, it must start with "/" ending with a string. It is matched against the context roots of other web applications hosted on this container.

To obtain context root programatically:
ServletContext getContext(String uripath)
Returns a ServletContext object that corresponds to a specified URL on the server.
Servlet mapping
As developers the servlet will be identify with the servlet name. The servlet class defines the actual location of the servlet file (including package) and the url pattern will be the address displayed in the URL.
  <servlet>
    <servlet-name>MyServlet</servlet-name>
    <servlet-class>example.MyServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>MyServlet</servlet-name>
    <url-pattern>/MyServlet</url-pattern>
  </servlet-mapping> 
See next post: Container facilities for servlets and JSPs (part2)

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

Tuesday 12 May 2015

OCEJWCD.- 4.The Servlet's environment (part2)

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification


3. Understand fundamentals of the HttpServlet and related APIS

HttpServlet is an abstract class to be subclassed to create an HTTP servletSome methods that can be overriden to perform HTTP actions are: GET, POST, DELETE, HEAD, PUT, OPTIONS and TRACE.
  • doGet()
  • doPost()
  • doDelete()
  • doHead()
  • doPut()
  • doOptions()
  • doTrace()
Servlet example:
public class Login1 extends HttpServlet {
   protected void doPost(HttpServletRequest request, 
      HttpServletResponse response) throws ServletException, IOException  
   {    
      this.getServletContext().getRequestDispatcher("/welcome.jsp");
      forward(request, response);
   }
}

The servlet container creates an HttpServletRequest and HttpServletResponse object and passes it as an argument to the servlet's service methods (doGetdoPost, etc).

HttpRequest

  • Attributes: getAttribute(String name), getAttributeNames()
  • Parameters: getParameter(String name), getParameterMap() getParameterValues()
  • ContextPath: getContextPath()
  • Cookies: getCookies()
  • Headers: getHeader(), getHeaderNames()

HttpResponse

  • PrintWriter: getWriter()
  • ServletOutputStream: getOutputStream()
  • Header: getHeader(String name), addHeader(String name, String value)
  • Cookie: addCookie(Cookie cookie)
  • ContentType: setContentType(String type)
  • URL : sendRedirect(String location)
4. Write code that manages client sessions and cookies

The container can manage the client session with the object HttpSession. 
Cookie is client related information stored in the client web browser.

Session

Session contains a pair of key/value
- key --> string type
- value --> object

Time limit can be configured in Deployment Descriptor: <session-timeout>

Every object in the server session must implement Serializable interface.

Methods in HttpSession:
  • getAttribute(String names)
  • getAttributeNames()
  • removeAttribute(String name)
  • setAttribute(String name, object value)
  • getId()
  • getLastAccesedTime()
  • getMaxInactiveInterval()
  • getServletContext()
  • setMaxInactiveInterval(int interval)
  • invalidate()


Cookies
A cookie contains a pair of key/ value, where:
-key -->string type
-value -> string type

To retrieve cookies from the user
request.getCookies() - obtain Cookie[]

To add a cookie to the client browser
response.addCookie(Cookie)



Methods:
  • getName()
  • getValue()
  • setValue(String value)
  • getPath() -- > path in the server
  • setPath(String uri) 
  • getMaxAge() -->max seconds

Session Vs Cookies
Both are methods to manage user info but not in the same way. Let's see a list of advantages and disavantages:

- Session stores information in the server side
- Cookies stores information in the client

- Session consumes resources in the server. It can be stored by a limited time.
- Cookies do not consume resources in the server, but they have a limited space defined by the browser. Although, it can have a longer duration (days, months..)

- Session can store objects, binary data, files.
- Cookies can only store text.

- Session, is safer because the data is stored in the sever.
- Cookies, the data is exposed to be modified by user, intecept by third party, so in any case should not contain sensible data.

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

Monday 11 May 2015

OCEJWCD - 4.The Servlet's environment (part1)

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification


4.1. Understand more details of the HTTP protocol
HTTP protocol is used to transfer resources between a client and a server. 
HTTP is stateless.
The information is identified by URL (uniform resource locator).
URL structure: protocol://machine:port/context/resource
Methods in HTTP
  • HEAD : get metainfo contained in headers
  • GET : get a resource from the server
  • POST : send data included in the body to the server to be processed (get,add or update)
  • PUT :  send a resource(file) to the server by a new connection.
  • DELETE: delete a resource
  • TRACE : to obtain a response code from the server
  • OPTIONS : to obtain http methods supported
  • CONNECT : to transform connection to https
  • PATCH : to modify partially a resource in the server.
Response codes in HTTP
The most common are:
  • 4XX - Error in client side
  • 5XX - Error in server

4.2. Understand fundamentals of HTML forms
A html form has these attributes:
- action :  resource
- method : GET or POST
  • GET : add form data to the URL using ? as separator (QueryString)
  • POST : the data is sent into the body.

The above form contains these different elements:
  • Textfield
  • Radiobutton
  • Checkbox
  • Buttons
  • SelectionList
  • TextArea
When the submit button is clicked the form-data is sent to a page on the server called "order.jsp"






























See next post The Servlet's Environment (part2)

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

Sunday 10 May 2015

OCEJWCD - 3. Implementing an MVC Design (part2)

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

3.3.  Forward control from a servlet to a JSP

One way to perform this is using javax.servlet.RequestDispatcher interface

ServletContext sc = this.getServletContext();
RequestDispatcher rd = sc.getRequestDispatcher("/jsp/mypage.jsp");

There are 2 methods:
rd.include(request, response);
rd.forward(request, response);

The difference between them is that include will return the control to the invoking servlet but forward not.

* Note: For invoking a servlet from a JSP, the following jsp actions can be used,for example:
<jsp:include page="/MyServlet />
<jsp:forward page="/MyServlet />

The second way is using HttpResponse.sendRedirect(), this method of HttpServletResponse interface can be used to redirect response to another resource (servlet, jsp or html file).

response.sendRedirect("..");

Differences between sendRedirect and forward.
  • The forward method works at server side and sendRedirect at client side.
  • Request dispatcher can be used only when the resource is being forwarded resided in the same application. Otherwise sendRedirect can be use within an outside the server.
  • Forward method sends the same request and response method and sendRedirect sends a new request.

3.4.  Understand fundamentals of EL

EL Expression Language. It allows to dynamically access data from JavaBeans components by using simple expressions.

Examples of notation:

  • ${person.name}
where: 
- first argument is a map or bean name.
- second argument is a map key or bean property.

  • ${person["name"]}

in this case in the square brackets we can use a map key, bean property or an index in case of a list or array object: ${personList[0]}

EL with implicit objects. Some examples:

  • Request params ${param.name}
  • Header ${header.host}
  • page Context ${pageContext.request.method}
  • Cookie ${cookie.userName.value}
  • Context init param ${initParam.email}

List of operators in EL


  • [] .


  • ()


  • not ! empty


  • * / div % mod


  • + - (binary)


  • < > <= >= lt gt le ge


  • == != eq ne


  • && and


  • || or


  • ? :
OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

Saturday 9 May 2015

OCEJWCD - 3. Implementing an MVC Design (part1)

OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification

In this post we are going to implement a simple application step by step:

The behaviour will be:
  1. Start the application (start.jsp).Introduce data in input fields and click the submit button.
  2. The servlet Login1 will be called.
  3. Welcome page (welcome.jsp) will be displayed with the name of the user.
Deployment descriptor:

Note: When creating a project in Eclipse use DynamicWeb Project. 

3.1. Code a controller using a servlet

The servlet code is created under src folder.

3.2.  Code a view using a JSP

The JSPs have been created directly under WebContent.

start.jsp
welcome.jsp

Executing the application:
-Start the application : http://localhost:8080/ExampleServlets/start.jsp



OCEJWCD (SCWCD) - 1Z0-899 - Web Component Developer Certification