struts官方的portlet例子

Struts 2 Portlet Tutorial - Creating a simple Bookmark Portlet

Work in progress
Using version 2.1.1-SNAPSHOT of the portlet plugin
Note that this tutorial assumes that you're familiar with basic Struts 2 web application programming.
If you have not used Struts 2 before, please check out some of the other Struts 2 tutorials first.

Preparations

In this tutorial we will use eclipse as our IDE. If you do not have Eclipse, you can download it from http://www.eclipse.org.

The project itself will be set up using Maven 2. Maven 2 is available from http://maven.apache.org.

If you have not used the maven-eclipse-plugin before, you need to set up the Eclipse workspace with a variable that points to the Maven 2 repository. To do this, type

mvn -Declipse.workspace=<path-to-eclipse-workspace> eclipse:add-maven-repo

Creating the project

We'll use Maven 2 with the Struts 2 Portlet Archetype to create a skeleton project for our portlet application. From the command line, issue the command:

mvn archetype:create -DarchetypeGroupId=org.apache.struts -DarchetypeArtifactId=struts2-archetype-portlet -DarchetypeVersion=2.1.1-SNAPSHOT -DartifactId=bookmark-portlet 
    -DgroupId=com.mycompany -DremoteRepositories=http://people.apache.org/repo/m2-snapshot-repository

This will set up the maven 2 structure for us and also set up the basic configuration needed to create a Struts 2 portlet. The archetype creates a sample HelloWorld portlet that shows off some of the basic principles of Struts 2 portlet programming. To test the set up, type

mvn jetty:run -P pluto-embedded

in a command prompt. Open a browser and point your browser to http://localhost:8080/bookmark-portlet/pluto/index.jsp and play around.

Looking at the basics

To see how the basic HelloWorld example works, let's look at some of the configuration files, starting with the JSR168 portlet descriptor

src/main/webapp/WEB-INF/portlet.xml
<?xml version="1.0" encoding="UTF-8"?>

<portlet-app
   version="1.0"
   xmlns="http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd"
   id="bookmark-portlet">

   <portlet id="HelloPortlet">
      <description xml:lang="EN">Simple hello world portlet</description>
      <portlet-name>HelloPortlet</portlet-name>
      <display-name xml:lang="EN">bookmark-portlet</display-name>
		
      <portlet-class>org.apache.struts2.portlet.dispatcher.Jsr168Dispatcher</portlet-class>
		
      <!-- The namespace for the actions configured for view mode -->
      <init-param>
         <name>viewNamespace</name>
         <value>/view</value>
      </init-param>
		
      <!-- The default action to invoke in view mode. -->
      <init-param>
         <name>defaultViewAction</name>
         <value>index</value>
      </init-param>
		
      <!-- The namespace for the actions configured for edit mode -->
      <init-param>
         <name>editNamespace</name>
         <value>/edit</value>
      </init-param>
		
      <!-- The default action to invoke in edit mode. -->
      <init-param>
         <name>defaultEditAction</name>
         <value>index!input</value>
      </init-param>
		
      <expiration-cache>0</expiration-cache>
		
      <supports>
         <mime-type>text/html</mime-type>
         <portlet-mode>view</portlet-mode>
         <portlet-mode>edit</portlet-mode>
      </supports>
		
      <supported-locale>en</supported-locale>
		
      <portlet-info>
         <title>HelloPortlet</title>
         <short-title>HelloPortlet</short-title>
         <keywords>struts 2,portlet,hello,world</keywords>
      </portlet-info>
   </portlet>  
</portlet-app>

The important parts to notice are the portlet-class and init-param elements. The portlet-class element is always org.apache.struts2.portlet.dispatcher.Jsr168Dispatcher (or a subclass, if you have added some custom functionality). This is the portlet that acts as the dispatcher for the Struts 2 framework, and translates incoming user interaction to action requests that Struts 2 understands. The init-params viewNamespace, defaultViewAction, editNamespace and defaultEditAction set up some defaults for the dispatcher when the portlet encounters a portlet mode without a specific action. Here, we set up the view portlet mode to map to the /view action namespace, and the edit portlet mode to map to the /edit action namespace. We also specify that the default actions for the mentioned portlet modes are index and index!input respectively. We will recognize these namespaces in the next file:

src/main/resources/struts.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
    "-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
    "http://struts.apache.org/dtds/struts-2.0.dtd">

<struts>
   <package name="default" extends="struts-portlet-default" namespace="/view">
        <action name="index" class="com.mycompany.HelloAction">
	    <result>/WEB-INF/jsp/view/index.jsp</result>
	</action>
   </package>
	
   <package name="edit" extends="struts-portlet-default" namespace="/edit">
	<action name="index" class="com.mycompany.UpdateNameAction">
	    <result type="redirectAction">
	        <param name="actionName">index</param>
		<param name="portletMode">view</param>
	    </result>
	    <result name="input">/WEB-INF/jsp/edit/index.jsp</result>
	</action>
    </package>
</struts>

As we can see, the actions for the view portlet mode is in the default package, with /view as namespace, and the actions for the edit portlet mode is in the edit package, with /edit as namespace.

Import the project into Eclipse

Now let's import the project into Eclipse. First, type

mvn eclipse:eclipse -P pluto-embedded

Then start Eclipse (if you have not already done so), and import the project using "File -> Import -> General -> Existing Projects into Workspace". Browse to the folder where you created the project and press finish. Your portlet project should now be setup up with all dependencies in place.

Creating the Bookmark domain object

To represent the bookmarks, we'll create a simple domain object. We'll keep it really simple, so the Bookmark object will only have a name and a url property:

src/main/java/com/mycompany/domain/Bookmark.java
public class Bookmark {
   private String name;
   private String url;

   public Bookmark(String name, String url) {
      this.name = name;
      this.url = url;
   }
	
   public String getName() {
      return name;
   }

   public String getUrl() {
      return url;
   }
}

Adding bookmarks

Adding bookmarks is an operation that logically belongs to the edit portlet mode. So we'll create a simple action for this purpose, and configure it in the edit configuration package. In normal Struts 2 fashion, we'll create an action object with the properties we need:

src/main/java/com/mycompany/AddBookmark.java
public class AddBookmarkAction extends DefaultActionSupport {

   private String name;
   private String url;

   public void setName(String name) {
      this.name = name;
   }

   public void setUrl(String url) {
      this.url = url;
   }

   @Override
   public String execute() throws Exception {
      return SUCCESS;
   }
}

And in struts.xml, remove the existing configuration for the edit package and add an entry for the action:

struts.xml
<package name="edit" extends="struts-portlet-default" namespace="/edit">
	
   <action name="index" class="com.mycompany.AddBookmarkAction">
      <result name="input">/WEB-INF/jsp/edit/index.jsp</result>
   </action>

</package>

Let's create the input form so we have something to display. The form is really simple, with a label and a text field for each of the properties in the Bookmark domain object:

src/main/webapp/WEB-INF/jsp/edit/index.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>

<h2>Manage bookmarks</h2>

<s:form action="index">
   <table>
      <s:textfield name="name" label="Name"/>
      <s:textfield name="url" label="URL"/>
      <s:submit value="Add"/>
   </table>
</s:form>

The textfields maps to the property names we have defined in AddBookmarkAction. Before we continue, let's check that everything is configured correctly and check that our portlet can be run. In a command prompt, change into the directory where you have created the project and issue the command mvn jetty:run -P pluto-embedded. Then open http://localhost:8080/bookmark-portlet/pluto/index.jsp and click on the edit portlet window control. If everything is set up correctly, you should see a form like this:

If you try to submit data in the form, it will obviously not work since we have not implemented any logic to add bookmarks yet. That will be our next task. Since we'll need a PortletPreferences reference, we'll have the action implement the PortletPreferencesAware interface that will instruct Struts 2 to inject this into our action, without the need for us to look it up manually. When we have the reference to the PortletPreferences object, we'll implement logic to store the bookmark (or rather the bookmark's properties, since we can only store Strings in the preferences object):

src/main/java/com/mycompany/AddBookmarkAction.java
public class AddBookmarkAction extends DefaultActionSupport implements PortletPreferencesAware {

   private String name;
   private String url;
	
   private PortletPreferences portletPreferences;

   public void setName(String name) {
      this.name = name;
   }

   public void setUrl(String url) {
      this.url = url;
   }
	
   public void setPortletPreferences(PortletPreferences portletPreferences) {
      this.portletPreferences = portletPreferences;	
   }

   @Override
   public String execute() throws Exception {
      portletPreferences.setValue(name, url);
      portletPreferences.store();
      return SUCCESS;
   }
}

After the bookmark has been stored, we'll just redirect back to the input form:

src/main/resources/struts.xml
<package name="edit" extends="struts-portlet-default" namespace="/edit">
	
   <action name="index" class="com.mycompany.AddBookmarkAction">
      <result type="redirectAction">
         <param name="actionName">index!input</param>
      </result>
      <result name="input">/WEB-INF/jsp/edit/index.jsp</result>
   </action>

</package>

We use a redirectAction result type to redirect back to the input form in proper PRG (Post - Redirect - Get) manner.

Now we can add some bookmarks. We don't get much feedback though, so let's proceed...

Listing the bookmarks

The bookmarks will be listed in the view portlet mode, so we'll create a ListBookmarksAction and configure it in the default package:

src/main/java/com/mycompany/ListBookmarksAction.java
public class ListBookmarksAction extends DefaultActionSupport implements PortletPreferencesAware {
   private List<Bookmark> bookmarks = new ArrayList<Bookmark>();
   private PortletPreferences portletPreferences;

   public List<Bookmark> getBookmarks() {
      return bookmarks;
   }

   public void setPortletPreferences(PortletPreferences portletPreferences) {
      this.portletPreferences = portletPreferences;
   }

   @Override
   public String execute() throws Exception {
      // For simplicity, we'll assume that only bookmarks are stored in the preferences.
      Map<String, String[]> preferencesMap = portletPreferences.getMap();
      for(Map.Entry<String, String[]> entry : preferencesMap.entrySet()) {
         bookmarks.add(new Bookmark(entry.getKey(), entry.getValue()[0]));
      }
      return SUCCESS;
   }
}

Again we use the PortletPreferencesAware to get the PortletPreferences injected in our action. Then we just get all the values from the preferences and add them as a Bookmark instance in an ArrayList.

Obviously, we'll need a jsp to view the list of bookmarks:

src/main/webapp/WEB-INF/jsp/view/index.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>

<strong>Bookmarks</strong>
<p>
   <table>
   <s:iterator value="%{bookmarks}" var="bookmark">
      <tr>
         <td><s:property value="%{name}"/></td>
         <td><a href="<s:property value="%{url}"/>" target="_blank"><s:property value="%{url}"/></a></td>
      </tr>
   </s:iterator>
   </table>
</p>

In the JSP, we just iterate over the list of Bookmarks and print the properties in the iterator loop.

In struts.xml, remove the default package, and add this instead:

src/main/resources/struts.xml
<package name="view" extends="struts-portlet-default" namespace="/view">
   <action name="index" class="com.mycompany.ListBookmarksAction">
      <result>/WEB-INF/jsp/view/index.jsp</result>
   </action>
</package>

When you're ready, go back to a command prompt and start the server again (mvn jetty:run -P pluto-embedded), open a browser and start adding some bookmarks. When you go back to view mode after adding a few, you'll see the bookmarks listed:

Preparing for bookmark management

It would be nice to be able to manage the list of bookmarks, so we'll add delete and edit functionality. All modifications will happen in the edit portlet mode. We'll start by displaying the list of bookmarks in the edit mode as well. The plan is to extend this list to add a delete and an edit link to modify the bookmark entries. We'll do it really simple and just copy the code from the index.jsp for view into the index.jsp for edit and add the links in a new table column:

src/main/webapp/WEB-INF/jsp/edit/index.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>

<h2>Manage bookmarks</h2>

<p>
   <table>
   <s:iterator value="%{bookmarks}" var="bookmark">
      <s:url action="editBookmark!input" id="editUrl">
         <s:param name="oldName" value="%{name}"/>
      </s:url>
      <s:url action="deleteBookmark" portletUrlType="action" id="deleteUrl">
         <s:param name="bookmarkName" value="%{name}"/>
      </s:url>
      <tr>
         <td><s:property value="%{name}"/></td>
         <td><a href="<s:property value="%{url}"/>" target="_blank"><s:property value="%{url}"/></a></td>
         <td><a href="<s:property value="%{editUrl}"/>">Edit</a></td>
         <td><a href="<s:property value="%{deleteUrl}"/>">Delete</a></td>
      </tr>
   </s:iterator>
   </table>
</p>

<s:form action="addBookmark">
   <table>
      <s:textfield name="name" label="Name"/>
      <s:textfield name="url" label="URL"/>
      <s:submit value="Add"/>
   </table>
</s:form>

For the delete url we need to specify that it is a portlet action url since portlet preferences cannot be changed in the render phase. We also need to change our configuration a bit since we'll use this page as index page for edit mode, and not only as the input form for the AddBookmarkAction:

src/main/resources/struts.xml
<package name="edit" extends="struts-portlet-default" namespace="/edit">

   <action name="index" class="com.mycompany.ListBookmarksAction">
      <result>/WEB-INF/jsp/edit/index.jsp</result>
   </action>

   <action name="addBookmark" class="com.mycompany.AddBookmarkAction">
      <result type="redirectAction">
         <param name="actionName">index</param>
      </result>
   </action>

</package>

Here we have added the ListBookmarksAction as the index action, which will display the bookmark list with the input form. When the form is submitted, it will invoke the addBookmark action, and upon success, control is redirected back to the index action. With this new structure, we'll also need to updated the portlet descriptor to use index instead of index!input as the default action for edit mode:

src/main/webapp/WEB-INF/portlet.xml
<!-- The default action to invoke in edit mode. -->
<init-param>
   <name>defaultEditAction</name>
   <value>index</value>
</init-param>

Now you can (re)start the server and see how it works. This is how it looks in edit mode after adding a few entries:

Deleting bookmarks

Let's create the action that handles deletion of bookmarks. It's pretty simple. As with our other actions, we need to get a reference to the PortletPreferences and simply remove the bookmark values from it:

src/main/java/com/mycompany/DeleteBookmarkAction.java
public class DeleteBookmarkAction extends DefaultActionSupport implements PortletPreferencesAware{

   private String bookmarkName;
	
   private PortletPreferences portletPreferences;

   public void setBookmarkName(String bookmarkName) {
      this.bookmarkName = bookmarkName;
   }
	
   public void setPortletPreferences(PortletPreferences portletPreferences) {
      this.portletPreferences = portletPreferences;
   }
	
   @Override
   public String execute() throws Exception {
      portletPreferences.reset(bookmarkName);
      portletPreferences.store();
      return SUCCESS;
   }

}

Pretty simple and straight forward. Next, add a configuration entry for the action in the edit package:

src/main/resources/struts.xml
<action name="deleteBookmark" class="com.mycompany.DeleteBookmarkAction">
   <result type="redirectAction">
      <param name="actionName">index</param>
   </result>
</action>

After a bookmark has been deleted, we redirect back to the index action. Now you should be able to click the Delete link to remove individual entries.

Editing bookmarks

The final step is to edit bookmark entries. When the user clicks the edit link, the portlet will display a new page with an input form and the bookmark values already filled in the text fields. We'll start by creating the jsp file:

src/main/webapp/WEB-INF/jsp/edit.jsp
<%@ taglib prefix="s" uri="/struts-tags" %>

<h2>Edit bookmark</h2>

<s:form action="editBookmark">
   <input type="hidden" name="oldName" value="<s:property value="%{oldName}"/>"/>
   <table>
      <s:textfield name="name" label="Name" value="%{oldName}"/>
      <s:textfield name="url" label="URL"/>
      <s:submit value="Update"/>
   </table>
</s:form>

The oldName hidden field keeps track of which bookmark is beeing edited, since the name is also our id to the entry beeing edited. The actual update of the bookmark will be a "delete and add a new entry":

src/main/java/com/mycompany/EditBookmarkAction.java
public class EditBookmarkAction extends DefaultActionSupport implements PortletPreferencesAware, Preparable, ParameterAware {

   private String oldName;
   private String name;
   private String url;
	
   private PortletPreferences portletPreferences;
   private Map<String, String[]> parameters;
	
   public String getOldName() {
      return oldName;
   }
	
   public void setOldName(String oldName) {
      this.oldName = oldName;
   }
	
   public String getUrl() {
      return url;
   }

   public void setUrl(String url) {
      this.url = url;
   }

   public void setName(String name) {
      this.name = name;
   }
	
   public void setPortletPreferences(PortletPreferences portletPreferences) {
      this.portletPreferences = portletPreferences;
   }
	
   public void setParameters(Map<String, String[]> parameters) {
      this.parameters = parameters;
   }
	
   public void prepare() throws Exception {
      // Since the prepare interceptor is run before the parameter interceptor, 
      // we have to get the parameter "manually".
      this.oldName = parameters.get("oldName")[0];
      this.url = portletPreferences.getValue(oldName, null);
   }
	
   public String execute() throws Exception {
      // The modification is handled as remove/add
      portletPreferences.reset(oldName);
      portletPreferences.setValue(name, url);
      portletPreferences.store();
      return SUCCESS;
   }
}

There's a couple of new things here, but nothing unfamiliar if you have worked with Struts 2 before. We use the Preparable interface to pre-populate the vaules in the edit form, and we use the ParameterAware interface to get a reference to the request parameter map. Other than that, the execute method simply resets the old value for the bookmark and add it with the (possibly) new name.

The last thing we need to do is to add the configuration in the edit package for the new action:

src/main/resources/struts.xml
<action name="editBookmark" class="com.mycompany.EditBookmarkAction">
   <result type="redirectAction">
      <param name="actionName">index</param>
   </result>
   <result name="input">/WEB-INF/jsp/edit/edit.jsp</result>
</action>

Summary

Using Struts 2, we built a simple bookmark portlet utilizing the edit portlet mode for management operations. The tutorial should have given you a basic understanding of portlet development with Struts 2, and that it is not very different from using Struts 2 in a regular web application.

Notes

Instead of using the Maven 2 Jetty plugin to run the tutorial, you can check out the JettyPlutoLauncher which is included in the test sources. Just launch it as a regular Java class in your IDE. And to debug, just launch it in debug mode.

Links

S2PLUGINS:Source code for the tutorial
JSR168 Specification
Struts 2 Portlet Configuration options
Author's blog about portlet related development
Old tutorial for WebWork 2


*****************************************************************************

Struts 2的Portlet的教程 - 创建一个简单的书签的Portlet

工作进展情况
使用portlet的插件版本2.1.1 - SNAPSHOT
注意,本教程假定您熟悉基本的Struts 2的Web应用程序编程。
如果你还没有使用Struts 2之前,请检查出一些其他Struts 2教程第一。

筹备工作

在本教程中,我们将使用Eclipse的IDE的。 如果你没有Eclipse中,你可以下载它http://www.eclipse.org

该项目本身将设立使用Maven 2。 Maven 2的是从现有的http://maven.apache.org

如果你还没有使用Maven的Eclipse的插件之前,你需要设置一个变量的Eclipse工作区的Maven 2存储库点。要做到这一点,键入

  MVN Declipse.workspace = <path-to-eclipse-workspace>月食:添加Maven的回购 

创建项目

我们将使用Struts 2的Portlet的原型的Maven 2创建一个为我们的portlet应用程序的骨架项目。在命令行中,发出以下命令:

  MVN原型:创建DarchetypeGroupId = org.apache.struts - DarchetypeArtifactId = Struts2中的原型portlet的DarchetypeVersion = 2.1.1 - SNAPSHOT - DartifactId =书签的portlet 
     DgroupId = com.mycompany DremoteRepositories = http://people.apache.org/repo/m2-snapshot-repository 

这将设置为我们的Maven 2的结构,还设置了基本的配置,需要创建一个Struts 2的portlet。 原型创建一个示例的HelloWorld portlet中显示了Struts 2的portlet编程的一些基本原则。要测试的成立,类型

  MVN码头:RUN - P冥王星嵌入式 

在命令提示符下。 打开浏览器,将浏览器指向http://localhost:8080/bookmark-portlet/pluto/index.jsp玩耍。

综观的基础知识

要看到基本的HelloWorld示例如何工作的,让我们来看看一些配置文件,与JSR168的portlet描述符开始

src /主/ webapp的/ WEB - INF / portlet.xml中
 <?XML版本=“1.0”编码=“UTF -”?>

 <portlet中的应用
   版本=“1.0”
    XMLNS =“http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd” 
  XMLNS:XSI =“http://www.w3.org/2001/XMLSchema-instance” 
  XSI:的schemaLocation =“http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd http://java.sun.com/xml/ns/portlet/portlet-app_1_0.xsd” 
  ID =“书签的portlet”>

    <portlet id= "HelloPortlet">
       <description xml:lang= "EN">简单的Hello World portlet的</说明>
       <portlet-name> HelloPortlet </ portlet的名称>
       <display-name xml:lang= "EN">书签的portlet </显示名称>
		
       <portlet-class> org.apache.struts2.portlet.dispatcher.Jsr168Dispatcher </ portlet的类>
		
       <! -视图模式配置的行动命名空间- >
       <init-param>
          <名称> viewNamespace </名称>
          <VALUE> /视图</价值>
       </的init - param>
		
       <! - 预设的动作,在查看模式下调用。  - >
       <init-param>
          <名称> defaultViewAction </名称>
          <VALUE>指数</价值>
       </的init - param>
		
       <! -编辑模式配置的行动命名空间- >
       <init-param>
          <名称> editNamespace </名称>
          <VALUE> /编辑</价值>
       </的init - param>
		
       <! - 预设的动作,在编辑模式下调用。  - >
       <init-param>
          <名称> defaultEditAction </名称>
          <VALUE>指数!输入</价值>
       </的init - param>
		
       <expiration-cache> 0 </到期缓存>
		
       <supports>
          <mime-type>文本/ html </ mime类型>
          <portlet-mode>视图</ portlet的模式>
          <portlet-mode>编辑</ portlet的模式>
       </支持>
		
       <supported-locale> EN </支持的语言环境>
		
       <portlet-info>
          <TITLE> HelloPortlet </ TITLE>
          < 标题> HelloPortlet </ 标题>
          <keywords> Struts 2中,portlet的,你好,世界</关键词>
       </ portlet的信息>
    </ portlet中>  
 </ portlet的应用程序>

要注意的重要组成部分 portlet init - param元素。 portlet级的元素总是 org.apache.struts2.portlet.dispatcher.Jsr168Dispatcher(或子类,如果你增加了一些自定义功能) 。这是Struts 2框架的调度行为的portlet,并将其转换传入的用户交互行动的请求,Struts 2的理解。 在init -defaultViewAction,editNamespacedefaultEditAction PARAMS viewNamespace,设立一些调度默认的portlet时遇到一个portlet模式没有一个具体的行动。在这里,我们成立视图 portlet模式映射到/视图行动命名空间,和编辑 portlet模式映射到/编辑行动命名空间。我们还规定,所提到的portlet模式的默认操作是索引索引!输入分别。 在接下来的文件,我们会认识到这些命名空间:

src /主/资源/ struts.xml中
 <?XML版本=“1.0”编码=“UTF -”?>
 <!DOCTYPE Struts的公众
     “ - / /阿帕奇软件基金会/ / DTD Struts配置2.0 / / EN” 
  “http://struts.apache.org/dtds/struts-2.0.dtd”> 

 <struts>
    < 名称=“ 默认 ”=“的struts - portlet的默认命名空间=“/视图 扩展 ”>
         <action name= "index" class= "com.mycompany.HelloAction">
	    的<result> / WEB-INF/jsp/view/index.jsp </结果>
	 </行动>
    </  >
	
    < 名称=“编辑” 延伸 “的struts - portlet的默认的命名空间= =“/编辑 ” >
	 <action name= "index" class= "com.mycompany.UpdateNameAction">
	     <result type= "redirectAction">
	         <param name= "actionName">指数</ PARAM>
		 <PARAM name= "portletMode"> </参数>
	     </结果>
	     <result name= "input"> / WEB-INF/jsp/edit/index.jsp </结果>
	 </行动>
     </  >
 </支柱>

正如我们可以看到, 视图 portlet模式的行动是在默认包中,使用/作为命名空间看法,编辑portlet模式的行动是作为命名空间/编辑, 编辑包。

导入到Eclipse项目

现在,让我们的项目导入到Eclipse。 首先,键入

  MVN日食:日食- P的冥王星嵌入式 

然后启动Eclipse(如果你还没有这样做),并使用“文件导入项目 - >导入 - >常规 - >将现有工作区项目”。 浏览所在的文件夹中创建的项目和按完成。 您的portlet项目现在应该安装全部到位依赖。

创建书签域对象

为代表的书签,我们将创建一个简单的域对象。 我们将保持它真的很简单,所以书签对象只会有一个名字和一个URL属性:

src /主/ JAVA / COM / MyCompany的/域/ Bookmark.java
 公共类书签{
    私人 字符串名称;
    私人 字符串 URL;

    公共书签(String名称, 字符串 URL){
       这个名称=名称;
       这个 URL = URL;
    }
	
    公共 字符串getName(){
       返回的名称;
    }

    公共 字符串的getURL(){
       返回 URL;
    }
 }

添加书签

添加书签是一个操作,在逻辑上属于编辑 portlet模式。 所以我们将创建一个简单的动作为此,在编辑配置包配置。在正常的Struts 2的时尚,我们将创建一个与我们所需要的属性的行动对象:

src /主/ JAVA / COM / MyCompany的/ AddBookmark.java
 公共类AddBookmarkAction 延伸 DefaultActionSupport {

    私人 字符串名称;
    私人 字符串 URL;

    公共无效的setName(String名称){
       这个名称=名称;
    }

    公共无效setUrl( 字符串 URL){
       这个 URL = URL;
    }

    @覆盖
    公共 字符串的execute() 抛出异常
       返回 SUCCESS;
    }
 }

在struts.xml,编辑包中删除现有的配置和添加一个动作中的条目:

struts.xml中
 < 名称=“编辑” 延伸 “的struts - portlet的默认的命名空间= =“/编辑 ” >
	
    <action name= "index" class= "com.mycompany.AddBookmarkAction">
       <result name= "input"> / WEB-INF/jsp/edit/index.jsp </结果>
    </行动>

 </  >

让我们创建输入表单,所以我们要显示的东西。 形式是非常简单的, 书签域对象的每个属性的一个标签和一个文本字段:

src /主/ web应用/ WEB - INF / JSP /编辑/ index.jsp的
 <%的taglib前缀=“S”的uri =“/ Struts的标签”%>

 <H2>管理书签</ H2>

 <s:form action= "index">
    <TABLE>
       <s:textfield name= "name" label= "Name" />
       <s:textfield name= "url" label= "URL" />
       <s:submit value= "Add" />
    </ TABLE>
 </ S:形式>

文本框地图我们在AddBookmarkAction定义该属性的名称。 在我们继续之前,让我们的检查,一切都配置正确,并检查我们的portlet可以运行。在命令提示符下,转变为在您已创建的项目和问题的命令MVN码头目录:RUN - P冥王星嵌入式。 然后打开http://localhost:8080/bookmark-portlet/pluto/index.jsp和点击编辑 portlet窗口控制。 如果一切设置正确,你应该看到一个这样的形式:

如果您尝试提交表单中的数据,它显然将无法正常工作,因为我们还没有实现任何逻辑添加书签。 这将是我们下一步的工作。由于我们需要一个PortletPreferences参考,我们将有行动的实施将指示Struts 2的注入到我们的行动,而不需要我们手动来关注一下吧,PortletPreferencesAware接口。当我们有参考的PortletPreferences对象,我们要实现的逻辑存储书签(或书签的属性,因为我们只能存储在Preferences对象的字符串):

src /主/ JAVA / COM / MyCompany的/ AddBookmarkAction.java
 公共类AddBookmarkAction 延伸 DefaultActionSupport 实现 PortletPreferencesAware {

    私人 字符串名称;
    私人 字符串 URL;
	
    portletPreferences 私人 PortletPreferences;

    公共无效的setName(String名称){
       这个名称=名称;
    }

    公共无效setUrl( 字符串 URL){
       这个 URL = URL;
    }
	
    公共无效setPortletPreferences(PortletPreferences portletPreferences){
        portletPreferences = portletPreferences;	
    }

    @覆盖
    公共 字符串的execute() 抛出异常
       portletPreferences.setValue(名称,URL);
       portletPreferences.store();
       返回 SUCCESS;
    }
 }

已存储的书签后,我们就重定向回输入表单:

src /主/资源/ struts.xml中
 < 名称=“编辑” 延伸 “的struts - portlet的默认的命名空间= =“/编辑 ” >
	
    <action name= "index" class= "com.mycompany.AddBookmarkAction">
       <result type= "redirectAction">
          <param name= "actionName">指数!输入</ PARAM>
       </结果>
       <result name= "input"> / WEB-INF/jsp/edit/index.jsp </结果>
    </行动>

 </  >

我们使用一个redirectAction结果类型重定向回输入表单在适当的PRG(会后-重定向- GET)的方式。

现在,我们可以添加一些书签。 我们虽然没有得到太多的反馈,所以让我们继续... ...

清单中的书签

书签将被列在视图 portlet模式,因此,我们将创建一个 ListBookmarksAction和配置在默认包中:

src /主/ JAVA / COM / MyCompany的/ ListBookmarksAction.java
 公共类ListBookmarksAction 延伸 DefaultActionSupport 实现 PortletPreferencesAware {
    私人名单<Bookmark>书签= 新的ArrayList <Bookmark>();
    portletPreferences 私人 PortletPreferences;

    公开名单<Bookmark> getBookmarks(){
       返回的书签;
    }

    公共无效setPortletPreferences(PortletPreferences portletPreferences){
        portletPreferences = portletPreferences;
    }

    @覆盖
    公共 字符串的execute() 抛出异常
       / /为简单起见,我们假设,只有书签存储的喜好。 
 地图< 字符串字符串 []> preferencesMap = portletPreferences.getMap();
       (Map.Entry的< 字符串字符串 []>项:preferencesMap.entrySet()){
          bookmarks.add(entry.getValue 新的书签(entry.getKey(),()[0]));
       }
       返回 SUCCESS;
    }
 }

我们再次使用PortletPreferencesAware在我们的行动注入了PortletPreferences。然后,我们只是从喜好的所有值,并在一个 ArrayList书签实例添加他们。

显然,我们需要一个jsp查看书签列表:

src /主/ web应用/ WEB - INF / JSP /视图/ index.jsp的
 <%的taglib前缀=“S”的uri =“/ Struts的标签”%>

 <strong>书签</ STRONG>
 <P>
    <TABLE>
    <s:iterator value= "%{bookmarks}" VAR = "bookmark"
       <TR>
          <TD> <s:property value= "%{name}" </ TD>
          <TD> <A HREF =“<s:property value="一般管理 %{url} "/>”目标=“_blank”> <s:property value= "%{url}" </ A> </ TD >
       </ TR>
    </ S:迭代>
    </ TABLE>
 </ P>

在JSP中,我们只是遍历书签列表和打印的特性,在迭代循环。

在struts.xml,删除默认的包,并添加此,而不是:

src /主/资源/ struts.xml中
 < 名称=“查看” 延伸 =“的struts - portlet的默认命名空间=“/视图”>
    <action name= "index" class= "com.mycompany.ListBookmarksAction">
      的<result> / WEB-INF/jsp/view/index.jsp </结果>
    </行动>
 </  >

当你准备好了,回去到命令提示符并重新启动服务器(MVN码头:RUN - P冥王星嵌入式),打开浏览器,并开始加入一些书签。当你回去后查看模式,增加了一些,你会看到列出的书签:

书签管理前的准备工作

这将是很好能够管理书签列表,因此我们将添加删除和编辑功能。 所有的修改将出现在编辑 portlet模式。首先,我们将显示在编辑模式中的书签列表以及。 该计划是扩展这个列表, 添加删除和编辑链接修改的书签条目。我们会做到这一点真的很简单,只是从index.jsp的代码复制编辑的index.jsp,并添加一个新的表列链接:

src /主/ web应用/ WEB - INF / JSP /编辑/ index.jsp的
 <%的taglib前缀=“S”的uri =“/ Struts的标签”%>

 <H2>管理书签</ H2>

 <P>
    <TABLE>
    <s:iterator value= "%{bookmarks}" VAR = "bookmark"
       <s:url action= "editBookmark!input" id= "editUrl">
          <s:param name= "oldName" value= "%{name}" />
       </ S:URL>
       <s:url action= "deleteBookmark" portletUrlType= "action" id= "deleteUrl">
          <s:param name= "bookmarkName" value= "%{name}" />
       </ S:URL>
       <TR>
          <TD> <s:property value= "%{name}" </ TD>
          <TD> <A HREF =“<s:property value="一般管理 %{url} "/>”目标=“_blank”> <s:property value= "%{url}" </ A> </ TD >
          <TD> <A HREF =“<s:property value="一般管理 %{editUrl} "/>”>编辑</ A> </ TD>
          <TD> <A HREF =“<s:property value="一般管理 %{deleteUrl} "/>”>删除</ A> </ TD>
       </ TR>
    </ S:迭代>
    </ TABLE>
 </ P>

 <s:form action= "addBookmark">
    <TABLE>
       <s:textfield name= "name" label= "Name" />
       <s:textfield name= "url" label= "URL" />
       <s:submit value= "Add" />
    </ TABLE>
 </ S:形式>

对于删除 URL,我们需要指定它是一个Portlet操作URL,因为Portlet首选项不能在呈现阶段改变。 我们还需要改变我们的配置了一下,因为我们将使用索引页,此页为编辑模式,不仅输入形式 AddBookmarkAction :

src /主/资源/ struts.xml中
 < 名称=“编辑” 延伸 “的struts - portlet的默认的命名空间= =“/编辑 ” >

    <action name= "index" class= "com.mycompany.ListBookmarksAction">
      的<result> / WEB-INF/jsp/edit/index.jsp </结果>
    </行动>

    <action name= "addBookmark" class= "com.mycompany.AddBookmarkAction">
       <result type= "redirectAction">
          <param name= "actionName">指数</ PARAM>
       </结果>
    </行动>

 </  >

在这里,我们增加一条,作为该指数的行动,这将书签列表中显示输入表单 ListBookmarksAction 。提交表单时,它会调用addBookmark行动,并成功后,控制重定向回索引操作。 有了这个新的结构,我们还需要更新的portlet描述符使用索引 ,而不是指数作为编辑模式的默认动作输入!

src /主/ webapp的/ WEB - INF / portlet.xml中
 <! - 预设的动作,在编辑模式下调用。  - >
 <init-param>
    <名称> defaultEditAction </名称>
    <VALUE>指数</价值>
 </的init - param>

现在,您可以(重新)启动服务器,并看到它是如何工作的。 这是如何在编辑模式下看起来增加了几个项目后:

删除书签

让我们一起创造的行动,处理删除的书签。 它是非常简单的。 至于与我们的其他行动,我们需要得到一个参考PortletPreferences简单地从它删除书签值:

src /主/ JAVA / COM / MyCompany的/ DeleteBookmarkAction.java
 公共类DeleteBookmarkAction 延伸 DefaultActionSupport 实现 PortletPreferencesAware {

    私人 字符串 bookmarkName;
	
    portletPreferences 私人 PortletPreferences;

    公共无效setBookmarkName( 字符串 bookmarkName){
        bookmarkName = bookmarkName;
    }
	
    公共无效setPortletPreferences(PortletPreferences portletPreferences){
        portletPreferences = portletPreferences;
    }
	
    @覆盖
    公共 字符串的execute() 抛出异常
       portletPreferences.reset(bookmarkName);
       portletPreferences.store();
       返回 SUCCESS;
    }

 }

非常简单和直截了当。 接下来,添加一个配置条目的编辑包中的行动:

src /主/资源/ struts.xml中
 <action name= "deleteBookmark" class= "com.mycompany.DeleteBookmarkAction">
    <result type= "redirectAction">
       <param name= "actionName">指数</ PARAM>
    </结果>
 </行动>

书签后已被删除,我们重定向回索引操作。 现在,你应该能够单击“删除”链接删除单个条目。

编辑书签

最后一步是编辑书签条目。 当用户点击编辑链接,portlet将显示输入表单的一个新的页面和书签在文本字段值已经充满。我们将首先创建的JSP文件:

src /主/ web应用/ WEB - INF / JSP / edit.jsp
 <%的taglib前缀=“S”的uri =“/ Struts的标签”%>

 <H2>编辑书签</ H2>

 <s:form action= "editBookmark">
    <INPUT TYPE =“隐藏”名称=“oldName”价值=“<s:property value="一般管理 %{oldName} "/>”/>
    <TABLE>
       <s:textfield name= "name" label= "Name" value= "%{oldName}" />
       <s:textfield name= "url" label= "URL" />
       <s:submit value= "Update" />
    </ TABLE>
 </ S:形式>

oldName隐藏字段跟踪书签beeing编辑,因为这个名字也是我们beeing编辑条目的ID 。 书签的实际更新,将“删除,并添加一个新条目”:

src /主/ JAVA / COM / MyCompany的/ EditBookmarkAction.java
 公共类EditBookmarkAction 延伸 DefaultActionSupport 实现 PortletPreferencesAware,Preparable,ParameterAware {

    私人 字符串 oldName;
    私人 字符串名称;
    私人 字符串 URL;
	
    portletPreferences 私人 PortletPreferences;
    私人地图< 字符串字符串 []>参数;
	
    公共 字符串 getOldName(){
       返回 oldName;
    }
	
    公共无效setOldName( 字符串 oldName){
        oldName = oldName;
    }
	
    公共 字符串的getURL(){
       返回 URL;
    }

    公共无效setUrl( 字符串 URL){
       这个 URL = URL;
    }

    公共无效的setName(String名称){
       这个名称=名称;
    }
	
    公共无效setPortletPreferences(PortletPreferences portletPreferences){
        portletPreferences = portletPreferences;
    }
	
    公共无效setParameters(地图< 字符串字符串 []>参数){
       参数=参数;
    }
	
    公共无效准备() 抛出异常
       / /由于准备拦截器运行参数拦截器之前 
  / /我们已经得到的参数为“手动
   oldName = parameters.get(“oldName”)[0];
       这个 URL = portletPreferences.getValue(oldName,NULL);
    }
	
    公共 字符串的execute() 抛出异常
       / /处理修改为删除/添加 
  portletPreferences.reset(oldName);
       portletPreferences.setValue(名称,URL);
       portletPreferences.store();
       返回 SUCCESS;
    }
 }

还有的几个新的东西在这里,但没有陌生,如果你有Struts 2的工作之前。 我们使用Preparable的接口,预填充编辑表单vaules,我们使用ParameterAware的接口获得请求参数映射。 除此之外, 执行方法简单地重置为书签的旧值和添加(可能)的新名称。

我们需要做的最后一件事是,添加新动作编辑包配置:

src /主/资源/ struts.xml中
 <action name= "editBookmark" class= "com.mycompany.EditBookmarkAction">
    <result type= "redirectAction">
       <param name= "actionName">指数</ PARAM>
    </结果>
    <result name= "input"> / WEB-INF/jsp/edit/edit.jsp </结果>
 </行动>

摘要

使用Struts 2,我们建立了一个简单的书签Portlet的利用编辑portlet的管理操作模式。 本教程应该有给你一个基本的了解与Struts 2的Portlet发展,和它不是一个普通的Web应用程序中使用Struts 2的非常不同。

注释

而不是使用Maven 2的Jetty插件来运行教程,你可以检查出这是包含在测试源JettyPlutoLauncher。只要启动它作为一个普通的Java类在你的IDE。 和调试,在调试模式下启动。

链接

S2PLUGINS:本教程的源代码
JSR168规范
Struts 2的portlet配置选项
作者的博客有关portlet的相关发展
WebWork的旧教程2


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值