SUN Technologies - Java Web and Mobile
SUN Technologies - Java Web and Mobile
MOBILE
Created by XMLmind
XSL-FO Converter.
of
Web
with
Java
http://www.supinfo.com
and
Java
Micro
Edition
How to use it ?
Current mistakes
Design an application
1. Course
1.1. Introduction
1.1.1. Why should I use an application platform ?
An application platform is a generic application which provides useful functionalities for your own applications.
Its functionalities are shared with the applications that are running on it. There are different kinds of platforms,
from the most generics to the most complex (developed for specific needs, for example). A lot of companies
have created their own platform, like IBM with WebSphere, BEA with WebLogic, etc.
Database connections
Object Containers
Configurations
....
For the advantages, we can say that it is portable and easy to maintain.
Furthermore, the JEE architecture uses components, which can be changed together and shared, which means
that:
An application developed with JEE can use high availability, in order to guarantee a good quality of service
The EJB supplier: is the actor who provides reusable business components either by the purchase to a supplier
of components, or by internal development
The assembler of applications: is the actor who is able to build an application starting from existing EJB
The installer : is the actor who deploy the application on an application server
The administrator: is the actor who controls the operation of the application server and ensures the
supervision of the applications
The supplier of container: is the editor who markets a Web container or an EJB container, this editor often
markets an application server which includes these containers
The server supplier: s the editor who markets the application server (BEA, IBM, etc)
4
http://www.supinfo.com
The various rectangles define the containers (JEE execution environment) which provide the services for the
various components (represented by the rectangles in the rectangles). The whole of the components will be
explained in the following chapter. The arrows represent the connections between the components of the
application server. For example, the customer application can be connected to the "Web Container" by the
intermediary of the JSP/Servlet, it can be also connected to the "EJB Container", etc.
Now, the diagram of connections between the platform JEE and the other application (various protocols used).
This diagram is very important in the field of connection between various applications. It provides information
concerning the protocols used for each possible remote connection.
For example, "Web Container" provides accesses via HTTP/SSL or SOAP; "EJB Container" provides accesses
HTTP/IIOP (RMI: Internet Inter-Orb Protocol)/SSL, etc.
We can then think that a customer using C #, for example, can connect on a EJB in HTTP mode or via the IIOP
protocol (more widespread).
5
http://www.supinfo.com
Components
Infrastructure services
Communication services
1.2.2.1. Components
There is 2 great categories of components:
Web
Bussiness
It is the presentation layer. The client receives only HTML text, but it is only the visible part of the application.
Behind the scene, different technologies are working to allow the code to be powerful and easy to maintain.
WEB
JSP
JSPs (Java Server Pages) are web pages which generate HTML to the client user interface. In this text file
both HTML and Java code (called Scriptlet), and even tags are linked to java code (tag-lib). This technology is
useful to generate HTML pages, but not very much to convenient to treat a request from the user. This part is
called the View because it is related to the visible part of your application for your client.
Servlet
A servlet is a java class which allows to treat a request from the client. Then, once your treatment will be
performed, you will have to redirect the client to another view. This part is the Controller by it controls the
actions of your application. This Java class should never generate HTML code (or else as less as possible).
Business - EJB (Entreprise JavaBean)
It is specific components which are supposed to treat the data of your application (called business methods) and
this connection with the data base. This part is the View Layer of the model MVC because it is related to the
visible part of your client application.
1.2.2.2. Connection services
JDBC - Java Data base Connectivity
JDBC - Java Data base Connectivity : It is a data base connection API. It is provided too with the standard
version of java, but it has been improved by the application server by creating database connections pools. It
reduces the number of lines to write, and it optimizes the performance
6
http://www.supinfo.com
JNDI : With this API, you will be able to retrieve remote objects, and to access to directories like DNS, NIS,
LDAP, etc
JTA / JTS - Java Transaction Api / Java Transaction Services : This API defines the transaction manager
JCA (JEE Connector Architecture) : It is an API which allows you to connect different informations systems
together in you organization. It work most of the time with Legacy systems, like ERP
JMX (Java Management eXtension) : This API provides you a way to monitor your applications
1.2.2.3. Communications services
JAAS (Java Authentification and Authorization Service) : This is an authentification and permission manager
API.
RMI (Remote Method Invocation) : This API allows you to communication through remote objects.
Web services : The Web services allow you to share treatments. Web services are executed remotely. This
technology uses XML, it allows you to share your application with many different platforms and languages.
1.2.2.4. JMS (Java Message Service)
This API provides a way to create an asynchronous communication.(called MOM for Middleware Object
Message) between applications.
User session Manager: define a specific session for each user of your application, even if they are using the
same objects. Most of the application servers create an user id for each new client. The client retrieves this
value each time it communicates with the server. In order to retrieve this value, you can use hidden fields, a
cookie, or a parameter in your request url.
Load balancing and recovery of the accidents: In order to manage more users, the application server needs to
be deployed on different computers. Furthermore, it is possible to recover your data if there is a problem.
Although, most of the time, the load balancing is only working on the network side with a DNS round-robin,
a reverse proxy, etc).
Manage database connections: The application server can manage your data connection to different data
source. This container is called the databases pool connections.
7
http://www.supinfo.com
...
The application server is necessary if you want to avoid re-writing these functionalities (like for GGI). By this
definition, the JSP/Servlets containers, Microsoft ASP, Cold Fusion, and PHP are applications server (even if
they are integrated with PHP/ASP web servers).
1.2.3.2. What is an object server
If you want to understand what is an object server, you have to understand that there is two ways to create your
applications:
The second one consists in developing business components (clients, providers, etc) in order to hide the
difficulties of the data access. For example, if you have got an account in a bank, your account will have two
methods, one to add money, and another one to check out the money. Thus, the hidden part modify the values
automatically for you, and the data source can be either an ERP (Entreprise Resource Planning),a
CRM(Customer Relation Ship Managment) or a database.
1.
The client sends a request
2.
The web server transmit the request to the application server
3.
The application server treats your request by using the object server
4.
The object server treats your data through the database
5.
The object server returns the objects to the application server
6.
The application server returns the result to the web server
7.
The web server returns a response to the client
In order to manager these objects, an environment is necessary : the object server. This server provide different
services of the application server.
8
http://www.supinfo.com
Load balancing: here the server does not work like an application server
Thus, as we have seen previously, the concepts are different. Most of the application servers today are EJB
server (Entreprise Java Beans). It is a necessary part only if you have important needs and you want to use the
whole business functionalities.
It is important to understand what is a difference between an object servers and an application server, or else
you will not buy the good one, like 80% of the customers. In fact, most of the organizations only need a
servlet/jsp container, and an EJB container is too difficult and useless in most of the cases.
On the market, the application servers are widely presents, more than the object servers.
During the past years, the application servers market, the standardization has decreased the number of offers.
From dozen of solutions, there is only three left today: Java, Microsoft .NET and PHP. We advise you to avoid
other solutions.
Here is a brief description of these offers:
PHP 4: The scripting applications are really easy to write, and able to perform a good job. Nevertheless, they
are difficult to maintain because the code has not a good structure
Java, Microsoft .NET, PHP 5: The object oriented solutions allow you to write a better code, easy to
maintain, without having the difficulties of the business objects
Java EJB: The business objects are more difficult and more expensive to program. You will need an
application server with an EJB Container. For example, Tomcat has a web container, but he has no EJB
container
Including this three families of solutions, Open-Source products are available for the development and the
production (Tomcat, NetBeans, JBoss, Jonas ).
The corner stone of your application server choice are:
Ease of use
9
http://www.supinfo.com
Hibernate: it is a framework which allows to "map" a relational data base into object (POJO: Plain Old Java
Object). Thus, It makes it possible to completely abstract the access to the data base and thus proposes an
access completely Object vision of the data
Spring: it is a framework which makes it possible "to replace" the heaviness of the application servers.
Indeed, one speaks about "light container". It deals with the creation and the connection of objects by the
intermediary of a configuration file describing the whole of these relations. One of the principal advantages is
that it does not force to inherit or to implement an interface or a class, contrary to the EJB
HOW TO USE
Using these two frameworks in the same application is recommended. Indeed Hibernate enables you to reach the
data whereas Spring is useful to you for "automated factory"! Moreover these both frameworks are very easily
to use and requires only one engine of servlet., contrary to the EJB which require an application server (much
heavier!).
1.3.2.2. Servlet & JSP vs Struts
With the arrival of the JSP, after the Servlets, the programmer could start to separate the presentation layer and
the application layer/treatment in a remarkable way . However the maintenance of the code and the heaviness of
use of the servlets showed their limits.
Model MVC (Model View Controller) that each developer thought on its side each time was too much limited
and not very evolutionary.
10
http://www.supinfo.com
The arrival of Struts gave a solid base answering a good MVC architecture.
1.3.2.2.1. Presentation
Struts is a framework which is designed to build Web applications. It is based on Servlet technology/JSP by
adding the an MVC2 Model (Model View Controller). It provides the frame of a Web application and avoids the
developers having to manage in a tiresome Modle View Controller separation.
1.3.2.2.2. How to Use
The use of this framework is often use in the development of Web applications. However Struts is not the only
one technology helping with the development of the application layer/Web presentation. Indeed, you can also
use JSF (Java Server Faces) or Cocoon...
1.3.2.2.2.1. Application Server: utilization and limits
The Application Servers have been developed since the creation of JEE. We can notice 2 mains categories of
servers:
JSP
Servlet
JDBC
JNDI
1.3.2.3.2. Jonas : ObjectWeb
Jonas is an application server which implements the official references for the EJBs. It embed tomcat in order to
create web applications.
Sources : http://jonas.objectweb.org/
Related technologies:
JSP
11
http://www.supinfo.com
Servlet
EJB
JCA
JDBC
JTA
JMS
JMX
JNDI
JAAS
JavaMail
12
http://www.supinfo.com
1.3.2.3.4. GlassFish
In computing, GlassFish is an application server project by Sun Microsystems for the Java Enterprise Edition
(Java EE) platform. The commercial version is called Sun Java System Application Server 9.x.
GlassFish is free software, dual-licensed under two free software licences: the Common Development and
Distribution License (CDDL) and the GNU General Public License (GPL) with the classpath exception.
GlassFish is the name for the open source development project for building a Java EE 5 application server. It is
based on the source code for Sun Java System Application Server PE 9 donated by Sun Microsystems and
TopLink persistence code donated by Oracle. This project provides a structured process for developing a high
quality application server that makes new features available faster than ever before. It is the response to Java
developers who want access to the source code and the ability to contribute to the development of Sun's next
generation application server which is based on GlassFish. This project is designed to encourage communication
between Sun and Oracle engineers and the community and will enable all developers to participate in the
application server development process.
Sources : http://glassfish.dev.java.net
1.3.2.3.5. Commercials
The commercials application server are famous because they supply useful tools. They help you to configure
your applications.
Although, you have to pay to use them
The most important commercial application servers:
WebSphere : IBM
WebLogic : BEA
WebObject : Apple
13
http://www.supinfo.com
To develop important applications, you are to use an IDE (Integrated Environnement Development).
Some often them are open-source, and freely usable.
Here is a short presentation of the most important ones.
1.3.3.1. Open Source
1.3.3.1.1. Eclipse : IBM
A very good tool because it is simple to use, and it allows to the beginners to learn java. Furthermore, a lot of
plugins are available, and they will help you to go farther in your learning path.
Link: http://www.eclipse.org
1.3.3.1.2. Sun: NetBeans
14
http://www.supinfo.com
A tool specialized for the professionals because it allows very powerful functionalities. The generation of code
and the use of modelling tools are very good. However it is permeable to the beginners, for whom Eclipse is
adapted better and it remains very expensive. It is based upon Eclipse.
Link: http://www-306.ibm.com/software/sw-bycategory/subcategory/SW710.html
1.3.3.1.3. XCode & WebObject : Apple
15
http://www.supinfo.com
Apple has a very good Application Server and IDE, mostly based on WYSIWYG, while keeping a clean and
effective code. Although,, it only works on apple platforms.
1.3.3.1.4. JDev: Oracle
Oracle JDeveloper is a free yet performant EDI allowing to modelize and develop java application for JSE, JEE,
or even JME. It is well integrated with Oracle Database, with in particular a PL/SQL debugger.
16
http://www.supinfo.com
The new functionalities are integrated by the JDK 1.5. This is why the version JEE 5 will use hem in order to
have a platform much more accessible and more optimized than the previous one.
17
http://www.supinfo.com
1. Course
1.1. Presentation
Nowadays, web sites are not static anymore, identical for all users. Its now essential to create web site with
personalized content for users which change to meet their needs, allowing them to access information and
interact with it and even with other users.
Servlet and JSP technologies are the solution created by Sun to allow you to create dynamic web content. Not
like scripting language where business tier, presentation tier and data access tier are all mixed together,
Servlet/JSP allow you to create a clear architecture, which motivate developers to separate layers. To faster
development, a web application have to be based on a MVC (Model View Controller) architecture.
Presentation tier are the web page for a client (web browser, applet, rich client application).
Web pages can be static or dynamic. In this last case, they are the result of a code executed on a server.
Development OT this tier can be realized by a J2EE application server with:
Servlets Java
18
Created by XMLmind
XSL-FO Converter.
JavaBeans
Tag Libraries
The server begins to send web page content (the response) or a error page
XSL-FO Converter.
The server detect that the request is destinated to a servlet and transfer the request to the servlet engine
Then the method service() is called. This method takes two parameters:
Servlet engine returns the result to the web server which return it to the client
20
Created by XMLmind
XSL-FO Converter.
Most important tag here is Context . This tag allows you to create different Context Path and then to
share folders of your hard drive.
In previous example we create two contexts which are mapped on local folder.
The first one is: localhost which is mapped to C:\www_root\localhost\ .
The second one is: localhost2 which is mapped to C:\www_root\localhost2\ .
You can access at this two context from a web browser via the following addresses :
21
Created by XMLmind
XSL-FO Converter.
</VSCLASS>
Like in the previous example, weve mapped localhost and locahost2 to the two respective folders :
C:\www_root\localhost et C:\www_root\localhost2 .
1.2.2.1.4. Servlet compilation and tests
Well now use the simple servlet ever. It display Hello World when a client call it.
Heres the code :
[CODE:java]import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.GenericServlet;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
public final class HelloServlet extends GenericServlet {
public void service (ServletRequest req, ServletResponse res)
throws IOException {
res.setContentType("text/html");
PrintWriter pageWriter = res.getWriter();
pageWriter.println("<html>");
pageWriter.println("<body>");
pageWriter.println("Hello World");
pageWriter.println("</body>");
pageWriter.println("</html>");
}
}
1.2.2.1.4.1. Compilation
If you compile from the command line and you use javac from the JDK, you have to check if your environment
variable: CLASSPATH includes a path to the servlet JAR libraries.
To compile from command line, type:
javac HelloServlet.java
The compiler create a class file which to be placed in specific folder depending on which server you are using.
1.2.2.1.4.2. Deployment
To use our servlet, we now have to deploy it.
1.2.2.1.4.2.1. Apache Tomcat and Sun Application Server
Well now deploy our basic servlet. You must have at least one context path on your server (well use the
context: localhost). Heres the tree structure which you have to use in order to use servlet:
/ => Context root
/.classpath => Define the classpath to access libraries
/WEBINF/classes => Contains packages and servlets
/WEBINF/lib => Can contains external libraries
/WEBINF/web.xml => Application configuration file
/work/ => Working folder for the servlet engine
The file: HelloServlet.class goes in the folder : /WEBINF/classes/.
We now have to indicates to the servlet engine that the context localhost is a web application . This can be
done by editing the file web.xml.
22
Created by XMLmind
XSL-FO Converter.
The markup <webapp></ webapp> specify that its a webapp (web application).
Then we indicates, that this webapp contains a servlet named HelloServlet which is HelloServlet(.class).
Finally, well map the path servlet/Hello to this servlet. This allow us to access our servlet via the address:
http://localhost:8080/localhost/servlet/Hello
Remark : You have to be careful at the order of markups. All <servletmapping> markups must be after
<servlet> markups. Which means you cant have a <servlet> markup followed by a <servletmapping> markup
and then another <servlet> markup. Some servers can have problems to parse this file.
1.3. Servlets
1.3.1. Presentation
Servlets are the Java alternative to CG (Common Gateway Interface) programming. A servlet is a Java class,
which is dynamically loaded, allows to extend capacity of a Web server and to reply dynamically to request.
They are executed on a Java Virtual Machine (JVM) on the server which provide a total portability and better
security. Instead of applets, servlets dont force a client to have a JVM because they are executed on a server.
1.3.1.1. Advantages
Servlets offers a lot of advantages instead of CGI. All servlets can be managed by different thread inside the
same process or by different thread inside many processes on multiple servers. The other advantages are that
they are portable from one operating system to another but also from a Web server to another.
Heres a non exhaustive list of all advantages:
Efficacy
Semi compiled
Residents
23
Created by XMLmind
XSL-FO Converter.
Multithread
Cache management
Practical
Cookies managements
Session tracing
Power
XSL-FO Converter.
method public doGet(HttpServletRequest req, HttpServletResponse res) is called for a GET request.
method public doPost(HttpServletRequest req, HttpServletResponse res) is called for POST request.
There are other methods for request like Put, Delete, Options. These methods have a structure like public
doXxx(HttpServletRequest req, HttpServletResponse res) where Xxx = (Put, Delete, Options )
Remark : If you dont need to know which type of request it is, you can just use GenericServlet
25
Created by XMLmind
XSL-FO Converter.
that
we
use
HTTP[ServletResponse/ServletRequest]
instead
of
the second version is used when a servlet need to read configuration parameters. This parameters are used to
adapt a servlet to a specific server. Parameters can be used to retrieve database connection, a password file or
other things still.
Definition of this method is:
[CODE:java]public void init(ServletConfig cfg) throws ServletException {
super.init(cfg);
// Initialisation Code
}
The only argument of type ServletConfig provides access to different configuration parameters thanks to the
method getInitParameter(). You have to specify the parameter name as argument and the method returns its
value.
You must not forget to call super.init() if you override this method. super.init() from superclass store the object
ServletConfig at a specific place in the servlet which is used thereafter.
1.3.2.2.2. service method
This method is called for each request. If you dont use HttpServlet you have to override this method to
implement your servlet. But if you use a HttpServlet, this method checks the type of request and then call the
good method (doGet(), doPost(), doTrace()). If you want a servlet which process GET and POST with the same
manner, you may want to override service() method but its not the good solution! It can actually lead to conflict
if your servlet evolves. You better have to create a new method which will be called by doPost() via doGet().
Thanks to this method, you can override doPut(), doTrace(), doOptions() directly or in subclasses.
Definition of this method :
public void service(ServletRequest req, ServletResponse res) throws IOException
XSL-FO Converter.
Remark : a Web server can be shutdown because of a bug or another technical problem (someone can plug out
the server!), thats why you cant be sure that this method will be called. So make sure to save your data
periodically.
Definition of this method :
[CODE:java]public void destroy();
getParameterMap() method: returns a Map which contains all parameters name and their associated value
SERVER_PROTOCOLE
getProtocole()
SERVER_PORT
getServerPort()
REQUEST_METHOD
getMethod()
PATH_INFO
getPathInfo()
PATH_TRANSLATED
SCRIPT_NAME
DOCUMENT_ROOT
getPathTranslated()
getServletPath()
getServletContext().getRealPath("/")
27
Created by XMLmind
XSL-FO Converter.
QUERY_STRING
getQueryString()
REMOTE_HOST
getRemoteHost()
REMOTE_ADDR
getRemoteAddr()
AUTH_TYPE
getAuthType()
REMOTE_USER
getRemoteUser()
CONTENT_TYPE
getContentType()
HTTP_ACCEPT
getHeader("Accept")
HTTP_USER_AGENT
getHeader("UserAgent")
HTTP_REFERER
getHeader("Referer")
Its possible to returns all type of content by specifying the good MIME type.
1.3.2.4.2. Writing
The data writing of the text type in the answer is done by the object : PrintWriter which we can recover by the
method : getWriter().
[CODE:java]PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<BODY>");
out.println("Bonjour le monde");
out.println("</BODY>");
out.println("</HTML>");
out.close();
If you want to returns binary data, its preferable to use the ServletOutputStream object returned by method
getOutputStream().
Heres an example to return a picture from a local picture :
[CODE:java]res.setContentType("image/gif");
ServletOutputStream out = res.getOutputStream();
FileInputStream fis = new FileInputStream (new File ("./logo.gif"));
while (fis.available() > 0) {
fis.read (buf, 0, buf.length);
out.write(buf);
out.flush();
}
fis.close();
out.close();
XSL-FO Converter.
Weve seen in previous part, the basics for servlet development. Now well learn advanced concepts.
1.3.3.1. Cookies
1.3.3.1.1. Principle
Cookies are text information send by server, and send back by client without any modifications, at each later
visit. This technique is very useful to keep trace of visitors (to know if they already come to the site or not).
1.3.3.1.2. Advantages
Cookies allow to keep a link between the client and its session on a server thanks to an session login for
example.
Cookies are very simple to use and allow to manage a lot of interesting functionalities for client.
1.3.3.1.3. Drawbacks
Cookies are sent at each request, this can increase network traffic if you make an expensive use of them.
Usage of cookies is not recommended for security. Value of each parameters actually transit with no encrypting
and can be retrieved by a hacker.
Cookies are not always accepted by clients, this can be a problem when no other s means of session tracking
exist.
1.3.3.1.4. Cookies creation
Servlets use their own cookies API. Cookies are represented by the class Cookie. Heres a description of this
class:
Constructor Cookie(String name, String value) : constructor which takes in parameter the name of the cookie
and his assigned value.
Once a cookie is instanced, you can specify certain properties (with setters ) or retrieve information from a
cookie (with getters ) :
Method int getMaxAge() : returns the duration in second before the cookies is out of date.
Method setMaxAge(int lifetime) : set the duration in second before the cookies is out of date. Value 0
indicates that the cookies must be destroy.
XSL-FO Converter.
Method setPath(String path) : set the path to the cookie (allow to specify that the cookie is only used for
certain part of the web site)
Method boolean getSecure() : returns true if cookie is transmit only for secure connection
Method setSecure(boolean secureFlag) : set if the cookie must be transmit only for secure connection
If you want to remove a cookie, you just have to set an age equals to 0 :
[CODE:java]c1.setMaxAge(0);
1.3.3.2. Sessions
30
Created by XMLmind
XSL-FO Converter.
1.3.3.2.1. Presentation
Weve seen how to keep information about a clients with cookies. However this mechanism is very limited,
thats why session system has been created.
When you talk about session, activity is on the server and not on the client (instead of cookies). Session are vert
limited in web application and more specifically in ebusiness web site Sessions allow to store data for each
client on the server.
1.3.3.2.2. Advantages
Sessions are executed on the server which is more secure than cookies. Only an identifier is used to link client
and server because data are stored on the server.
Sessions are simple to use thanks to the servlet session API.
1.3.3.2.3. Drawbacks
A link must be established between the client and the server (session login) either with a cookie, either inside
the URL.
1.3.3.2.4. session API
Servlet provides an API to manage sessions. Usage of sessions inside servlets is simple, you just have to retrieve
the session object bound to the current request. If no session object exists, you can create it automatically.
Class which represents session is : HttpSession.
Heres a description of its methods :
Method Object getValue() or Objet getAttribute(String name) : returns value of an existing session attribute
Remark : method getValue() is replaced by getAttribute() since servlets API version 2.2
Method putValue(String name, Object value) or setAttribute(String name, Object value) : bind an object to a
name
Remark : method putValue() is replaced by setAttribute() since servlets API version 2.2
Method removeValue(String name) or removeAttribute(String name) : remove an attribute from its name
Remark : method removeValue() is replaced by removeAttribute() since servlets API version 2.2
Method String[] getValueNames() or Enumeration getAttributeNames() : returns all attributes session name
Remark : method getValueNames() is replaced by getAttributeNames() since servlets API version 2.2
Method String getId() : returns a string containing the unique identifier assigned to this session. (this can be
used has a key)
Method boolean isNew() : returns true if the session has just been created or false if it already exists
Method invalidate() : invalidate the whole session and remove all objects bound to the session
1.3.3.2.5. Session management
31
Created by XMLmind
XSL-FO Converter.
First you must retrieve the session object with the method getSession() from the object HttpServletRequest.
[CODE:java]HttpSession session = req.getSession(true);
To automatically create the session (if it doesnt exists), you pass true to the method getSession().
Remark : If you pass false as parameter, the method getSession() will returns null.
With the session object, you can now add object (method setAttribute()), remove (method removeAttribute()) or
read (method getAttribute()).
1.3.3.3. SingleThreadModel interface
Weve seen that only a servlet instance is used by multiple thread (on thread by client). This can be a problem
when you want for example, that a connection to a database doesnt be shared between threads, a file
modification
The first solution is to add synchronized to service() method of servlet.
However there is a better way to do that. SingleThreadModel interface indicates to the servlet engine that you
want that a servlet can only be called by a Thread at the same time.
This interface doesnt defines any methods, its only used as a flag for the servlet engine.
Finally, this interface is useful because it can be used to secure concurrent access, however its not always the
best solution. In the case of database connection, the best things to do is to create a multi thread connection
pool. Indeed, the database can only accept a restricted number of connections (which can be lower than the
number of simultaneous clients).
1.3.3.4. ServletContext usage
A servlet associated to a servlet (ServletContext) is the environment in which the servlet is executed. Object
ServletContext is created by the servlet container and allow to access information about the environment.
The object is shared between all servlets container. This can be used to share information between servlets.
1.3.3.4.1. ServletContext description
Heres a description of all main methods of ServletContext :
int getMajorVersion() : returns the major version of the Java Servlet API that this servlet container supports.
int getMinorVersion() : returns the minor version of the Servlet API that this servlet container supports
1.3.3.4.2. Usage of object ServletContext
Method getServletContext() is used to retrieve the ServletContext object.
32
Created by XMLmind
XSL-FO Converter.
Scripting elements
Directives
Action elements
Scriplets
Comments
Declarations
Expressions
Scriplets, <% my java code%>, are Java code inside a HTML page. This characters allow to specify which type
of language to use to process encapsulated code. Variables declared inside this block can only be accessed from
the current block.
Example :
[CODE:java]<%String s = "Hello!"; %>
Comments, <% my comments %>, like the name said are used to create comments inside your code. You can
also use HTML comments code, but JSP comments cant be seen by clients.
Declarations, <%! %>, are used to declare methods and instance variable which can be used in all the current
33
Created by XMLmind
XSL-FO Converter.
Displays:
Hello!
out element references javax.servlet.jsp.JspWriter is the output flow send to the client
pageContext element references of the page context, represented by the object javax.servlet.jsp.PageContext.
It provides access to different attributes of the page.
application element references javax.servlet.ServletContext. Its used to store global data. Difference with
instance field are that these data will be shared between all the servlets of the servlet engine.
page element references an instance of the page itself, like the keyword this inside a Java class.
34
Created by XMLmind
XSL-FO Converter.
1.4.4.2. Result.jsp :
Heres interesting part, we can see how to retrieve data sent by a form.
Hence, thanks to method getParameter(String s) from request variable, we can retrieve variables values passed
as parameters.
35
Created by XMLmind
XSL-FO Converter.
[CODE:html]<html>
<head>
<title>Result of my form </title>
</head>
<body>
<h3>My information</h3>
<%
if (request.getParameter("submit") != null) {
if (request.getParameter("submit").equals("Validate")) {
%>
<table>
<tbody>
<tr>
<td><b>Last name: </b>
<% out.println(request.getParameter("lastName"));%></td>
</tr>
<tr>
<td><b>First name: </b>
<% out.println(request.getParameter("firstName"));%></td>
</tr>
<tr>
<td><form action="Formulaire.html">
<input type="submit" value="Back"></form></td>
</tr>
</tbody>
</table>
<%
} else {
%>
<jsp:forward page="Formulaire.html"/>
<%
}
}
%>
</body>
</html>
jsp:useBean
useBean markup is used to separate presentation tier from business login tier. Indeed, you will Java classes
which will allow you to create JavaBeans. These JavaBeans will retrieve data from the JSP page, process it and
return it to the JSP page in order to display it.
A JavaBean is an object represented by a Java class which must conforms to the following rules:
XSL-FO Converter.
MyBean.java :
[CODE:java]package monpackage;
public class MyBean {
private int nb;
private boolean empty;
public MyBean() {
}
public int increm(int i) {
return nb + 10;
}
public int getNb() {
return nb;
}
public void setNb(int nb) {
this.nb = nb;
}
public boolean isNb() {
return empty;
}
}
UTestBean.jsp :
<jsp:useBean id="testB" class="mypackage.MyBean"/>
Here an object of type mypackage.MyBean has been created and affected to testB variable.
Remark : You have to place your classes inside packages.
1.4.5.1. Markups jsp:setProperty et getProperty
There markups are used to get or set a property of a JavaBean instance.
There are 3 ways to do :
A star ( * ) for property allow to set automatically all attributes of a JavaBean based on the values retrieved
from a form.
<jsp:setProperty name="testB" property="*"/>
You can also specify the name of the property you want to set. The value of the attribute will be the value of the
parameter specify with param of the form.
<jsp:setProperty name="testB" property="propName" param="paramName"/>
You can directly indicates the name of the property and its value.
<jsp:setProperty name="testB" property="propName" value="Jean"/>
You can now use the JavaBean instance inside scriplets markup and use its method. Hence, instead of using
<jsp:getProperty> markup, you can use this syntax :
<%= testB.getNomProp() %>
XSL-FO Converter.
request time.
Its also possible to include file at the page translation time, just before the compilation (4.4.2).
If you want to pass parameters to the resource, you have to add the following lines :
[CODE:java]<jsp:include page="Relative path to the file " flush="true">
<jsp:param name="PARAM1" value="VALUE1"/>
<jsp:param name="PARAM2" value="VALUE2"/>(...)
</jsp:include>
1.4.5.2.1. jsp:forward
This markup is used to pass the request control to another dynamic or static request. If you want to pass
parameters to the resource, you use the same syntax that before:
Example :
[CODE:java]<jsp:forward page="Redirect.jsp">
<jsp:param name="redir" value="ca marche"/>
</jsp:forward>
Hence, inside the page Redirect.jsp you can get the value of redir thanks to the variable request
(request.getParameter("redir")).
1.4.5.2.2. Markups jsp:plugin et jsp:fallback
The plugin markup is used to generate HTML markups <object> or <embed> which indicates to the client
browser the loading of the corresponding markup.
The fallback markup is used to display a message if the client browser doesnt have support for applet.
1.4.6. Directives
Directives are messages send to the JSP container to indicates how to translate a JSP into a servlet. These
directives can be easily distinguished thanks to characters <%@ %>.
There are 3 types of directives, pages directives, inclusions directives and personalized directives.
1.4.6.1. Pages directives
Table 2.2. These directives have a form like : <%@page... %>. They can take the
following parameters :
Parameter
Parameter role
Values
language
java
38
Created by XMLmind
XSL-FO Converter.
info
contentType
Set
the
MIME(Multipurpose text/html;charset=ISO8859-1
Internet Mail Extension) type of the
page and the character encoding
extends
import
buffer
autoFlush
session
isThreadSafe
errorPage
isErrorPage
39
Created by XMLmind
XSL-FO Converter.
Tag interface is the interface to implement to create a tag handler. Different methods of this tag will allow
initialization, evaluation and closing of the markup. Different call of these methods obey to the following life
cycle:
1.4.6.4.2.2. Tag handler life cycle
Inside the same JSP page there is only one instance of the same tag. This means that is you call the same tags
several time, the same instance will be used.
Life cycle of a tag handler is controlled by a JSP container :
First, the JSP container get an tag handler instance from a instance pool, or create a new one.
It then call the setPageContext() method with the argument PageContext which represents the JSP which
contains the tag.
The container call the method setParent() with the parent tag (closest enclosing tag handler) as parameter or
null.
40
Created by XMLmind
XSL-FO Converter.
JSP container then define all attributes of the custom tag. Attributes are processed like JavaBeans properties
(getters, setters).
The method doStartTag() is called. This method can returns the following values:
Tag.SKIP_BODY : There is no evaluation of the body of the tag. It means that the content between the
open markup and the closing markup wont be displayed.
Tag.EVAL_BODY_INCLUDE : the container process the body of the tag like JSP and the body will be
displayed inside the page (the body can contains JSP, HTML and even others tags).
Whatever the returns value is, the container call the method doEndTag(). This method can returns :
Tag.SKIP_PAGE : No processing for the rest of the JSP page. The content of the page after the tag will not
be processing.
Finally, the JSP container returns an instance of the tag handler inside the pool.
For now methods of our Tag Handler are very limited. We can for example, evaluate the content of our tag (its
41
Created by XMLmind
XSL-FO Converter.
content) only one time, and if we cant display data, we cant retrieve the content of the tag and modify it. We
can only retrieve data passed as parameters of the tag.
Example of tag which implements the Tag interface :
Well create a Tag handler which represents a markup colorMessage. This tag will display Hello World Tag !
With a color specified as parameter.
[CODE:java]public class MyTag implements Tag{
private PageContext pageContext;
private Tag parent;
private String color;
public void setColor(String color) {
this.color = color;
}
public void setPageContext(PageContext arg0) {
pageContext = arg0;
}
public void setParent(Tag arg0) {
parent = arg0;
}
public Tag getParent() {
return parent;
}
public int doStartTag() throws JspException
{
JspWriter out = pageContext.getOut();
try {
out.println("<font color="+color+">Hello World Tag ! </font>");
}catch(IOException e){
}
return SKIP_BODY;
}
public int doEndTag() throws JspException{
return SKIP_PAGE;
}
public void release() {
}
}
Method doAfterBody() is called after doStartTag() method and can returns Tag.SKIP_BODY or
Tag.EVAL_BODYAGAIN.
This allow to reevaluate the body of the tag many times. If doAfterBody() returns Tag.SKIP_BODY the method
doEndTag() is directly called, if Tag.EVAL_BODYAGAIN is returned the method doAfterBody() is called.
42
Created by XMLmind
XSL-FO Converter.
43
Created by XMLmind
XSL-FO Converter.
Advantages of extending TagSupport instead of implementing IterationTag is to only override used methods.
Implementation of the class TagSupport is :
XSL-FO Converter.
The class TagWithoutBody has a color attribute which defines the font color of the message.
1.4.6.4.2.5.2. Tags with body evaluation
Its tags like bold or color markups (markup <b> </b> or <font color=> </font> in HTML) which modify its
content.
For this type of tags, well create a class which extends BodyTagSupport. This class extends and implements
BodyTag :
[CODE:java]public class BodyTagSupport implements BodyTag {
int doAfterBody();
int doEndTag();
void doInitBody();
int doStartTag();
BodyContent getBodyContent();
JspWriter getPreviousOut();
void release();
void setBodyContent(BodyContent b);
}
Hence to retrieve the body of the tag, you will retrieve from the class BodyTagSupport
BodyContent class:
This class extends javax.servlet.jsp.JspWriter. It represents the content of a custom tag (when it exists).
BodyContent of a custom tag can be retrieved with the method getBodyContent() of the BodyTagSupport class.
String content = bodyContent.getString() ;
Finally, the writing of the JSP page is made with the help of a PrintWriter inside the BodyContent.
JspWriter out = bodyContent.getEnclosingWriter() ;
Implementation of the class BodyTagSupport is :
XSL-FO Converter.
1.4.6.4.2.6. Role and format of the TLD File (Tag Librairy Descriptor)
The TLD file is a XML file which describes personalized markups.
Markup role
Its the root element of the file
<tlibversion> (mandatory)
<jspversion> (mandatory)
<shortname>
<info>
<uri>
XSL-FO Converter.
manner
<tag>
Table 2.4. Tag markup will define characteristic of a personalized tag. This markup
have the following elements :
Element name
Element role
name (mandatory)
Tag indentifier
tagclass (mandatory)
teiclass
bodycontent
description, information
Attribute
required : (true,false)
47
Created by XMLmind
XSL-FO Converter.
<attribute>
<name>color</name>
<rtexprvalue>true</rtexprvalue>
<required>true</required>
</attribute>
</tag>
</taglib>
The attribute uri specify the path to the TLD file. The attribute prefix defines a prefix which is used to prefix the
name of the tags (like a namespace).
To use a tag, you just use one of the following syntax :
<TagPrefix:TagName attribute1="value"/>
48
Created by XMLmind
XSL-FO Converter.
http://jakarta.apache.org/taglibs/
http://displaytag.sourceforge.net/install.html
http://struts.apache.org/userGuide/
1.4.6.4.3.1. JavaServer Pages Server TagLib
Well now see some functionalities of the JSTL.
To use JSTL, you must have a servlet engine which have support for servlet API 2.3 and JSP API 1.2
All the files necessary to their use are in the pack Java Web Services Developer Pack v1.4.
Once you have the jstl folder, you must place:
Core library represents basic functions and is associated to the TLD c.tld.
XML library represents XML processing and is associated to the TLD x.tld
I18n library represents internationalization functions and is associated to the TLD fmt.tld
Database library represents SQL processing and is associated to the TLD sql.tld
1.4.6.4.3.1.1. Core library
This library contains tags to create conditional structure, url management or iteration.
49
Created by XMLmind
XSL-FO Converter.
set markup makes it possible to store a variable and to define its scope.
It allow to instance a variable, thanks to the var attribute (define the variable name) and value attribute (value to
store). You can also modify the properties of a JavaBean with the target attribute (variable name which contains
the bean), property (property name) and value.
And finally the scope attribute will define the scope of the variable. It can take the following values: page,
request, session et application.
Example 1:
<coreTag:set value="Hello !" var="message" scope="page"/>
Example 2:
<coreTag:set value="Hello !" target="myBean" property="BeanName" scope="page"/>
To retrieve the value of a variable, you can use the out tag or use the following syntax :
${varname}
Its important to set in the page directive <%@ page %> the attribute isELIgnored at false. Indeed, this is
attribute is true by default, and it force the JSP to interpret the string "${varname}" like a common string and
not like a variable.
Example :
<coreTag:out value="${pageScope.message}" default="default value" escapeXml="true"/>
If you dont specify the scope of a variable, inside the attribute value (value="${message}"), the value will be
first searched in the page, then the request, then the session and finally the application.
remove markup makes it possible to remove a variable. You just have to specify its name in the var attribute and
its scope in the scope attribute.
catch markup is used to catch exceptions. Code which may throws exceptions must be encapsulated inside catch
markup. The var attribute contains information about the catched exception. Exception have a message property
which contains an error message.
Example :
<coreTag:catch var="Error">
<% code which may throw an exception %>
</coreTag:catch>
<coreTag:out value="${Error.message}"/>
XSL-FO Converter.
to present information in a different manner according to the requests from the customer that becomes
increasingly complex.
At this point in time the transmissions of requests intervene.
Once that you had your object, you only have to call the method forward() or include() of this one. You must
provide to this one the objects HttpServletRequest and HttpServletResponse.
If you use include, the resource is inserted in the active servlet.
If you use forward, the flow is completely redirected towards the new resource (caller cant write other things to
the client, this task is transmitted to the new resource only).
Inclusion or the forward towards a new resource (page or servlet) is done as follows:
[CODE:java]// Inclusion
void service(HttpServletRequest req, HttpServletResponse res) {
RequestDispatcher dispat =
getServletContext().getRequestDispatcher("/folder/page.jsp");
dispat.include(req, res);
}
[CODE:java]// Forward
void service(HttpServletRequest req, HttpServletResponse res) {
RequestDispatcher dispat =
getServletContext().getRequestDispatcher("/folder/page.jsp");
dispat.forward(req, res);
}
Remarks :
the inclusion of a servlet in another is synchronous, it means that it returns only at the end of the method
service() of the servlet called
XSL-FO Converter.
the data which you work with in the first script passed to other script.
The solution with that is to use the HttpServletRequest object and the method setAttribute(). The page of
destination will be able to then reach this information via the method getAttribute().
Since version 2.2 of the servlets a new manner of sending information has been created. You can directly put the
parameters in the URL (method GET) that you to pass at the time of the request of RequestDispatcher.
Here an example of use of this method :
[CODE:java]// Forward
void service(HttpServletRequest req, HttpServletResponse res) {
String url = "/folder/page.jsp?param1=value1¶m2=value2";
RequestDispatcher dispat =
getServletContext().getRequestDispatcher(url);
dispat.forward(req, res);
}
52
Created by XMLmind
XSL-FO Converter.
Chapter 3. Struts
This chapter allow you :
to learn Struts
1. Course
1.1. Introduction
1.1.1. Java EE platform presentation
Java EE (Java Enterprise Edition) is composed of APIs used for enterpriseoriented application development.
Amongst those APIs, some of them already exist in the Java standard version (Java Standard Edition, Java
SE), whereas the others are specific to the enterpriseoriented platform. For example, APIs like EJBs (Enterprise
Java Beans) or JMS (Java Message Service) are only available in the Java EE JDK, but APIs like JDBC or RMI
are also included in Java SE. The Java EE platform offers an optimal solution to develop robust, secure and
evolutive applications. When you choose this technology, you have to follow a number of rules, in order to
separate your application in different layers. In this course, well see how to separate the different layers, which
model to use and with which tools.
public void init(ServletConfig cfg) used at the first servlet call, when it is instanciated
public void service(ServletRequest req, ServletResponse res) called each time a client make a request on this
Servlet
53
Created by XMLmind
XSL-FO Converter.
In our JSP page, different components are available to display the different responses generated in the lower
layers. JavaBeans are components used to instanciate and manipulate different Java objects (stored in page,
request, session or application scope) with JSP tags. The advantage : when the server encounters a tag, he will
automatically detect if the object has already been instanciated or not. If thats the case, he uses the existing one
else he creates a new instance. It allows the use of an object in several pages, and even during all applications
lifetime. Taglibs, like JavaBeans are composants used to instanciate and manipulate different Java objects
thanks to JSP tags. However, their visibility is limited to the current page. We cannot reuse the same object
instance on many pages. For each page, its a different instance. Taglibs, personnalized tags, let the possibility
to create our own tags from the simpliest to the most complex in order to display all results from different
treatments in a few lines. For more information about those components, refer to the Servlets/JSP course.
1.1.2.3. Definition and interests of a presentation framework
We have seen that JSP are an ideal solution to show treatment results in a page. They represent the applications
presentation part. Theres also the possibility to use JavaBeans or Taglibs to suppress Java code in our JSP
pages. A developer objectives is to reuse his code not to do the same things over and over again. For that, well
pick a framework which imposes a simple and efficient development method. It will produce an application
respecting the reutilisability aimed by objectoriented programmation. Concretely, a framework is the
applications skeleton. It will allow fast creation of actions, events for example forms (managing security,
validation). The presentation framework choosen is independent from the inferior layers. It helps us to
achieve our objective : layers independent from each other. Its then possible to switch a layer without having to
change the others.
The ModelViewController pattern is one of the most known and famous models. It was designed first by Xerox
during the development of their first windowed system, in particular to manage user interaction with the
application. The problem solved by this MVC model is the simplification of the three major functions common
to many applications :
The conditional logic managing which screens to show to the user, what happens when an error occurs, how
and when the distant systems are updated
Its possible to combine all those modules to obtain a functional system. However, its not easy to maintain this
code. For example with JSP, we have HTML designers for the look end feel and Java developers maintaining
the code and theyre generally different people. MVC deals with this problem by separating the code in three
54
Created by XMLmind
XSL-FO Converter.
distinct parts :
Controller components, managing the conditional logic. This module chooses which screens will be shownto
the user, how to handle errors and updates distant systems
MVC simplify the application maintenance by separating each logic type without mixing them up. It hides a
modules implementation details to the others and reduces dependencies between them. MVC creates a
frontier between web designers, dedicated to HTML and presentation layer, and Java developers. A
considerable advantage during a Web application development (JSP, Servlets) is that the exceptions are all
managed by the controller, so its easier to treat them. Of course its not the only advantage, here are some other
examples :
If different Views are necessary depending on the date obtained from a database or a distant system, the
Controller decides which screen to show
If the application changes depending on the date or hour, the Controller can manage that
1.3.2. Architecture
1.3.2.1. Http request lifecycle
55
Created by XMLmind
XSL-FO Converter.
8.
The client sends a request to the application
9.
The Controller component receives the request. It starts taking decisions on how to continue, depending on
managing rules defined by the application
10.
Model components interact with persistent data storage
11.
Depending on what was returned by the Model, the Controller determines which View to show to and
transfers data to it
12.
The choosen View generates the response to the client
1.3.2.2. Overview of a Struts application
Struts is contitued of three main parts :
XSL-FO Converter.
struts( bean / logic / nested / html).tld : Struts tag library descriptor files (optional)
57
Created by XMLmind
XSL-FO Converter.
Model classes serves as an access to database or distant systems to present them to the user
They must be conceived by hiding implementation details to data access (utilisation dinterface)
1.3.3.2. Model component example
If an application is built on a Servlet container (like Tomcat), the Model component can be limited to a simple
Java bean. It provides a business view to a JDBC logic, storing information in database. The application
interacts with the Model to readn and write data, only the Model interacts with database. In an application built
with a frontal system using JSP and a dorsal system accessed via WebServices, Model components provides a
business view of the dorsal system. The application access to the information thanks to the Model, the only one
interacting with the Webservices. Its the same with an EJB application (cf. Entreprise Java Bean). The Model
provides access to the EJB. It allows great flexibility for the application evolution but also power and flexibility
for developers.
1.3.4. Views
In MVC pattern, the View component concentrates on the presentation layer showing pages to the user. This
component must refrain from containing business logic and complex analysis. The View components are often
associated to the response to the HTTP request. In Struts case, JSP are commonly used. Those files generate the
HTML content that will be sent to the client. One of JSP advantages is that we can integrate HTML, JSP tags
and Java scriptlets in the same file. The inconvenient is that the web designers task is complicated for look and
feel maintenance! And a Java developer is easily tempted to abuse scriplets and to include business logic (or
conditional logic) directly in the JSP ! With the MVC pattern, this problem is solved because it isolates the
model, the treatments, and the views. And Struts provides a set of JSP tags helping for creating View
components. We can find various tags such as : <html:text>, <logic:iterate> giving Java developers and Web
designers the possibility to have functionalities without using Java scriplet.
1.3.4.1. Struts taglibs
Struts personalized taglibs are an important part of the framework. They greatly simplify JSP development
(View component) anf link them to other components. Those tags are useful during debugging because their
name and description are a considerable advantage over scriptlets. Struts taglibs are separated in four librairies:
Html : manage html tags (text fields, file )
Logic : manage view logic (iteration, condition )
Bean : manage bean (and its properties) access in the application (page, request, session )
Nested : contains html, logic, and bean and add an arborescence for bean access
All the descriptors of those librairies are included in the framework distribution under the name : struts<<
type>>.tld. For example : strutshtml. tld is the descriptor for the html library.
1.3.4.1.1. StrutsHtml
This library is mainly used for form handling in Struts. It covers the majority of HTML tags. A little table with
all available tags :
XSL-FO Converter.
javascript: Displays Javascript content used to validate a form on the client side (plugin Validator)
empty: Evaluates the tag content body if the variable is null or empty
equal: Evaluates the tag content body if the variable is equal to the specified value
59
Created by XMLmind
XSL-FO Converter.
greaterEqual: Evaluates the tag content body if the variable is greater or equal than the specified value
greaterThan: Evaluates the tag content body if the variable is strictly greater than the specified value
iterate: Repeat the tag content body depending on the specified collection
lessEqual: Evaluates the tag content body if the variable is lesser or equal than the specified value
lessEqual: Evaluates the tag content body if the variable is lesser or equal than the specified value
lessThan: Evaluates the tag content body if the variable is strictly lesser than the specified value
match: Evaluates the tag content body if the specified value is a substring of a variable
messagesNotPresent: Generates tag content body if the specified message is not present in any scope
messagesPresent: Generates tag content body if the specified message is present in a scope
notEmpty: Evaluates the tag content body if the variable is not null/empty (works on collections too)
notEqual: Evaluates the tag content body if the variable is not equal to the specified value
notMatch: Evaluates the tag content body if the specified value is not a substring of a variable
notPresent: Generates tag content body if the specified value is not present in any scope
present: Generates tag content body if the specified value is present in a scope
60
Created by XMLmind
XSL-FO Converter.
include: Loads the response from a dynamic application and includes it in a (type String)
resource: Loads the corresponding application resource and includes it in a bean (type String or InputStream)
Take decisions about how to treat errors occuring during response treatment
XSL-FO Converter.
Not contain direct link to a JSP page (this link is made in the configuration file)
This action class can range from the simple to the more complex. For example you can create a link forwarding
to an action class displaying a form (user account creation in this case). The action class will look like this :
[CODE:java]
package com.labosun.lessons.struts.action;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
public class NewAccountAction extends Action {
public ActionForward execute(ActionMapping mappings, ActionForm form,
HttpServletRequest request,HttpServletResponse response)throws Exception {
return mappings.findForward("newUserForm");
}
}
However the majority of actions are more complex than this one. They realize data access, treaments
Heres a set of common methods in Action class :
XSL-FO Converter.
action in progress. Returns an ActionForward object indicating the view or the action to transmit the request
to
1.3.6. Internationalization
Struts provides a complete set of tools to manage internationalization of your web pages simply, like you could
do with JSTL. Internationalization is not only reserved for text into JSPs but also for form errors and messages.
In Struts, the name message bundle is used to describe a set of dynamic messages. A bundle is represented by a
Properties file (wellknown in Java world).
1.3.6.1. Properties file
Whats a Properties file? In Java APIs, there is a class used to read a standardized file (properties file) very
simply : java.util.Properties.
This file generally has the .properties extension an is composed of key/values couple. Each dynamic value is
linked to an unique key indepently from the language to associate several values to the same key depending on
the language. Little example of a Properties file :
key1=value1
key2=value2
key3=value3
63
Created by XMLmind
XSL-FO Converter.
13.
An action class cast an exception Type Exception
14.
Struts detects a configuration for this exception in the configuration file
15.
Depending on the configuration, Struts call the Handler class for this exception
16.
Struts redirects the client to the configured jsp error page
learn
all
struts
base
tags
thanks
to
the
DTD
provided
by
Its called the root tag. Theres only one in each file. It accepts in its body the following tags :
64
Created by XMLmind
XSL-FO Converter.
Apache
Each datasources tag contains all datasources for the application. It contains 0 or n datasource tags.
Each datasource tag definites precisely all configuration parameters to a datasource (and more precisely JDBC
2.0 DataSource objects). Here are all different available tags :
className : optional tag. It defines which class will be used to configure the datasource. It must contain all
necessary data to instanciate a DataSource according to its type. It has to manage all specific properties in
setproperty tag. If the tag is not present, Struts use the default class : org.apache.struts.config.Config to
manage properties
key : a key linked to a datasource. For example, for a stockdb database, the application can access it via
org.apache.struts.action.DATA_SOURCE/stockdb (if no prefix exists : prefix = "")
type : specify the DataSource class name that implements java.sql.DataSource. This class is used by Struts to
create a datasource instance, its configured with the class defined in the className attribute
setproperty : used for connection parameters for the datasource, maps a key to a value (login, password,
database parameters)
Corresponding DTD :
<!ELEMENT setproperty
EMPTY>
<!ATTLIST setproperty
65
Created by XMLmind
XSL-FO Converter.
id ID #IMPLIED>
<!ATTLIST setproperty
property %PropName; #REQUIRED>
<!ATTLIST setproperty
value CDATA #REQUIRED>
Now, its possible to retrieve a connection to the datasource to realize operations on it.
1.3.8.3. FormBeans
formbeans and formbean indicates to Struts to bind an unique indentifier to an ActionForm class. Theyre useful
to initialize DynaForms too.
Corresponding DTD :
<!ELEMENT formbeans
(formbean*)>
<!ATTLIST formbeans
id ID #IMPLIED>
<!ATTLIST formbeans
type %ClassName; #IMPLIED>
<!ATTLIST formbean
id ID #IMPLIED>
<!ATTLIST formbean
className %ClassName; #IMPLIED>
<!ATTLIST formbean
dynamic %Boolean; #IMPLIED>
<!ATTLIST formbean
name %BeanName; #REQUIRED>
<!ATTLIST formbean
66
Created by XMLmind
XSL-FO Converter.
className : used to define a configuration bean for this form (like for DataSource), not common
dynamic : deprecated
name : unique identifier used to access to the form to eventually associate it to an action. Important notice :
if the forms scope is session, you can access to the form with the getAttribute() method from the session
object
1.3.8.4. Exceptions
The globalexceptions tag gathers all exceptions managed by the application during a request treatment. Its
possible to manage as many exceptions as desired. This configuration section can be assimilated to a try
catch block in Java language. You declare a catch block with an exception tag.
Attributes admitted by this tag :
bundle : specifies the bundle name that will be used for this exception
handler : specifies which class will be called when the exception is cast. It must extends the
org.apache.struts.action.ExceptionHandler class or derived class
key : indicates the key to search for and use for the generated error message in the selected messages bundle
67
Created by XMLmind
XSL-FO Converter.
path : defines the URL path to transfer the control to when the exception is cast
scope : tells to Struts if it needs to memorize ActionError created by the exception handler in session or
request scope
If an exception is cast during a process, database.error model is sought in the default resources bundle
(ApplicationResources.properties), a new ActionError is created thanks to the model, and then placed in request
attributes. Control is finally transmitted to the standard error page.
1.3.8.5. Global Forwards
Global forwards are useful to declare pathes accessible by all defined actions in the configuration file. For
example, if many actions needs to transfer control to a login page, define the transfer in this section instead of
doing it separately in each action.
Corresponding DTD :
<!ELEMENT globalforwards
(forward*)>
<!ATTLIST globalforwards
id ID #IMPLIED>
<!ATTLIST globalforwards
type %ClassName; #IMPLIED>
<!ELEMENT forward (icon?, displayname?,
description?, setproperty*)>
<!ATTLIST forward id ID #IMPLIED>
<!ATTLIST forward className %ClassName; #IMPLIED>
<!ATTLIST forward contextRelative %Boolean; #IMPLIED>
<!ATTLIST forward module %RequestPath; #IMPLIED>
<!ATTLIST forward name CDATA #REQUIRED>
<!ATTLIST forward path %RequestPath; #REQUIRED>
<!ATTLIST forward redirect %Boolean; #IMPLIED>
Attributes description :
contextRelative : indicates if path is relative to an application module (if false) or for all the application (if
true)
name : represents the unique forward identifier. Its possible to get this forward in an action with the
findForward() method
redirect : if positioned at true, control is transmitted to the page like a redirection instead of a transfer. So a
new request is created
Generally, setproperty are not used for forwards. But hey can be useful if you want to create your own forward
classes (extending the base one). In this case, you have to precise the complete class name in the className
attribute.
1.3.8.5.1. Example
68
Created by XMLmind
XSL-FO Converter.
attribute : unique ID used tomemorize theActionForm in reqest or session scope, else name is used
forward / include : transfers control to a new path instead of processing the action
input : indicates the page or action which generated the input form processing data
parameter : transmits a parameter to the action, but its preferable to use the setproperty tag
path : links an action to a path it must be the path without suffix. For example if you specify
/admin/add.do in the action form then you have to put /admin/add in the path
prefix / suffixe : specify a prefix/suffix added to the ActionForm bean properties names before associating
them to request parameters
69
Created by XMLmind
XSL-FO Converter.
1.3.8.7. Controller
This tag is not used often. Only people with the need to modify Struts core will use it !
<!ELEMENT controller (setproperty*)>
<!ATTLIST controller id ID #IMPLIED>
<!ATTLIST controller bufferSize %Integer; #IMPLIED>
<!ATTLIST controller className %ClassName; #IMPLIED>
<!ATTLIST controller contentType CDATA #IMPLIED>
<!ATTLIST controller forwardPattern CDATA #IMPLIED>
<!ATTLIST controller inputForward %Boolean; #IMPLIED>
<!ATTLIST controller locale %Boolean; #IMPLIED>
<!ATTLIST controller maxFileSize CDATA #IMPLIED>
<!ATTLIST controller memFileSize CDATA #IMPLIED>
<!ATTLIST controller multipartClass %ClassName; #IMPLIED>
<!ATTLIST controller nocache %Boolean; #IMPLIED>
<!ATTLIST controller pagePattern CDATA #IMPLIED>
<!ATTLIST controller processorClass %ClassName; #IMPLIED>
<!ATTLIST controller tempDir CDATA #IMPLIED>
Attributes description :
maxFileSize : set maximum file size to be loaded, could be followed by K (kilo), M (mega) or G (giga)
forwardPattern : modify the way an application is linked to a context relative URL with forwardPattern.$A
value is expanded as application prefix (/applicationContext for example) and $P as required path. Default
value $A$P
inputForward : when set to true, input attributes parameters from action tags are processed like forwards, not
pathes. It means theyre compared to forward tags defined globally and locally instead of beig processed as
URI
locale : memorize a locale in user session if its not already done when this attiribute is set to true
70
Created by XMLmind
XSL-FO Converter.
nocache : sends a deactivation request of the content cache to the client browser for each HTTP response
pagePattern : tells Struts how to link pages to subjacent URL, similarly to forwardPattern
1.3.8.8. Messageresources
This tag section allows to declare application resources bundles. Its not limited to one, several bundles can be
declared.
<!ELEMENT messageresources
(setproperty*)>
<!ATTLIST messageresources
id ID #IMPLIED>
<!ATTLIST messageresources
className %ClassName; #IMPLIED>
<!ATTLIST messageresources
factory %ClassName; #IMPLIED>
<!ATTLIST messageresources
key %AttributeName; #IMPLIED>
<!ATTLIST messageresources
null %Boolean; #IMPLIED>
<!ATTLIST messageresources
parameter CDATA #REQUIRED>
Attributes description :
factory : specify message resource data location. By default, properties files are configured
null : sets application behaviour when a message is not found. If attribute is set to true, it returns null. When
set to false, returns an error message with the faulty key.
parameter : transmits a parameter to the factory when a bundle is created. For factories based on property
files, its the file path.
Example :
<messageresources
key=com.labosun.MAIN_MESSAGES
parameter=com.labosun.MainMessages />
1.3.8.9. Plugin
This last element is used to load plugins dynamically in Struts framework.
<!ELEMENT plugin
(setproperty*)>
<!ATTLIST plugin
id ID #IMPLIED>
<!ATTLIST plugin
className %ClassName; #REQUIRED>
71
Created by XMLmind
XSL-FO Converter.
Attributes description :
1.4. Tiles
1.4.1. Presentation
72
Created by XMLmind
XSL-FO Converter.
During a Web application development, its noticeable that many pages possess their own central element with
more or less static ones around it (navigation bar, header & footer )
Tiles library is a Struts plugin, used to create templates for our application thaks to another XML configuration
file.
Its possible to use this library without Struts. Well how to associate it with Struts (to see how powerful a Struts
application can be with Tiles).
1.4.2. Architecture
This architecture preserves the separation between page structure and page content. Its possible to create as
many layouts as desired. In the configuration file, to apply a layout to a page, you have to write that this page
extends this layout. We can see that the application layer is not present into the JSP pages, instead they use use a
structuring
layer
(tiles)
73
Created by XMLmind
XSL-FO Converter.
1. Course
1.1. Web Services Generalities
1.1.1. Definition
Device conversions for implementing in a Web application or for Widget available on certain operating systems,
you surely dealt with the Web services without too being aware of it.
A Web Service is a functionality implemented in many languages and system in a layer of standards derived
from the XML. It must be able to be required and called upon dynamically by other services.
Generally, the Web Services are basic functionalities of the companys available server. This technology,
initiated by IBM and Microsoft, then partly standardized by the W3C, is now accepted largely by other
information & computing industrys players without exception.
This is main point which makes Web Services a revolutionary technology and is very popular.
It makes it possible for the applications to dialogue through the network, independently of their platform of
execution (Windows, Linux) and of the type of the client (Mobiles, Office Applications ) or their
implementation language. They fall under the continuous initiatives such as CORBA (Common Object Request
Broker Structures, of l' OMG) in bringing however a simpler answer, being pressed on technologies and
recognized standards which characterize the concept even of Web service:
SOAP
WSDL
UDDI
There is a multiple use of Web Services like in B2C ,B2B, stock management domains, etc.
XSL-FO Converter.
Services technologies can be applied to all kinds of applications to which they offer considerable advantages in
comparison to the former API owners, with the specific platform traditional implementation restrictions that one
can meet. They can be useful in the majority of the scenarios when the communication can be established on a
bidirectional model (request/response). It is nevertheless farto be as restrictive, much of other models can have
recourse to the Web Services, without same as you in returned account. The companies which place them at the
disposal allow the developers interested by its functionalities to re-use them without having to re-code them.
The concept of the Web Services is currently articulated around the three following acronyms:
SOAP (Simple Object Protocol Access) is inter-application exchange platform independent protocol based on
XML language. A call of SOAP service is an ASCII flow framed in XML and transported with HTTP
protocol.
WSDL (Web Services Language Description) gives the description of XML format of Web Services by
specifying the methods being able to be called upon, their signatures and the access point (URL, port, etc.). It
is, to some extent, the equivalent of the IDL distributed programming language CORBA.
UDDI (Universal Description, Discovery and Integration) standardizes a solution of distributed directory of
Web Services, allowing at the same time the publication and exploration (research) of Web Services. UDDI
behaves almost like a Web service of which the methods are called via protocol SOAP.
We will thus see in details these standards and their operation in the continuation of this course (cf.chp 2)
75
Created by XMLmind
XSL-FO Converter.
The XML (eXtended Markup Language) is at the base of all the described protocols here. The fact that the Web
Services use the XML brings the advantage of non-ownership and thus really makes it multi platform. It is thus
recommended to have a minimum of bases (XML, DTD, diagrams, XSL,) in order to be able to really set up
of the Web Services optimized.
Example of Web services installation in a company:
1.1.3. Architecture
76
Created by XMLmind
XSL-FO Converter.
The Web Services architecture rests on a mechanism of transport of service request between a customer and a
server, both connected to network (corporate network or Internet).
Current standardization around the Web Services is however a vast building site which is a simple method
invocation of a distant object. Various work thus started to define a true distributed infrastructure, able to satisfy
all needs for a distributed application, as well in terms of standardization of the exchanges as in terms of
services.
One can figure this organization of the standardization committees according to following cutting:
Transport Layer: Definition of the structure of the messages used by the applications to be discovered and
dialogue between them
Semantics Layer: Standardization of the data taking part in the exchanges according to trades criteria
Process management Layer: Standardization of the processes management exchanges which extend on
several applications available on Internet
Directory Service: Standardization of the means of access to a service for a request relating to the contents
of service or on a supplier
Security service: Standardization of the means allowing to cover the problems of authentification and
management of the access rights.
Transaction Service
77
Created by XMLmind
XSL-FO Converter.
Standardization of the means guaranteeing integrity of the long transactions implying several Web Services
(orchestration of Web Services).
All the major actors (J2EE or .NET) propose a directed Web Services solution as well as the integration of the
associated standards. In parallel, the first uses of this technology are born, in particular in the field of the CRM
solution (Sevina or Onyx), human resources management (CCMX) or of the contents (System U, Digiplug).
Non-ownership
Multiplatform
Layer Operations
The principal disadvantage which is not really is on the level of safety. In the use of the port 80 which makes it
possible to avoid any problem of firewall also allows outside penetrating the information systems without access
controls nor analyzes contents. But this problem remains foreseeable and with thus solutions during the
development. We thus will see more in detail safety of the Web services with under following chapter (Cf.
chap.1.5).
1.1.5. Security
The current problems of safety in Web service have varied causes. Such as:
Installations without safety: password by defect or stored in light, files accessible in reading or read/write
Use of the same certificate for session SSL and XML signature
A non interest for the safety part in the projects Web service
But certain solutions are already applicable to split that. As to use combined SSL/TLS has certificates or
signatures XML. Following advises are not negligible to set up your clean Web services:
XSL-FO Converter.
Another solution are addressed in chapter WSDL (cf.chap. 2.2) The Web service is expanding considerable; to
take into account safety in this field is thus not negligible.
1.2.1. SOAP
Web Services communicate with SOAP protocol.
79
Created by XMLmind
XSL-FO Converter.
SOAP or Simple Object Access Protocol, is a simple and light protocol to share informations. SOAP is different
from RMI, CORBA and COM, because it use an system of auto description of data. It define XML message
structure used by applications to communicate.
You can use it to:
header (optional)
body
It define also encodage for different data types which based on XML technology. Datas could be simple (string,
integer, float, ...) or advanced.
SOAP manage datas's format during sending or receiving. So, there are two types of trafic:
message
80
Created by XMLmind
XSL-FO Converter.
envelop
All messages SOAP in an XML document named envelop which are containers of a SOAP message. An
envelop is the first element in an XML document. Envelop is formated with SOAP specifications, the sender
and the consumer could be written on different platforms.
1.2.1.2. HTTP request
Les requtes HTTP consistent avoir une mthodologie de requte, une requte en URL qui spcifie les enttes
et corps du flux envoy. Les messages SOAP sont transmis via HTTP permettent une complte interoprabilit
entre les clients et les Web Services. Lors de lenvoi dune requte HTTP, le champ dentte doit avoir la valeur
SOAPAction : pour que le message soit assimil un message SOAP.
We use request methodology by adding header and body (stream) in the URL. The header field must have the
value "SOAPAction" in order to be know like a SOAP message.
GET return source
HEAD return the header
POST send value to the server
PUT save a resource for the request
DELETE delete the resource
OPTIONS return HTTP method provide by the server
HTTP 1.0 include only methods GET, HEAD and POST. Although J2EE servers want to have only HTTP 1.0,
some of servers use HTTP 1.1 version.
POST /LocalWeather HTTP/1.0
Host: www.mindstrm.com
ContentType:text/xml; charset="utf8"
ContentLength:328
SOAPAction: "WeatherStation"
<SOAPENV:Envelope
xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/envelope/"
SOAPENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAPENV:Body>
<m:GetCurrentTemperature xmlns:m="WeatherStation">
<m:scale>Celsius</m:scale>
</m:GetCurrentTemperature>
</SOAPENV:Body>
</SOAPENV:Envelope>
the header
81
Created by XMLmind
XSL-FO Converter.
the body
Here are some errors with HTTP protocol:
404 resource is unavailable
401 need authentification
500 internal error
503 the server is overloaded
HTTP/1.0 200 OK
ContentType:text/xml; charset="utf8"
ContentLength:359
<SOAPENV:Envelope xmlns:SOAPENV="http://schemas.xmlsoap.org/soap/envelope/"
SOAPENV:encodingStyle="http://schemas.xmlsoap.org/soap/encoding/">
<SOAPENV:Body>
<m:GetCurrentTemperatureResponse xmlns:m="WeatherStation">
<m:temperature>26.6</m:temperature>
</m:GetCurrentTemperatureResponse>
</SOAPENV:Body>
</SOAPENV:Envelope>
IBM created a new standard named HTTPR or HTTP Reliable, HTTP Fiable, in order to make sending et
receiving SOAP message reliable.
1.2.1.4. Namespaces
It's important to understand XML namespaces to understand SOAP.
<m:GetCurrentTemperature xmlns:m="WeatherStation">
<m:scale>Celsius</m:scale>
</m:GetCurrentTemperature>
Let's go to analyse this XML code. XML allow you to create variables names like in a programmation language.
Here the namespace identity called "m" and this variable have "WeatherStation" as namespace. This principle of
variable is very used in data description files. The exemple "m:GetCurrentTemperature" allow to identify
namespace thank to "m".
XML use default namespaces, you can meet streams like that:
<GetCurrentTemperature xmlns="WeatherStation">
<scale>Celsius</scale>
</GetCurrentTemperature>
1.2.2. WSDL
1.2.3. UDDI directory
UDDI (Universal Description, Discovery and Integration) is a specification which defines how to publish and
discover Web Services through a search engine. Thus, in order to grant access to a new service, we must create a
file called Business Registry which describes the service using XML Language with UDDI specifications.
UDDI allows to classify and search Web Services. In fact, if a consumer cannot find a specific Web Service, it
means nothing to deploy it. Thats why the idea of a universal directory has been established. Unlike LDAP
(Lightweight Directory Access Protocol) directories, UDDIs doesnt deal with resources such as hardware,
software or peoples. In fact, they are private directories based on the Internet. They are usually used for
Business to Business (B2B) exchanges. UDDI directories provide both technical information (WSDL
documents) as usual information about the company which provides the service (the company Web page,
82
Created by XMLmind
XSL-FO Converter.
products and so on). The UDDI API is divided in two interfaces. The first registers Web Service in the
directory and the second is used to search inside of the directory. This API has two main libraries:
Publishing API
Request/Research API
1.2.3.1. Searching a Web Service
You can search Web Services through a search engine which is embedded in the website of the UDDI operator.
You can define a lot of search criteria in order to refine your request:
Companys name
Companys location
...
Thanks to the Request API, UDDI directories will locate Web Services which are deploy on all public servers in
the world. By searching a Web Service, you can find a lot of information about the company which provide this
service, even other services they can offer.
UDDI operators certify the security and the integrity of Web Services they have in their directories.
Calling operators websites grant access to information about a Web Service entry in the UDDI directory :
find_business : search the identity of the company which provide the Web Service
find_relatedbusiness : find a list of companies which are link (partnership, departments, subsidiary) to this
company
83
Created by XMLmind
XSL-FO Converter.
1.3. In practice
1.3.1. JWS (Java Web Services)
Java Web Services, also known as JWS, is a new standard for implementing Web Services. This standard was
first written by WebLogic Workshop. Also, this new standard is now supported by the Java Community
Process. The main aim for JWS is to provide an easily usable and understandable implementation for Web
Services. AXIS is based on this standard to provide features enabling the developer to deploy and use Web
Services.
1.3.1.1. Deploy a Web Service using JWS
In order to deploy a Web Service using JWS features, we just have to rename a Java source file describing the
Web Service, replacing the file extension to .jws instead of .java For example, a file named
MyHelloWS.java should be renamed into MyHelloWS.jws. Once our JWS file created, we have to copy
this file into the webapps/axis directory, inside Tomcat server directory. You can verify that your Web
Service was deployed, trying to access it with a Web browser at the following URL :
http://localhost:8080/axis/MyHelloWS.jws
You should have access to the following page :
You can view the WSDL corresponding to your Web Service by clicking on the previous link, or by adding
?wsdl to the Web Service URL.
1.3.1.2. Undeploy a Web Service using JWS
Undeploy a Web Service using JWS is a very easy task. You just have to delete the JWS file previously
deployed on the server. If you try to access the URL for an undeployed Web Service, you'll see the following
page :
1.3.2. Axis
Apache AXIS is a SOAP (Simple Object Access Protocol) implementation for JWS which provides some
utilities to help developers create and deploy Web Services. You can find more informations at
http://ws.apache.org/axis/ Also, you have to download Axis at the URL above, in order to install it in your
84
Created by XMLmind
XSL-FO Converter.
Tomcat server.
1.3.2.1. Installation
In our case, we'll use Axis inside a Tomcat Servlet container. To install Axis inside our Tomcat server, you just
have to copy the webapps directory contents from the Archive Axis to the webapps directory inside Tomcat.
You should new have a directory tree for your Tomcat looking like this :
Now, start your Tomcat server using the startup.bat script located in the bin/ repertory inside your Tomcat
folder, or via your favorite IDE.
Now, try to access the following URL: http://localhost:8080/axis You should see the following page:
You can try to click the Validation link, in order to check the Axis installation.
85
Created by XMLmind
XSL-FO Converter.
You can also click the List link on the home page in order to list all the deployed Web Services:
1.3.2.2. Features
Axis provides some features related to Web Services. You can easily deploy or undeploy Web Services inside
your Tomcat server, thanks to Axis. Also, you'll have access to the WSDL directly trough your Web Browser.
No .wsdl file are written, WSDL is dynamically generated. You'll also have access to your Web Services
methods via a web browser, specifying the Web Service name and the method you want to invoke. Finally, Axis
helps developers writing console, Swing and/or JSP clients thanks to some specific classes included into Axis,
which will simplify the client development. A traffic monitor is also available to check every calls on every
Web Services deployed on your server.
1.3.2.3. Invoke Web Services
Invoking a Web Service can be made via a Web browser, a console client or even a Web client. If you want to
invoke a method via a Web browser, you'll have to specify which method you want to invoke though the
method parameter.
For example, to invoke the sayHello method,
http://localhost:8080/axis/MyHelloWS.jws?method=sayHello
we'll
access
You'll now see the following page, corresponding to the returning SOAP message:
86
Created by XMLmind
XSL-FO Converter.
the
following
URL:
axis_libs corresponds to a system variable containing the path of all Axis' JAR files. You have to create this
variable with the following value:
%CATALINA_HOME%\webapps\axis\WEBINF\lib\activation.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\axis.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\axisant.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\commonsdiscovery0.2.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\commonshttpclient3.0rc2.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\commonslogging1.0.4.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\jaxrpc.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\log4j1.2.8.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\mailapi_1_3_1.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\saaj.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\servlet.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\wsdl4j1.5.1.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\xercesImpl.jar;
%CATALINA_HOME%\webapps\axis\WEBINF\lib\xmlParserAPIs.jar
These paths are using the system variable CATALINA_HOME. This variable should contain the Tomcat
installation path, for example: d:\java\tomcat5.0.28 For Linux users, use the export command, as shown
below:
export axis_libs=${CATALINA_HOME}\webapps\axis\WEBINF\lib\activation.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\axisant.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\axis.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\commonsdiscovery0.2.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\commonshttpclient3.0rc2.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\commonslogging1.0.4.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\jaxrpc.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\log4j1.2.8.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\mailapi_1_3_1.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\saaj.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\servlet.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\wsdl4j1.5.1.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\xercesImpl.jar:
${CATALINA_HOME}\webapps\axis\WEBINF\lib\xmlParserAPIs.jar
87
Created by XMLmind
XSL-FO Converter.
Actually, the WSDD file is an XML file used at deployment time. The WSDD file should contain the used name
spaces in order to check it's validity.
In a second time, you have to use the service markup, specifying the following attributes:
The Web Service mode: RPC (which stands for Remote Procedure Call)
Also, you have to specify at least two parameter tags:
One of them should define the name of the class associated to the Web Service. Using deployment
descriptors, you can specify different names for the Web Service and for its class.
The second one define the methods published into the Web Service.
Here is an example for a deploy.wsdd file:
<deployment xmlns="http://xml.apache.org/axis/wsdd/" xmlns:java="http://xml.apache.org/axis/wsdd/providers/java">
<service name="MyHelloWorldWebService" provider="java:RPC">
<parameter name="className" value="MyHelloWorldWS"/>
<parameter name="allowedMethods" value="*"/>
</service>
</deployment>
Once the file created, you'll have to use it in order to deploy your Web Service. To do this, you'll have to use an
utility provided by Axis and called AdminClient. This utility will also be used to undeploy a Web Service. The
syntax to use is the following: java cp %axis_libs% org.apache.axis.client.AdminClient deploy.wsdd axis_libs
is corresponding to the environment variable previously created and containing the path to all JAR files
available into the Axis' lib directory.
After executing the line above, you'll obtain the following response:
You can now access the Axis' home page and click on the List button. You'll see the following page, listing
all the deployed Web Services:
This feature, listing all the deployed services, wasn't available using the JWS deployment. Here, you can also
read the WSDL corresponding to each service.
You
can
access
the
following
URL
to
verify
your
Web
88
Created by XMLmind
XSL-FO Converter.
Service
deployment:
If you want to invoke a method on this Web Service, you can proceed the same way we saw above with a Web
Service deployed using the JWS principle. You just have to add the method parameter into your URL. Here is
the
URL
to
call
the
sayHello
method
on
the
MyHelloWS
Web
Service:
http://localhost:8080/axis/services/MyHelloWS?method=sayHello
You'll now have access to the following page, corresponding to the returned SOAP message:
1.3.2.7. Undeployment
Undeploying a Web Service previously deployed using a Deployment Descriptor is very easy. We have to create
an undeploy.wsdd file. It's an XML file containing a service markup, with a single name attribute. The
name value is the name of the Web Service you want to undeploy. Here is an example, undeploying the Web
Service named MyHelloWS:
<undeployment
xmlns="http://xml.apache.org/axis/wsdd/">
<service name="MyHelloWorldWebService"/>
</undeployment>
Once the file created, we'll use the AdminClient utility, as we have done during deployment.
The syntax is exactly the same, we just change the WSDD file name: java cp %axis_libs%
org.apache.axis.client.AdminClient undeploy.wsdd
Executing the above command produces the following output:
On the page listing all the deployed Web Services, we can see that MyHelloWS has been correctly undeployed:
89
Created by XMLmind
XSL-FO Converter.
Trying to access an undeployed Web Service will produce the following page:
You're now able to deploy and undeploy Web Services using WSDD files.
A proxy client (stub) for each binding defined by the service. A binding is the implementation of a service
corresponding to a given exchange model (RPC or messages) using a given protocol (SOAP) trough a given
transport protocol (HTTP)
A service locator, comparable to a Factory, which will create implementations for the interface
1.3.3.3. Server side generation
The server side generation is similar to the client side generation. We use the same command, adding some
specific options. This principle will be used only if you want to deploy the service on your server. The main
90
Created by XMLmind
XSL-FO Converter.
deploy.wsdd
undeploy.wsdd
localhost\axis\<NomDuWS>_jws\<NomDuWS>.java
localhost\axis\<NomDuWS>_jws\<NomDuWS>Service.java
localhost\axis\<NomDuWS>_jws\<NomDuWS>ServiceLocator.java
localhost\axis\<NomDuWS>_jws\<NomDuWS>SoapBindingImpl.java
localhost\axis\<NomDuWS>_jws\<NomDuWS>SoapBindingSkeleton.java
localhost\axis\<NomDuWS>_jws\<NomDuWS>SoapBindingStub.java
Administrate
91
Created by XMLmind
XSL-FO Converter.
Coordinate
Web Services can take place into different layers inside the enterprise information system. JAX-RPC is used
during the development of Web Services.
This API supports the following data types (on top of the primitive types):
java.lang.Boolean
java.lang.Byte
java.lang.Double
java.lang.Float
java.lang.Integer
java.lang.Long
java.lang.Short
java.lang.String
java.math.BigDecimal
java.math.BigInteger
java.net.URI
java.util.Calendar
java.util.Date
Java API for Web Services: JAX-WS, JAXP, JAXM, JAXR, JAX-RPC
92
Created by XMLmind
XSL-FO Converter.
These notions are not mandatory to master. This course has only for aim to present you the different aspects of
Web Services. If you want more informations , you now have some starting points to do some researches.
https://uddi.ibm.com/beta/find
http://www.strikeiron.com
http://uddi.microsoft.com/
1.3.7. Invoking a Web Service
Once you find, thanks to UDDI directories, the Web Service you want to use, you have to get the corresponding
WSDL address, for example: http://www.xmethods.net/sd/2001/TemperatureService.wsdl The client invoking
the Web Service can be either a Web browser, or a client application (Swing, SWT, ...). The invocation can be
asked by the user or be automated (Web Service invoking another, automated task, ...).
The client can be another platform than the one hosting the Web Service (Main frame, server, desktop, laptop,
PDA, mobile phone, ...). Also, if the Web Service is written using C#, clients can be developed using Java, PHP,
C, ...
Actually, the client doesn't has to know the language used to develop the Web Service in order to use it.
93
Created by XMLmind
XSL-FO Converter.
Knowing that invoking a Web Service go trough always trough a lot of XML dialects, we talk about XML
Web Services. It's mandatory to master the XML syntax in order to understand how Web Services
communicate
between
them,
and
how
implementations
are
build.
94
Created by XMLmind
XSL-FO Converter.
Discover JavaME
Practice
Enjoy it !
1. Course
1.1. Introduction
1.1.1. Presentation
Java Micro Edition (Java ME), is the most recent Java Plateform.
Incoming of new technologies are often gone with peculiarity, each constructor wanting to leave its claw. That
led to heterogeneity in the same domain however having the same goal. These bringing the nuisances that
everyone knows, the necessity for entirely reencode entirely a program which works on a machine X and not on
Y.
SUN already has a solution for this problem, remember in the World of personal computers with their principle
which consists on compile once, run anywhere.
The idea was to do the same with for the mobile devices, however towards available material, the use of
framework Java SE was impossible. An example, the power processor of a mobile phone is far from a PC.
So, Java ME has been thinking and conceives for mobile devices, including cell phones, PDA, TvBox and any
other device with limited resources.
However, dont forget Java SE, because Java Me approaches it on many aspects, and uses many of its concepts
(identical syntax, bytecode, package organisation, etc).
We will discover that Java ME is composed of 3 fundamental elements:
Configurations
Profiles
Optional APIs.
95
Created by XMLmind
XSL-FO Converter.
1.1.3. Software
In order to be able to develop for these devices, in particular cell phones, we can use the Wireless ToolKit that
we can download on SUNs website.
Although sufficient to develop, it is more simple to use an integrated development environment (IDE) than a
notepad, we will use Netbeans with the plugin Netbeans Mobility which provided us the necessary.
1.1.3.1. The Wireless ToolKit
To use the Wireless ToolKit, just install it.
In this kit, we will find a lot of tools, we will use one of them: the KToolBar.
It makes possible to compile, use, and emulate the project.
Here is a representation of it:
Figure 5.2.
96
Created by XMLmind
XSL-FO Converter.
java.io: Provides classes for input and output through data streams
java.lang: Provides classes that are fundamental to the Java programming language
97
Created by XMLmind
XSL-FO Converter.
java.util: Contains the collection classes, and the date and time facilities
1.2.2. Profile
A profile, as this word indicates, is usefull to specialize. In other words that means that profile will correspond
to a type of device or a whole of functionalities.
There are considerable profiles, like MIDP, Foundation Profil, Personal Profil. Each one of them is used with a
Configuration. Example: MIDP with CLDC, Foundation Profil with CDC
We will take interest in MIDP.
MIDP (Mobile Information Device Profil) provides necessary packages for graphic uses, data persistence and
for connectivity.
Applications developed with this Profile are named MIDlet, acronym of MIDP and Applet because they have
the same life cycle.
java.lang: Same as Java SE, Fundamental classes to the Java programming language. Ex: management of
Wrappers (String, Float, Boolean, etc.)
java.util: Same as Java SE, Contains the collection classes, and the date and time facilities
javax.microedition.lcdui.game: Provides a series of classes that enable the development of rich gaming
content
javax.microedition.media: Provides classes to manage media. The MIDP 2.0 Media API is a directly
compatible building block of the Mobile Media API (JSR135) specification
javax.microedition.media.control: This package defines the specific Control types that can be used with a
Player
98
Created by XMLmind
XSL-FO Converter.
javax.microedition.midlet: This package define MIDP applications and the interactions between the
application and the environment in which the application runs
javax.microedition.pki: Provides necessary to use Certificates which are used to authentication on secure
Connections
99
Created by XMLmind
XSL-FO Converter.
If you have cellphones, it is preferable to check on them that your application works. Indeed, although a
standard has been established, blurs remain, and results in some virtual machine are not very ended. In this
way, your application can work on a Motorola device and not on Nokia. Sometimes there are differences
on same devices because they dont have the same firmware.
Most of the time, Software publishers have a specific team to testing compatibility of their products in
many devices.
For the game development, sometimes, most part of the time ( ) is attribuate to test the application, in
order to test it on devices which are on the market.
Figure 5.3.
As you can note it on the diagram, the 3 methods are: startApp(), pauseApp() et destroyApp().
You will find them in a class that extends MIDlet:
The method startApp() is equivalent of main() in a Java SE program. Indeed, in Java ME there is no main()
method.
The method startApp() is equivalent of main() in a Java SE program. Indeed, in Java ME there is no
main() method.
100
Created by XMLmind
XSL-FO Converter.
The method pauseApp() signals the MIDlet to enter the Paused state.
The methode destroyApp(Boolean unconditional) signals the MIDlet to terminate and enter the Destroyed
state.It takes a parameter, if it is true , MIDlet is destroyed, if it is false , we ask the MIDlet to be
destroyed, if MIDlet is not ready to be sestroyed, it throw a MIDletStateChangeException.
There is a simple MIDlet which post Welcome and allows you to shut down application while pressing on a key.
[CODE:java]import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
public class premierMIDlet extends MIDlet implements CommandListener {
private Command commande1;
private Command commande2;
private Command commande3;
private Display display;
/**
* Constructor
**/
public premierMIDlet() {
display = Display.getDisplay(this);
commande1 = new Command("Cmde 1", Command.EXIT, 1);
}
/**
* Start the MIDlet
**/
public void startApp() {
// Creating a textbox.
TextBox t = new TextBox ("First MIDlet", "Welcome", 256, 0);
// Associate the command commande1 to the listener.
t.addCommand (commande1);
// Set up the listener
t.setCommandListener (this);
display.setCurrent (t);
}
/**
* Pause the MIDlet
**/
public void pauseApp() { }
/**
* Clean what the garbage collector dont deal, and destroy the MIDlet
**/
public void destroyApp (boolean unconditional) {}
/**
* Response to a command request.
**/
public void commandAction (Command commandeActivee, Displayable d) {
if (commandeActivee == commande1) {
destroyApp (false);
notifyDestroyed();
}
}
}
Now, were going to describe more deeply some points of this code.
The result of the MIDlet compiled and emulated by the Sun Toolkit :
Figure 5.4.
101
Created by XMLmind
XSL-FO Converter.
Figure 5.5.
102
Created by XMLmind
XSL-FO Converter.
Skin DefautColorPhone
Figure 5.6.
103
Created by XMLmind
XSL-FO Converter.
Skin MediaControlPhone
Figure 5.7.
104
Created by XMLmind
XSL-FO Converter.
Skin QWERTYDevice
105
Created by XMLmind
XSL-FO Converter.
We will be able to use this APIs in the same application, but not at the same time, remember this 2 API use the
screen, but there is only one screen.
It is well to use simple interfaces, especially to propose lists of choice because informations input is boring for
a user.
1.5.2. Display
It will be necessary to make difference between several objects on which display rests, here are these objects:
Displayable: An object that has the capability of being placed on the display
Display: Display represents the manager of the display and input devices of the system
Is it a color screen ?
isColor() This method returns a boolean
Figure 5.8.
This interface is more independent of device than lowlevel interface, so it is turned towards the portability.
106
Created by XMLmind
XSL-FO Converter.
It will have been guessed, the first argument of these constructors is the title of dialog box, this being the only
one compulsory. In the second constructor, we can add a message which indicates with detail the error for
example, a possible image, and the alerts type. You should know there is five types of alerts:
ALARM: A hint to alert the user to an event for which the user has previously requested to be notified
Create a list with a title and a type of list (one of IMPLICIT, EXCLUSIVE, or MULTIPLE ).
107
Created by XMLmind
XSL-FO Converter.
Create a list with a title, a type list, elements of the list, and images of this elements. The most used is the first
constructor.
To add some element to a list, we can use the method append(String stringPart, Image imagePart) setting
Image parameter to null if you dont want images. The parameter stringPart will show the text in the list.
To empty a List, use the method deleteAll() .This will delete all the elements in the list. If you want to delete a
specific element, use the method delete(int elementNum) which takes in parameter the id of the element.
To find which one is selected in the list, you can use the method getSelectedIndex(). This method returns the id
of the element.
So, you can select the default element. For this selection there are two methods available:
[CODE:java]setSelectedFlags (boolean[] selectedArray)
[CODE:java]setSelectedIndex (int elementNum, boolean selected)
The first takes in parameter a Boolean tables and the second allow you to modify select an element usin his id.
But you can unselect elements using the same method, just say false for parameter selected.
With the first method we can select all the elements at the same time, also for second method we have to call it
for each selected element.
Also, we can modify an element of the list using the method set(int elementNum, String stringPart, Image
imagePart), but if you just want to change the text you can use getString(int elementNum) which returns the text
of elementNum, such for image with getImage(int elementNum).
1.5.3.3. TextBox
The TextBox is similar to a TextArea in Java SE.
Like you see above, the constructor takes parameters, the title, the default text which will be displayed,
maximum size of the text and some constraints:
[CODE:java]TextBox(String title, String text, int maxSize, int constraints)
XSL-FO Converter.
Offset is the beginning of the text to erase, and length, number of characters to delete. With this method is easy
to delete all the text, just set offset to 1, and te length use size() to have the length of the text.
1.5.3.4. Form and Items
This object will be useful for Forms, its a container.
Form (String title)
As for other classes, there are two constructors, with parameter title in both cases, and for the second constructor
a list of items.
This list will be the component which form contains.
We can also detect how much items there is with the method size() which returns an int.
In same way, we will be able to select each items with get(int itemId). This method will return an object of type
item.
Thereafter we can add more items using the method append(Item item). which returns an int, the id of the item.
Of course, we can insert and delete items using insert(int itemNum, Item item) and delete(int itemNum). And to
erase all items at the same time use deleteAll().
1.5.3.4.1. Items
Here are different items that we can use:
ChoiceGroup, CustomItem, DateField, Gauge, ImageItem, Spacer, StringItem, TextField
All of them have some methods in common, in particular, those allowes modify its label: Text that generally is
display with the component.
109
Created by XMLmind
XSL-FO Converter.
The label allows to annotate the gauge, the Boolean allows user to modify or not the gauge, and next ther is the
maximum value and the initial value..
And there is again getter and setter to modify parameters when the application is running.
ANY
EMAILADDR
NUMERIC
PHONENUMBER
URL
PASSWORD
110
Created by XMLmind
XSL-FO Converter.
1.5.4. Commands
The first approach is simple.
To manage events, your MIDlet has to implements the interface CommandListener.
So, your MIDlet will have to redefine the methode
commandAction (Command c, Displayable d)
Just implement it once, but you know that you can have a lot of commands. So to know what command has
been pressed, you will use the object Command, it contains the name of the object you used.
The Displayable object contains informations of display.
When you create a command, you just have to add it to a form, there is an example:
import java.io.IOException;
import javax.microedition.midlet.*;
import javax.microedition.lcdui.*;
/**
*
* @author Michel
* @version
*/
public class Midlet extends MIDlet implements CommandListener{
// a command
Command c;
public void startApp() {
Display d = Display.getDisplay(this);
d.setCurrent(seeTextBox());
}
public void pauseApp() { }
public void destroyApp(boolean unconditional) {}
111
Created by XMLmind
XSL-FO Converter.
Figure 5.9.
1.5.6. Canvas
There is the Canvas constructor, its very simple :
Canvas()
This class allows us to manipulate the display, because it has access to the events due:
To stylus
112
Created by XMLmind
XSL-FO Converter.
This one when key is repeated, i.e. that one remains to support above.
It should be noted that this event could not be support by the device, so its necessary to check it using this
method:
boolean hasRepeatEvents()
1.5.6.4. Events
113
Created by XMLmind
XSL-FO Converter.
1.5.7. Graphics
This has some similarities with the one which you can find on the JDK Java SE. The difference is thaht there are
less methods in Java ME. Thi class allows to make simple 2D graphics like squares, lines, words, lle permet
aussi de crer des graphiques simples 2 dimensions. Tel que des rectangles, des lignes, des mots.
Some methods like:
drawImage (Image img, int x, int y, int anchor)
drawString (String str, int x, int y, int anchor)
They take in parameter an in anchor. Anchor is the point for positioning the image, the string .. Example: if
we want to draw an image, on which one we define the anchor point on his center, so the his center will be
located on x,y.
The definition of the anchor point must be one of the horizontal constants (LEFT, HCENTER, RIGHT)
combined with one of the vertical constants (TOP, BASELINE, BOTTOM).
Example: LEFT | TOP .
Another important method,
setClip (int x, int y, int width, int height)
114
Created by XMLmind
XSL-FO Converter.
Image myImage;
public Dessin2(){
try{
myImage = Image.createImage("/1.png");
}catch(Exception e){
e.printStackTrace();
}
}
protected void paint(Graphics g) {
g.drawImage( myImage, this.getWidth()/2, this.getHeight()/2,
Graphics.VCENTER | Graphics.HCENTER );
}
}
class Dessin1 extends Canvas{
public Dessin1(){}
protected void paint(Graphics g) {
g.setColor(0,0,255); //On choisit la couleur Bleu
g.drawRect(5,5,25,25); //On dessine un carr bleu
g.fillRect(35,5,25,25); // On dessine un carr plein bleu
g.setColor(0,255,0); //On choisit la couleur verte
g.drawString("Hello tout le monde",5,50,Graphics.LEFT |Graphics.TOP);
// On dessine une chaine de caractere, la font peut etre modifier par
// setFont(Font _font)
g.setColor(255,0,0) // On choisit la couleur rouge
g.drawLine(1,90,110,130); //On dessine une ligne rouge
g.drawRect(40,100,50,50); //On dessine un carr rouge
g.setColor(0,0,255);
g.setClip(40,100,50,50); //On ne modifiera plus que la zonedefinie
//ici, remarqu quil sagit du carr predefini juste au dessus
g.drawLine(1,90,110,130); //On redessine la mme ligne en bleu
}
}
sortie:
Figure 5.10.
1.6. Multimedia
1.6.1. Presentation
The MIDP 2.0 Media API is a directly compatible building block of the Mobile Media API (JSR135)
specification. It opens us the doors of mutlimedia, but contrary to the MMA, the MIDP 2.0 Media API is limited
to the audio.
Media just define one class, Manager, but also there are 4 interfaces Control, Controllable, Player,
PlayerListener and 1 exception class MediaException..
115
Created by XMLmind
XSL-FO Converter.
1.6.2. Concept
The concept of this api rests on 3 blocks:
Manager
Player
Control
Figure 5.11.
A Manager can have more than one Player, each one for a specific data type.
Ex: a player for data type Wav, another one for MP3
Each player can have several controls, we have to define them.
1.6.3. Methods
static Player createPlayer(InputStream stream, String type)
116
Created by XMLmind
XSL-FO Converter.
Allows the creation of a Player using a stream, and indicating its type of stream. Ex of type : "audio/Xwav"
static Player createPlayer(String locator)
Return the list of supported content types for the given protocol
static String[] getSupportedProtocols(String content_type)
Play back a tone as specified by a note, its duration and its volume ranging between 0 and 100.
import java.io.IOException;
import java.io.InputStream;
import javax.microedition.media.Manager;
import javax.microedition.media.MediaException;
import javax.microedition.media.Player;
import javax.microedition.media.control.ToneControl;
import javax.microedition.midlet.MIDlet;
import javax.microedition.midlet.MIDletStateChangeException;
public class TestMedia extends MIDlet {
public TestMedia() {
super();
// TODO Autogenerated
constructor stub
}
protected void startApp() throws MIDletStateChangeException {
String[] type = Manager.getSupportedProtocols("audio/xwav");
int i = type.length;
for (int j=0;j<=i;j++){
System.out.println(type[j]);
}
try {
InputStream is = getClass().getResourceAsStream("BONAL.WAV");
Player p = Manager.createPlayer(is, "audio/Xwav");
p.start();
} catch (IOException ioe) {
} catch (MediaException me) { }
try {
Manager.playTone(ToneControl.C4, 80000 /* ms */, 100 /* max
vol */);
} catch (MediaException e) { e.printStackTrace();}
}
protected void pauseApp() { }
protected void destroyApp(boolean arg0) throws
MIDletStateChangeException { }
}
This code returns the list of supported protocols by the type wav. The list can be shown in the shell.
This code shows us how to play a song named here Bonal.wav, this one is on the folder project.
And we can show how to diffuse the song.
XSL-FO Converter.
This package provides all classes and interfaces requisited to the client/server communication mainly throughout
HTTP 1.1 protocole.
Besides http is the only protocole that a MIDP implementation must contain, it means that all the other
protocoles (TCP, UDP) are not required because a lot of devices dont get an IP stack.
As you can notice, this example get us the HTML code of the Google research welcome page. If the URL was
wrong, a error message would appear.
Lets check the steps to respect to get a connexion.
Connection: the most basic type. Can only be opened and closed
InputConnection: represents the connexion to a device from which you can read data
OutputConnection: represents the connexion to a device to which you can write data
StreamConnection: this interface gathers the Input and Output types of connexion
XSL-FO Converter.
HttpConnection: this interface provides the methods and the constants appropriated for a http connection. http
is a request/response protocole and we just have to provide parameters to the request. The response is
formated and corresponds to a content type (html, simple texte, images, xml, wap)
HttpsConnection: this interface extends the HttpConnection interface and proveds the methods and constants
appropriated to a secure connection: http by TLS, SSL v3, WTLS, or WAP TLS
SecureConnection: this interface defines a secure connection to a socket by the same protocoles that
HttpsConnection except WTLS
DatagramConnection: this interface permits us to to send Datagram packets through the network
1.7.3.3. Retrieve the information
Once the connection is retrieved, you can read and write data into the data streams according to the use you
want to make. First of all, you will have to open the input ans output streams thanks to the openInputStream()
ans openOutputStream() methods.
This is an example:
InputStream is = null;
OutputStream os = null;
HttpConnection c = null;
String url = "http://www.myserver.com";
try {
c = (HttpConnection)Connector.open(url);
os = c.openOutputStream();
is = c.openInputStream();
} catch (Exception e) {
throw new IllegalArgumentException("Not an HTTP URL");
} finally {
...
}
getResponseCode(): the response code to the request (e.g.: 200 for OK)
119
Created by XMLmind
XSL-FO Converter.
setRequestMethod(String method): defines the method to pass parameters to the request (HEAD, GET or
POST)
1.7.5. Conclusion
Despite the reduced capabilities of the mobile devices for the network connection, the MIDP profile provides
classes and interfaces sufficent to connect and establish robust and secure applications for theses devices.
Concerning the bluetooth, an optional API is available but it wont be handled in this course.
120
Created by XMLmind
XSL-FO Converter.
Chapter 6. RMI
By completing this course you will :
1. Course
1.1. Introduction
Remote Method Invocation(RMI) allows an easy creation and use of distributed java applications.
1.1.2. RMI
RMIs goal is to create a distributed object integrating plainly the java language and local object model. RMI
extends the java security and robustness to the distributed application world. RMI allows the developer to create
distributed application easily because the syntax and semantic remains the same compared to the usual
applications.
RMI came up with the JDK version 1.1 and has been extended during the next versions.
With RMI, the methods of some objects (call remote objects) can be called from different JVM (distinct
memory location) of the one where the objects are. RMI manages the communication between the server and the
client with TCP/IP and this in a transparent way for the developer.
RMI uses mechanisms and protocols defined and standardized, as sockets and RMP (Remote Method Protocol).
So the developer doesnt have to care of lower layers issues specific for network technologies.
121
Created by XMLmind
XSL-FO Converter.
The RMI architecture defines the way the object have to act, how and when the exceptions can happen, how to
manage the memory and how the called methods give and get parameters.
RMI keeps the security inherent in the java environment thanks to the RMISecurityManager class and the DGC
(Distributed Garbage Collector).
Version 1.2 : The stubs have the same role as the skeletons and the skeletons are no more required.
XSL-FO Converter.
The transport layer is based on TCP/IP connections between machines. It gives the basic connectivity between
JVM.
Furthermore, this layer gives strategy to get through firewalls. The layer builds a table of all the remote objects
available and also listens and answers to the invocations.
This layer uses the Socket and SocketServer classes. It also uses a proprietary protocol RMP. (Remote Method
Protocol).
By using a layered architecture, each layer can be replaced without affecting the rest of the system. This is a
schema showing the information transfer between each layer:
XSL-FO Converter.
The UnicastRemoteObject class defines a not duplicated object, with valid references only if the server process
is active. It brings a support for the references of active objects using TCP/IP stream.
1.2.3.3. Stubs and Skeletons
When our client will call a remote method, this call will be transferred to the stub. Its the local representation of
the remote object. It marshalls the method argument of the remote objects and sends it in the data stream. It also
unmarshalls the return value given by the remote method.
The stubs are the intermediate between the client and the server, and manage the data transfers.
XSL-FO Converter.
The LocateRegistry class is used to get a reference on the registry itself or to create it on a host with a specified
port.
On the server, you have to call the static method createRegistry() which creates a registry, with the port number
you want to use. This method creates and returns a Registry reference allowing us to handle the objects on the
registry.
In the other hand, on the client, you have to get a Registry reference, thanks to the getRegistry() method. This
method takes the address of the server as parameters and optionally its port number (1099 by default)
The function details given by the Registry class is written below in the server and client subsection. All the
methods are static and can throw RemoteException exceptions in case of trouble with the communication.
1.2.3.5. The server
Our server has to set in the RMI registry the local object with the methods remotely callable. Here are some
methods often used on the server.
bind()
public static void bind(String name, Remote obj) throws AlreadyBoundException, MalformedURLException,
RemoteException
With this method you can add an object in the registry by giving a name. It takes as parameters a String which is
the URL of the object and an object of the Remote type. If there is already a link to an object with this URL,
an exception AlreadyBoundException is thrown.
rebind()
public static void rebind(String name, Remote obj) throws RemoteException, MalformedURLException
The way to use this method is the same as the previous one, but with this one, you can link the name with an
object and if this name was already bound to one object, itll be replaced. We would prefer this method instead
of the bind() method to avoid the AlreadyBoundException to be thrown.
unbind()
public static void unbind(String name) throws RemoteException, NotBoundException, MalformedURLException
This method removes the link of the object referenced with the name given as parameters in the RMI registry. If
the link doesnt exist, an exception NotBoundException will be thrown.
1.2.3.6. The client
The client can get a reference to the remote object by using the Registry class with the static method lookup() .
Then you can invoke the remote methods on this object.
The lookup() method is used by the client to call the registry and get a remote object. It takes as parameters a
URL specifying the server name and the name of the service required . It returns a reference of the remote
object with a Remote type. So you have to cast this object with the interface implemented by the remote object.
In fact, the client works with the remote interface and not with the remote object.
Then there are two useful Registry methods on the client.
lookup()
public static Remote lookup(String name) throws NotBoundException, MalformedURLException, RemoteException
The lookup() method is used by the client to get a reference of a remote object. The objects return is of type
Remote. This method takes as parameter the remote object URL with a String type. If the link in the registry
doesnt exist, an exception NotBoundException will be thrown.
list()
public static String[] list() throws RemoteException, MalformedURLException
125
Created by XMLmind
XSL-FO Converter.
This method returns a String array with every names previously stored in the registry.
1.2.3.7. Class distribution
With the JDK version 1.5, client and server have only their own classes and remote interfaces byte-code used. If
a class is required, it will be automatically downloaded (Part 4 : Dynamic Stub class loadind).
1.2.3.8. Summary schema
You have to remember that our interface extends the Remote interface in order to give the remote access for the
class implementing these methods. Furthermore, our getDate() method can throw RemoteException exception. If
we had declare some other methods, they would also have to be included this clause to be accessible by the
clients. All the returned objects by a remote method must implement the interface java.io.Serializable in order
to be sent on the network.
126
Created by XMLmind
XSL-FO Converter.
A remote object
Actually, the way the parameters are given to a remote object depends of its type:
The basics objects are also given by value. That means that when an object is given to a remote method, RMI
sends the object itself, not its references. In the same way, when a remote method returns an object, a copy of
the object itself is sent.
RMI uses a technology call Object Serialization to transform an object in the linear format which can be sent by
the network. The serialize objects can be unmarshalled in the remote JVM memory and used by a java program.
The objects given as parameters must be serializable (implementing the java.io.Serializable interface)
For the remote objects, a reference is given by the remote Skeleton (java.rmi.server.RemoteRef). The user's code
gets back a reference to the stub class implementing the initial interface.
Its in this class that we have to declare the getDate() method which is returning an object with the
java.util.Date type. You can return this object because the Date Object is serializable
1.3.3. MyServer
The Server class will create an object of DateServerImpl type. Then this object will be added in the registry with
the name: MyServer, by using the rebind() method of the Registry class.
package com.supinfo.labosun.server;
import java.rmi.Registry;
import java.rmi.RemoteException;
127
Created by XMLmind
XSL-FO Converter.
try {
DateServerImpl ds = new DateServerImpl();
Registry myRegistry = LocateRegistry.CreateRegistry(); myRegistry.rebind("myServerObject", ds);
} catch (RemoteException re) {
re.printStackTrace();
} catch (Exception e) {
e.printStackTrace();
}
}
}
You can also use the bind() method, but the rebind() method is better because it can add the object in the
registry again, even if the name already exists in the registry.
1.3.4. MyClient
The client will display on the console the date sent by the server. So we have to create an object with the
DateServer (our interface) type by calling the object with the name MyServer in the registry. Then we call the
remote method getDate().
package com.supinfo.labosun.client;
import java.rmi.Registry;
import java.rmi.RemoteException;
1.3.5. Starting
Now you can start the server, and then your clients, to check if everything is working properly.
The propertie java.rmi.server.codebase sets the URL where we can find the files to download. If a programm
executed in a JVM send an object reference to another JVM (as return value of a method), the other JVM will
need to load the class file of this object. When RMI sends the object with the serialization, it adds the URL with
it. So RMI dont send the class files with the serialized objects.
128
Created by XMLmind
XSL-FO Converter.
If the remote JVM needs to load a .class file for an object, it looks for a URL and contact the server chosen for
the file. When the properties java.rmi.server.useCodebaseOnly is active, the JVM loads the classes in the place
specified in the CLASSPATH, or at the URL specified by this property.
By using several combinations of available properties, you can create several RMI configuration systems.
In the Server date example, we can imagine that you have place the DateServerImpl_Stub.class file (the stub) on
a web server. If your programms (client or server) don't have the files in their CLASSPATH, they will look for
them at the URL specified. To specify that, you have to type the followings commands :
java Djava.rmi.server.codebase=http://172.16.X.X/path_des_classes/ MyServer
In these examples, we execute the server but the syntax is the same to execute the client.
You must write the last URL slash (/) in the URL.
The advantage of using a web server is to modify your remote objects without changing anything on the clients.
Usually the web service is started on the server with the RMI server.
The following code is an other way to define the java.rmi.server.codebase properties,but this time in your
application :
System.setProperty("java.rmi.server.codebase",
" http://172.16.X.X:2001/ MyServer");
Example : http://java.sun.com/developer/JDCTechTips/2001/tt0227.html#dynamic
First we check that there are no security manager already existing (in order to not overwrite it), and then we use
the RMISecurityManager object.
You have to use this code before calling the registry using the Registry class.
You can use this security manager on both side (server and client). It depends if you need to load dynamically
your classes.
Then you just have to define the permissions. It consists to set the permissions in a specific text file and this file
will be read when youll create the RMISecurityManager. By convention, this file have the .policy extension.
129
Created by XMLmind
XSL-FO Converter.
Format:
grant signedBy "signer_names", codeBase "URL",
{
permission permission_class_name "target_name", "action",
signedBy "signer_names";
permission permission_class_name "target_name", "action",
signedBy "signer_names";
...
};
The signedBy and codebase values are optional, and the order of these fields does not matter. A signedBy value
indicates the alias for a certificate, it's used to verify the digital signature on the code. An example is
"Duke,James,Oliver". A codeBase value indicates the code source location, an empty codeBase entry signifies
"any code"; it doesn't matter where the code comes from. For exemple : "file:/C:/somepath/api/"
Here we have examples of this file:
grant {
permission java.security.Allpermission
};
We accept all the connection on the host with the IP 172.16.23.32 on the port number 1099.
grant codebase "http://www.labo-sun.com" signedBy "Duke",{
permission java.io.FilePermission "${PROJECT_DIR}\\*", "read, write";
};
This allows code downloaded from "www.games.com", signed by "Duke", permission to read and write into the
project directory..
Permissions list : http://java.sun.com/j2se/1.3/docs/guide/security/permissions.html#PropertyPermission
130
Created by XMLmind
XSL-FO Converter.
131
Created by XMLmind
XSL-FO Converter.