Hello World -- WebSphere Portal V5 simplest Portlet: Part 1, presented in JSP

Source: Internet
Author: User
Tags i18n tld websphere application server

This article will show you how to develop and deploy a simple Portlet-based JSP in IBM WebSphere Portal version 5.

Introduction
In the first article of the "Hello World" sequence, you have learned how to create a Portlet in Java that can output "Hello, world ". This is exemplary and not a practical method for developing a Portlet. So what is the problem with it? This article (the second article) will solve one of the problems in the future.

In this simplest "Hello world !" In the program, the Java code contains the text "Hello, world" and the logic for displaying the text. If you can separate the logic of the Portlet from that of the presentation logic, the program will do better, because this allows you to create a Portlet that supports different languages and countries. Today, you may not need to create a Portlet for wireless Markup Language (WML) or a German version of Portlet. But what about tomorrow?

You may also work with a graphic designer who frequently changes the appearance and feeling. If the rendering is completed in Java code, a developer and an editing and processing engineer are required to modify the rendering. To solve this problem, you can use JSP to present your Portlet. It allows you to create an independent JSP file. Each file supports one metadata or one country language. The designer can completely control the JSP and modify it without the assistance of developers.

In this article, you will see how to build a Portlet in IBM WebSphere Portal version 5, which calls a JSP for rendering in it. Then we will introduce the JSP and some tags from the Portlet tag library. Finally, create a deployment descriptor, compress all these items into a package, and deploy them to the portal.

Create directory structure
First, you must create a directory structure where you can store your Portlet. The following content will be used in the Portlet:

  • helloWorld/com/ibm/portlets/sample -- The location where the source code is stored.
  • helloWorld/WEB-INF-- Stores the location of the deployment descriptor.
  • helloWorld/WEB-INF/lib-- Location where the JAR file is stored.
  • helloWorld/jsp-- The location where the JSP file is stored.

Important:All directory and environment references are based on Windows conventions. You can make some adjustments to apply them to Unix systems.

Create Java code
The sample directory is where you store the Java source files. Create a directory namedHelloWorld.javaAnd open it with your favorite text editor. The following class you need to type (or cut and paste it to) the createdHelloWorld.javaFile:

package com.ibm.portlets.sample;  //portlet APIs import org.apache.jetspeed.portlet.*;  //Java stuff import java.io.*;  public class HelloWorld  extends PortletAdapter {    public void service(PortletRequest request, PortletResponse response)     throws PortletException,  IOException {      // Include the view jsp     getPortletConfig().getContext().include( "/jsp/view.jsp",            request,  response);   } }

Compile code
After creating the source file, you can compile the Java code. You can use the following script to compile the Portlet in a batch file. First, define some environment variables, such as the environment variables that define the Java installation location (JAVA_HOME). Compiling with JDK provided by WebSphere Application Server is usually a good idea, because this is the environment where you will run the application.

You also need to setPATHEnvironment variable to include the installation location of the Java compiler. You must also setLIBPATHTo point to the directory where the WebSphere JAR file is located.

Next, we will designCP .CP The variable can be built on a line, but to illustrate the different jar files required, we will split it and display it in a branch. Then, the Java compiler is called to compile the code. The Code assumes that you arehelloWorld Directory. Adjust the directory path to the path suitable for your installation.

set JAVA_HOME=C:/WebSphere/AppServer/java set PATH=%JAVA_HOME%/bin set LIBPATH=C:/WebSphere/AppServer/lib set CP=. set CP=%CP%;%LIBPATH%/j2ee.jar set CP=%CP%;%LIBPATH%/dynacache.jar set CP=%CP%;C:/WebSphere/PortalServer/shared/app/portlet-api.jar  javac -classpath %CP% com/ibm/portlets/sample/HelloWorld.java 

If this cannot be compiled for some reason, you must correct the error before continuing the execution. Some common errors are:

  • Input error-Incorrect class name, path, and variable name.
  • Incorrect file name -- the file name must match the class name. In our example, the file name isHelloWorld.javaThe class name isHelloWorld. If you have changed one name, the other name must also be changed.
  • Editor error -- make sure the editor stores the file as text. An editor like a WordPad does not store files as text by default.

Create a JAR File
After compiling the Java source fileWEB-INF/libDirectory to create a jar file. Assume that you arehelloWorld Directory. These statements can be included as part of the batch file you created above. It depends onPATHSet to point to the jar program.

set JAVA_HOME=C:/WebSphere/AppServer/java set PATH=%JAVA_HOME%/bin  jar -cv0f ./WEB-INF/lib/HelloWorldFromJSP.jar com/ibm/portlets/sample/*.class

Create a JSP file
After compiling the Java source code and creating the JAR file, you can concentrate on creating the JSP file. The JSP directory is the location where the JSP source files are stored. Create a file namedview.jspAnd open it with your favorite text editor. Here are some JSP code, you need to type them (or cut and paste them)view.jspFile:

Hello world from the JSP!

That's simple. Now you can package and run these packages! After that, you can look back at the JSP to see what else you can add to support different languages and languages in different countries.

Create deployment descriptor
Now, you need to create two XML files:

  • helloWorld/WEB-INF/web.xml-- Web deployment descriptor.
  • helloWorld/WEB-INF/portlet.xml-- Portlet deployment descriptor.

Web. xml -- web deployment descriptor
The Web deployment descriptor is required by WebSphere Portal. Now the Portlet extends the servlet, so you need to use the Web deployment descriptor to declare the servlet (Portlet) class.

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web         Application 2.3//EN"    "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd"> <web-app id= "HelloWorldFromJSPWebApp">   <display-name>HelloWorldFromJSPPortlet</display-name>   <servlet id="Servlet_1">     <servlet-name>HelloWorldFromJSP</servlet-name>     <servlet-class>com.ibm.portlets.sample.HelloWorld</servlet-class>   </servlet>   <servlet-mapping id="ServletMapping_1">     <servlet-name>HelloWorldFromJSP</servlet-name>     <url-pattern>/HelloWorldFromJSP/*</url-pattern>   </servlet-mapping> </web-app>

Portlet. xml -- Portlet deployment descriptor
The Portlet deployment descriptor defines the Portlet to the portal. Each Portlet maps to a servlet defined in the Web deployment descriptor through the href attribute of the Portlet element. ToBoldThese references. The Portlet must define a unique ID, which can be referenced by each specific Portlet. Each specific Portlet uses the given ID of the href attribute of the concrete-Portlet element to reference the Portlet. These references are displayed in blue.

<?xml version="1.0" encoding="UTF-8" ?> <!DOCTYPE portlet-app-def PUBLIC "-//IBM//DTD Portlet Application         1.1//EN" "portlet_1.1.dtd"> <portlet-app-def>   <portlet-app uid="com.ibm.portlets.sample.HelloWorldFromJSP.1" major-version="1"        minor-version="0">     <portlet-app-name>HelloWorldFromJSP0Portlet</portlet-app-name>     <portlet href="WEB-INF/web.xml#Servlet_1" id="Portlet_1" major-version="1"        minor-version="0">       <portlet-name>HelloWorldFromJSP</portlet-name>      <cache>         <expires>0</expires>         <shared>no</shared>       </cache>       <allows>         <maximized/>         <minimized/>       </allows>       <supports>         <markup name="html">           <view/>         </markup>       </supports>     </portlet>   </portlet-app>   <concrete-portlet-app uid="com.ibm.portlets.sample.HelloWorldFromJSP.1.2">     <portlet-app-name>Concrete HelloWorldFromJSP</portlet-app-name>     <context-param>       <param-name>Author</param-name>       <param-value>tcat@us.ibm.com</param-value>     </context-param>     <concrete-portlet href="#Portlet_1">       <portlet-name>HelloWorldFromJSP</portlet-name>       <default-locale>en</default-locale>       <language locale="en">         <title>Hello World from JSP</title>       </language>     </concrete-portlet>   </concrete-portlet-app> </portlet-app-def>

Errors may occur in many places when these XML files are created. These errors are discovered only when you try to deploy the Portlet to the portal. Note the following:

  • Check each XML element to make sure that it has a closed element.
  • Check whether the class name is entered incorrectly. In this example, check whether the name you give to the class isHelloWorldFromJSP.
  • Make sure that the ID and href attributes match.
  • Make sure that the editor does save the file as text.

Create a war File
Finally, we can create war files for distribution. We will use the standardjarCommand to build the war file. InhelloWorldRun the following command in the directory:

set JAVA_HOME=C:/WebSphere/AppServer/java set PATH=%JAVA_HOME%/bin  jar -cf HelloWorldFromJSP.war WEB-INF jsp

Deploy war files

  1. As the portal Administrator (wpsadmin) Log on to the portal.
  2. In the upper-right corner of the default topic, selectAdministrationLink.

    Figure 1. Administrator Link

  3. Select on the leftPortletsPage, and selectInstallPortlet.

    Figure 2. Install the Portlet Management page

  4. Click.
  5. Locate the location of the war file, select, and click.

    Figure 3. file selection dialog box

  6. Click. This may take some time. Please wait for it to complete.
  7. Verify that the Portlet is helloworld. Click. Wait again until the installation is complete.

    Figure 4. Portlet installation verification Screen

  8. Finally, you will see this confirmation message :.

If an error occurs during deployment, it usually means that you have encountered an error in an XML file. Carefully analyze the error information displayed on the installation page. You can usually find the cause of the error. This information is also recorded in the latest log file:
%WPS_HOME%/log/wps_YYYY.MM.DD-HH.MM.SS.log

Common Errors in XML files are also listed above. You should also check the following:

  • The XML Declaration must be in the first line of the file (No space ).
  • The XML file has a correct name in case of a correct case.

Add a Portlet to a page

  1. Select on the leftPortal user interfacePage.
  2. ClickManage pages.

    Figure 5. Management page Portlet

  3. Then selectMy portalPage.
  4. Click.
  5. Enter a title for the new page.
  6. Click.
  7. Click.
  8. Click the Edit page icon next to the new page.
  9. Click.
  10. SearchHello, And click.
  11. Select the hello World Portlet and click.

    Figure 6. Search for portlets

  12. Click to complete the page layout design.

    Figure 7. Edit Layout Design

  13. In the upper-right corner, click the my portal link and select the page you created.

    Figure 8. portal website of the created Portal

I18n and multiple metadata languages
I18n is an international term used to design an application (your Portlet) in a certain way. applications designed in this way can be used in different languages and regions, you do not need to modify the code. Using your current implementation method, you cannot support multiple country languages or multiple metadata languages. The JSP-based Portlet supports i18n in two ways. Which of the following methods can help you implement multiple metadata languages.

The first supported method is to use multiple JSP to present your Portlet. This support mode allows a Portlet to have different la S, colors, images, texts, and other expressions that are specific to the Supported languages, regions, and languages.

The directory structure of your JSP is/jsp/view.jsp. The portal uses this directory as a base for searching the most suitable JSP. The following is the search sequence for Web browsers in English (USA:

/jsp/html/en_US/view.jsp /jsp/html/en/view.jsp /jsp/html/view.jsp /jsp/view.jsp

The first one foundview.jspUsed to present the Portlet. This Convention allows you to specify different JSP codes for different country languages. For example, you can/jsp/html/de/Create a directoryview.jsp. It reads "Hallo Welt" (this is the result I want, that is, "Hello World" in German "). The central idea is that each language and region can have its own JSP, which provides specialized Layout Design and verbage. What about different metalanguages? In the above search path, you can find that the specified/html/. You can provide JSP for the Portlet in the following path:

/jsp/html/en_US/view.jsp /jsp/html/en/view.jsp /jsp/html/de/view.jsp /jsp/html/view.jsp /jsp/wml/en_US/view.jsp /jsp/wml/en/view.jsp /jsp/wml/de/view.jsp /jsp/wml/view.jsp /jsp/view.jsp

With different JSPs, you can access your Portlet users through the WML Browser, And the Portlet can use/wml/The JSP in the directory structure to perform the search. Therefore, this is the first level that supports i18n.

The second level of help is in the form of resource bundles. For your Portlet, Java resource binding has the ability to put strings into feature files that are easy to interpret and independent from JSP code. You can use the same layout but present the text in the correct national language. To achieve this in WebSphere Portal V5, you need to go deep into the jstl (JSP standard tab library, JSP standard tag Library) World. Previously, you used the IBM Portlet tag library attached to WebSphere Portal to access resource binding from JSP. In V5, you can still do this, but it has discarded text tags and the future vision is jstl.

Introduction to jstl for i18n
Jstl provides various functions for JSP tags. In fact, jstl is a four different tag libraries:

  1. Core tag library-it provides an Expression Language and general control flow tag. For example, if and loop mark.
  2. Formatting tag library-it provides i18n features, such as Retrieving messages from resource binding, date, time, and other formatting tags.
  3. Database Access tag library-allows you to access the database directly from JSP.
  4. XML tag library-Various XML tags that allow you to parse and convert XML documents.

I found that the jstl database and XML section often conflict with other tag libraries in WebSphere Portal. For example, when I include a database tag library into A Portlet using the DB2 data source, a class conflict occurs, which makes it impossible for me to access my database. Also, when I include the XML tag library into A Portlet, I find that my JSP cannot be compiled any more.

These minor issues only occur in WebSphere Portal v5.0.2. I finally found out that the jstl xml tag library conflicted. Therefore, we recommend that you reduce jstl so that it only contains the formatted tag Library and the core tag library, unless you think the JAR file you actually need has a good solution to the conflict.

Speaking of jar files, you can download the jstl library from the standard tag library or find your own image site from the standard tag library entry. This article describes Version 1.0.

When you decompress the downloaded tag library, you will find that several directories have been created. Which of the following are the most interesting ones?libAndtldDirectory. You needlibDirectory to copy two jar files to yourWEB-INF/libDirectory, the two files arejstl.jarAndstandard.jar. All other tag libraries are not required for this exercise and they do not prevent you from executing the Portlet, as described above.

You also need to createWEB-INF/tldDirectory. Setc.tld,c-rt.tld,fmt.tld Andfmt-rt.tldSlavetldDirectory to yourWEB-INF/tldDirectory. These files define the kernel (c) Tag Library and the formatting (FMT) Tag library. Now you may wonder why two differenttldFile. Jstl has a concept of "twin libraries", which is not covered in this article. In short, one can use jstl to represent the language, and the other can use JSP to represent the language.

Yes, it looks like jstl from the external header, while there are two expressions at the backend. You may be dissatisfied and complain that I am not fair to jstl. Yes, I know, I am a little underestimating about jstl. I also encourage you to write an article about jstl. You are an elegant reader. You must interpret some resources that are better than me and learn about jstl. You can use Google or go to your favorite online bookstore. You will find many resources, but remember jstl 1.0!

In order to use jstl in your Portlet to access resource binding, you have made most preparations. You must modifyweb.xmlFile to declare the tag library to be used. Please take a look at the taglib mark after the servlet-mapping mark.

<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE web-app PUBLIC "-//Sun Microsystems, Inc.//DTD Web         Application 2.3//EN"    "http://java.sun.com/j2ee/dtds/web-app_2_3.dtd"> <web-app id= "HelloWorldFromJSPWebApp">   <display-name>HelloWorldFromJSPPortlet</display-name>   <servlet id="Servlet_1">     <servlet-name>HelloWorldFromJSP</servlet-name>     <servlet-class>com.ibm.portlets.sample.HelloWorld</servlet-class>   </servlet>   <servlet-mapping id="ServletMapping_1">     <servlet-name>HelloWorldFromJSP</servlet-name>     <url-pattern>/HelloWorldFromJSP/*</url-pattern>   </servlet-mapping>  <taglib id="TagLibRev_JSTL_fmt">    <taglib-uri>http://java.sun.com/jstl/fmt</taglib-uri>    <taglib-location>/WEB-INF/tld/fmt.tld</taglib-location>  </taglib>  <taglib id="TagLibRev_JSTL_fmt_rt">    <taglib-uri>http://java.sun.com/jstl/fmt_rt</taglib-uri>    <taglib-location>/WEB-INF/tld/fmt-rt.tld</taglib-location>  </taglib>  <taglib id="TagLibRev_JSTL_core">    <taglib-uri>http://java.sun.com/jstl/core</taglib-uri>    <taglib-location>/WEB-INF/tld/c.tld</taglib-location>  </taglib>  <taglib id="TagLibRev_JSTL_core_rt">    <taglib-uri>http://java.sun.com/jstl/core_rt</taglib-uri>    <taglib-location>/WEB-INF/tld/c-rt.tld</taglib-location>  </taglib></web-app>

You have defined all the tag libraries you may use. In this article, you do not need to use all of them, but I think there is no harm in defining them all. In addition, I am here to show you how to define all the tag libraries, so you don't have to worry about it yourself in your Portlet!

Now go to the real JSP code section. To use jstl to format the tag library, add the following instructions at the beginning of JSP to access the formatting tag Library:

<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %>        

You can use similar instructions to use the core library. Now we need to use the formatting library to retrieve messages from resource binding.

<fmt:setBundle basename="nls.labels"/><fmt:message key="helloWorldLabel"/>        

These codes will try to get "helloworldlabel" from the Tag feature file ". If no proper feature file is found, content between opening and closing text tags is displayed by default. In our example, "Hello world from the JSP!" is displayed !". In Java, the search feature file adopts the same method as the search standard resourcebundles:

<basename>_<lang>_<country>_<variant> <basename>_<lang>_<country> <basename>_<lang> <basename>

In this exercise, you need to create two feature files:

/WEB-INF/classes/nls/labels_en.properties /WEB-INF/classes/nls/labels_de.properties

They have the following content:

/WEB-INF/classes/nls/labels_en.properties: helloWorldLabel=Hello World!  /WEB-INF/classes/nls/labels_de.properties: helloWorldLabel=Hallo Welt!

To sum up, the JSP file/jsp/view.jspHas the following content:

<%@ taglib uri="http://java.sun.com/jstl/fmt" prefix="fmt" %><fmt:setBundle basename="nls.labels"/><fmt:message key="helloWorldLabel"/>        

If you set the language to English in the HTML browser, the JSP file, together with the two feature files, will generate the following content:

Figure 9. Hello World Portlet displayed in English

Then, in our HTML browser, set the language to German, then the Portlet will generate:

Figure 10. Hello World Portlet displayed in German

Pretty! However, you may want to ask how to update the Portlet deployed on the portal? You can delete this Portlet and redeploy it. However, in a real portal environment, this will lose user data and deployment information. The last section of this article will briefly introduce how to update a deployed Portlet.

Update a deployed Portlet

  1. As a portal Administrator (wpsadmin) Log on to the portal.
  2. In the upper-right corner of the default topic, selectAdministrationLink.

    Figure 1. Administrator Link

  3. Select on the leftPortletsPage, and then clickInstallTo install the Portlet.
  4. SelectManage applicationsPortlet.

    Figure 11. Manage portlets screens

  5. In the web modules list box, select the helloworldfromjsp. War entry.
  6. Click.
  7. Click.
  8. Find the location of the war file, select it, and click.
  9. Click, which may take some time. Please wait for it to complete.
  10. Verify that the Portlet is indeed helloworldfromjsp, click, and wait until the installation is complete.
  11. Finally, you will see the confirmation information.

Conclusion
This is the end. This article shows you how to use JSP to present your Portlet. This article describes how to compile, compile, and package Java code for A Portlet. First, create a deployment descriptor and package the Portlet for distribution and deployment. Then, deploy the Portlet to your portal. Finally, rewrite the JSP to make it internationalized and update the deployed Portlet. The Portlet development course allows you to learn more. Good luck! Have fun!

Back to Top

References

  • WebSphere Portal product documentation

  • WebSphere Portal
  • Jstl Specification
Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.