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
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
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
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).
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 file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
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
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
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:
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.
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 servlet. Some 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 (doGet, doPost, etc).
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
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
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:
Start the application (start.jsp).Introduce data in input fields and click the submit button.
The servlet Login1 will be called.
Welcome page (welcome.jsp) will be displayed with the name of the user.
Deployment descriptor:
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
The JSPs have been created directly under WebContent. start.jsp
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters