博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
adalm pluto_Apache Pluto Portlet&Struts 2集成示例教程
阅读量:2533 次
发布时间:2019-05-11

本文共 21203 字,大约阅读时间需要 70 分钟。

adalm pluto

In earlier tutorials, we’ve developed different types of Portlet. at once and then we learned using of . This time we’re going to develop a Portlet using another famous framework like Apache Struts.

在较早的教程中,我们开发了不同类型的Portlet。 ,然后我们学习了 。 这次,我们将使用另一个著名的框架(例如Apache Struts)来开发Portlet。

is an MVC-based one, we’ve already covered a lot of topics onto Apache Struts as you can refer for all of them, but this is the first time you will get a Struts application deployed into a Portlet container like Apache Pluto.

是基于MVC的 ,我们已经在Apache Struts上介绍了很多主题,您可以参考所有这些主题,但这是您第一次将Struts应用程序部署到Apache Pluto之类的Portlet容器中。

You’re likely going to use Apache Struts Bridge that is already maintained by Apache itself. However, the same application that you’ve implemented before (Employee Registration Form) will be used in this tutorial but with Struts2 framework.

您可能会使用Apache本身已经维护的Apache Struts Bridge 。 但是,本教程中将使用您之前实现的相同应用程序(员工注册表格),但使用Struts2框架。

The main goal of this application is to help you know all the details required for getting the application deployed and running properly onto any JSR-168/JSR-286 compliant Portlet container.

该应用程序的主要目的是帮助您了解将应用程序部署并正确运行到任何符合JSR-168 / JSR-286的Portlet容器上所需的所有详细信息。

最终项目结构 (Final Project Structure)

员工表设计 (Employee Table Design)

This section would clarify you what the Employee Table is and what are these columns used.

本节将向您阐明什么是“雇员表”以及使用了哪些列。

Employee.sql

Employee.sql

CREATE TABLE `employee` (  `EMP_ID` int(11) NOT NULL AUTO_INCREMENT,  `EMP_NAME` varchar(45) DEFAULT NULL,  `EMP_JOB` varchar(45) DEFAULT NULL,  `EMP_SALARY` int(11) DEFAULT NULL,  PRIMARY KEY (`EMP_ID`)) ENGINE=InnoDB AUTO_INCREMENT=3 DEFAULT CHARSET=utf8;

Let’s see the Employee entity (Model) that would be used for holding the data that are going back and forth between the application and the database store.

让我们看一下Employee实体(模型),该实体将用于保存在应用程序和数据库存储之间来回传递的数据。

package com.journaldev.data;public class Employee {	private String id;	private String name;	private String job;	private String salary;	public String getId() {		return id;	}	public void setId(String id) {		this.id = id;	}	public String getSalary() {		return salary;	}	public void setSalary(String salary) {		this.salary = salary;	}	public String getName() {		return name;	}	public void setName(String name) {		this.name = name;	}	public String getJob() {		return job;	}	public void setJob(String job) {		this.job = job;	}}

使用Eclipse IDE创建模板应用程序 (Create Template Application Using Eclipse IDE)

You may save your time instead of getting delve into creating the project by yourself, by using an Apache Struts Archetype. Following steps will help you creating a Struts Portlet application easily.

通过使用Apache Struts Archetype ,您可以节省时间,而不用自己去创建项目。 以下步骤将帮助您轻松创建Struts Portlet应用程序。

  • Add Remote Archetype Catalog https://struts.apache.org/ into your Maven Archetypes.

    将远程原型目录https://struts.apache.org/添加到您的Maven原型中。
  • Create a new Maven project. This time you will get stopped into Catalog selection, instead of using All Catalogs, you must select that’s one registered.

    创建一个新的Maven项目。 这次您将停止进入目录选择,而不必使用所有目录,而必须选择已注册的目录。
  • Fill in the all required information, GroupId, ArtifactId, version, and Package.

    填写所有必需的信息,GroupId,ArtifactId,版本和包。
  • Click Finish and waiting your Eclipse displaying created application into your Project Explorer.

    单击完成,然后等待Eclipse将创建的应用程序显示到项目资源管理器中。
  • Though the application is created successfully, but it’s likely want some of in-hand adjustment as the Archetype’s Maven dependencies isn’t updated somehow. That’s why you may notice some errors in the created application.

    尽管已成功创建了应用程序,但由于未对Archetype的Maven依赖项进行更新,因此可能需要进行一些手动调整。 因此,您可能会在创建的应用程序中发现一些错误。
  • Delete all undesired Java files under com.journaldev package.

    删除com.journaldev软件包下的所有不需要的Java文件。
  • Delete all undesired JSP files/folders under WEB-INF/jsp.

    删除WEB-INF / jsp下所有不需要的JSP文件/文件夹。

修改Maven依赖项 (Modify Maven Dependencies)

The Maven dependency file has got modified to serve two wanted features:

Maven依赖项文件已修改为提供两个所需功能:

  • Add required dependencies for Struts2 and its relevant Portlet container Bridge.

    为Struts2及其相关的Portlet容器Bridge添加所需的依赖关系。
  • Add all required Apache Pluto accompanies that would lead us for a healthy deployment onto Apache Pluto itself.

    添加所有必需的Apache Pluto随附文件,这些文件将引导我们在Apache Pluto本身上进行良好的部署。

pom.xml

pom.xml

4.0.0
com.journaldev
EmployeeRegistration-StrutsBridge
0.0.1-SNAPSHOT
war
EmployeeRegistration-StrutsBridge
2.3.16.3
UTF-8
D:/Apache Pluto/pluto-2.0.3/webapps
org.apache.portals
portlet-api_2.0_spec
1.0
provided
org.apache.struts
struts2-core
${struts2.version}
org.apache.struts
struts2-config-browser-plugin
${struts2.version}
org.apache.struts
struts2-portlet-plugin
2.3.16.3
org.apache.struts
struts2-junit-plugin
${struts2.version}
test
commons-logging
commons-logging
1.1.3
log4j
log4j
1.2.17
junit
junit
4.5
test
javax.servlet
servlet-api
2.4
provided
javax.servlet
jsp-api
2.0
provided
org.apache.portals.bridges
portals-bridges-struts-1.2.7
1.0.4
mysql
mysql-connector-java
5.1.32
${project.artifactId}
org.apache.portals.pluto
maven-pluto-plugin
2.1.0-M3
generate-resources
assemble
maven-war-plugin
2.1.1
${project.build.directory}/pluto-resources/web.xml
maven-antrun-plugin
copy
integration-test
run
delete
clean
true
run
org.apache.maven.plugins
maven-compiler-plugin
3.1
1.7
1.7

员工注册视图 (Employee Registration Views)

As you may know, Apache Struts has considered JSP as a view technology, so we would add a three distinct files, register.jsp, success.jsp and failure.jsp.

您可能知道,Apache Struts将JSP视为一种视图技术,因此我们将添加三个不同的文件, register.jspsuccess.jspfailure.jsp

According for Apache Struts Archetype, the files would be added under WEB-INF/jsp/employee folder.

对于Apache Struts Archetype,文件将添加到WEB-INF / jsp / employee文件夹下。

register.jsp

register.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"	pageEncoding="ISO-8859-1"%><%@ taglib prefix="s" uri="/struts-tags" %>
Register Employee

failure.jsp

failure.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"	pageEncoding="ISO-8859-1"%><%@ taglib prefix="s" uri="/struts-tags" %>
Failure Unfortunately! The Employee hasn't been registered successfully
">Try Again!

success.jsp

success.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"	pageEncoding="ISO-8859-1"%><%@ taglib prefix="s" uri="/struts-tags" %>
Success Congratulations! The Employee has been registered successfully
">Register Another

As you’ve noticed, we used a for providing a form component and its relevant parameters. If you’re not so good with a Struts, it’s so good for you return here to read some articles about it as it’s very elegant framework.

您已经注意到,我们使用了来提供表单组件及其相关参数。 如果您对Struts不太满意,那么回到这里阅读一些有关它的文章就非常好,因为它是一个非常优雅的框架。

Struts Tag library has provided a <url/> Tag for creating a Struts-based link. Struts-based link is a link that uses the Struts framework vocabulary like action.

Struts标记库提供了一个<url />标记,用于创建基于Struts的链接。 基于Struts的链接是使用Struts框架词汇之类的动作的链接。

One important thing you should notice that and it’s the action attribute for the form that’s referred for action it’s name is register. That name would be provided by the struts.xml file that would be discussed later on.

您应该注意的一件重要事情是,为动作引用的表单的动作属性是注册。 该名称将由struts.xml文件提供,稍后将进行讨论。

注册动作 (Register Action)

It’s may be known for you that a . In that, every form submission should be delegated into action based class that’s implemented to be extended from DefaultActionSupport class. Following RegisterAction Struts action class.

您可能已经知道 。 这样,每个表单提交都应该委托给基于动作的类,该类已实现为从DefaultActionSupport类扩展。 跟随RegisterAction Struts动作类。

package com.journaldev.action;import java.io.IOException;import java.sql.SQLException;import javax.portlet.PortletPreferences;import org.apache.log4j.Logger;import org.apache.struts2.dispatcher.DefaultActionSupport;import org.apache.struts2.portlet.interceptor.PortletPreferencesAware;import com.journaldev.dao.EmployeeDAO;import com.journaldev.data.Employee;public class RegisterAction extends DefaultActionSupport implements PortletPreferencesAware {	private static Logger logger = Logger.getLogger(RegisterAction.class);	private static final long serialVersionUID = 1L;	private PortletPreferences preferences;	private String id;	private String name;	private String job;	private String salary;	public PortletPreferences getPreferences() {		return preferences;	}	public void setPreferences(PortletPreferences preferences) {		this.preferences = preferences;	}	@Override	public void setPortletPreferences(PortletPreferences prefs) {		this.preferences = prefs;	}	@Override    public String execute() throws Exception {		try {			Employee employee = new Employee();			employee.setId(id);			employee.setName(name);			employee.setJob(job);			employee.setSalary(salary);			// Register Employee			employee = EmployeeDAO.getInstance().createEmployee(employee);			logger.debug("Employee Has Registered");			return "SUCCESS";		} catch (IllegalAccessException | ClassNotFoundException | SQLException | IOException e) {			logger.debug("Registration Process Has Failed",e);			return "FAILURE";		}    }	public String getId() {		return id;	}	public void setId(String id) {		this.id = id;	}	public String getName() {		return name;	}	public void setName(String name) {		this.name = name;	}	public String getJob() {		return job;	}	public void setJob(String job) {		this.job = job;	}	public String getSalary() {		return salary;	}	public void setSalary(String salary) {		this.salary = salary;	}}

Here’s detailed explanation for the RegisterAction class figured out:

这里是对RegisterAction类的详细说明:

  • Notice the class’s properties id, name, job and salary are analogous for these parameters’ names that are provided by the register.jsp page.

    请注意,类的属性id,名称,工作和薪水与register.jsp页面提供的这些参数的名称相似。
  • RegisterAction has overridden an execute method for serving the employee registration purposes.

    RegisterAction已覆盖用于服务员工注册目的的execute方法。
  • Struts framework will binded all form’s parameters with those corresponding ones at the action class. Id, name, job and salary will be passed automatically.

    Struts框架会将所有表单的参数与动作类中的那些对应参数绑定在一起。 ID,姓名,工作和薪水将自动传递。
  • RegisterAction has used the EmployeeDAO (The same utility class that we’ve impelemnted previously, that it would handle the all database manipulation code) for registering the employee instance.

    RegisterAction使用EmployeeDAO(我们之前介绍的相同的实用程序类,它将处理所有数据库操作代码)注册员工实例。
  • In case the registration process has failed the Struts framework would take you into failure page. The page success.jsp is that one, the Struts framework will redirect you into as soon as the registration has finished successfully.

    如果注册过程失败,Struts框架会将您带到失败页面。 一旦成功完成注册,Struts框架就会将页面success.jsp重定向到该页面。

Struts应用程序配置和Portlet.xml (Struts Application Configuration & Portlet.xml)

Struts.xml file is an XML-based file that used by the Apache Struts framework for getting connected the different components that you’re developed.

Struts.xml文件是基于XML的文件,Apache Struts框架使用该文件来连接所开发的不同组件。

Wiring of mentioned actions within your <s:form/> with the Struts-action must be defined as an entries within struts.xml file. Following Struts configuration file required:

必须将<s:form />中提到的动作与Struts-action的连线定义为struts.xml文件中的一项。 需要以下Struts配置文件:

struts.xml

struts.xml

/WEB-INF/jsp/employee/register.jsp
/WEB-INF/jsp/employee/success.jsp
/WEB-INF/jsp/employee/failure.jsp

Integration of Apache Struts with the given Portlet container has been done through using of portlet.xml file. In that, a new init-param should be used for this purpose. Following the Portlet.xml file that’s used.

通过使用portlet.xml文件,已将Apache Struts与给定的Portlet容器集成在一起。 因此,应为此目的使用新的init参数。 在使用的Portlet.xml文件之后。

portlet.xml

portlet.xml

Register Employee
RegisterEmployee
org.apache.struts2.portlet.dispatcher.Jsr286Dispatcher
actionPackages
com.journaldev.action
viewNamespace
/employee
defaultViewAction
index
text/html
view
en
Register Employee
Register Employee
Employee,Registration

Here’s detailed explanation for both of the Struts and Portlet configuration files listed above:

这是上面列出的Struts和Portlet配置文件的详细说明:

  • Your Portlets must be an instance of JSR286Dispatcher class.

    您的Portlet必须是JSR286Dispatcher类的实例。
  • We’ve defined three additional parameters, actionPackages, viewNamespace and defaultViewAction.

    我们定义了三个附加参数,actionPackages,viewNamespace和defaultViewAction。
  • Defined defaultViewAction will be used once you’ve opened the Portal page that’s contained the deployed Portlet. As being index is the value, the index should be defined as an action in the struts.xml file.

    打开包含已部署Portlet的Portal页面后,将使用已定义的defaultViewAction 。 由于索引是值,因此应该将索引定义为struts.xml文件中的操作。
  • Defined actionPackages will be used for determining the Java package that contains the Struts-actions classes.

    定义的actionPackages将用于确定包含Struts-actions类的Java包。
  • Defined viewNamespace will determine the namespace for the actions configured for view mode. It’s also applicable to define actions for edit and help modes.

    定义的viewNamespace将确定为view mode配置的动作的名称空间。 它也适用于定义edithelp模式的动作。
  • Struts configuration file has defined an register action that would be used as soon as the user has submitted the form’s register.

    Struts配置文件已定义一个register动作,用户提交表单的注册后将立即使用该动作。
  • Defined register action has had two different results, success and failure are used to determine the next view that Struts framework uses after finishing the calling of execute against action class.

    定义的register动作具有两个不同的结果,成功和失败用于确定在完成针对动作类的execute调用之后Struts框架使用的下一个视图。

部署描述符 (Deployment Descriptor)

web.xml

web.xml

RegisterEmployee
struts2
org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
struts2
/*

员工DAO和ConnectionUtility (EmployeeDAO & ConnectionUtility)

Following below both of EmployeeDAO and ConnectionUtility that help you getting database connection and creating the user after then.

在EmployeeDAO和ConnectionUtility之下,可以帮助您获得数据库连接并在此之后创建用户。

package com.journaldev.dao;import java.io.IOException;import java.sql.Connection;import java.sql.PreparedStatement;import java.sql.SQLException;import com.journaldev.dao.utility.ConnectionUtility;import com.journaldev.data.Employee;public class EmployeeDAO {	public static EmployeeDAO employeeDAO = null;	private EmployeeDAO(){	}	public static EmployeeDAO getInstance(){		synchronized(EmployeeDAO.class){			if(employeeDAO == null){				employeeDAO = new EmployeeDAO();			}		}		return employeeDAO;	}	public Employee createEmployee(Employee employee) throws SQLException, IllegalAccessException, IOException, ClassNotFoundException{		// Get connection instance		Connection connection = ConnectionUtility.getInstance().getConnection();		// Create Prepared Statement		PreparedStatement query = connection.prepareStatement("INSERT INTO EMPLOYEE VALUES (?,?,?,?)");		// Set variables		query.setInt(1, Integer.parseInt(employee.getId()));		query.setString(2, employee.getName());		query.setString(3, employee.getJob());		query.setInt(4, Integer.parseInt(employee.getSalary()));		try {			// Execute			query.execute();			// Return employee instance			return employee;		}		catch(Exception e){			// Close statement			query.close();			// Close connection			connection.close();			// Throw another exception for notifying the Servlet			throw new SQLException(e);		}	}	public boolean deleteEmployee(Employee employee){		return false;	}	public boolean updateEmployee(Employee employee, int employeeId){		return false;	}}
package com.journaldev.dao.utility;import java.io.IOException;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.util.Properties;public class ConnectionUtility {	private static ConnectionUtility connectionUtiliy = null;	private Connection connection = null;	private ConnectionUtility() {	}	public static ConnectionUtility getInstance() throws IOException, IllegalAccessException, SQLException, ClassNotFoundException{		// Synchronized against connectionUtility instance		synchronized(ConnectionUtility.class){			// Check whether the connectionUtility is null or not			if(connectionUtiliy == null){				// Create a properties instance				Properties properties = new Properties();				// Load properties from classpath				properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("connection.properties"));				// Set connection with connectionUtility				connectionUtiliy = new ConnectionUtility();				// Load driver class				Class.forName("com.mysql.jdbc.Driver");				// Create connection				connectionUtiliy.setConnection(DriverManager.getConnection("jdbc:mysql://localhost:3306/journaldev", properties));			}			return connectionUtiliy;		}	}	public Connection getConnection() throws ClassNotFoundException, SQLException, IOException {		if(connection.isClosed()){			// Create a properties instance			Properties properties = new Properties();			// Load properties from classpath			properties.load(Thread.currentThread().getContextClassLoader().getResourceAsStream("connection.properties"));			// Load driver class			Class.forName("com.mysql.jdbc.Driver");			// Create connection			connectionUtiliy.setConnection(DriverManager.getConnection("jdbc:mysql://localhost:3306/journaldev", properties));		}		return connection;	}	public void setConnection(Connection connection) {		this.connection = connection;	}}

注册员工演示 (Registration Employee Demo)

To get started showing your Portlet, you must logged into your Apache Pluto and navigating into JournalDev page. Typically, we have added a Portal page that’s contained for our developed Portlet. The process of creating a Portal page and add the Portlets upon it is discussed at .

要开始显示Portlet,您必须登录Apache Pluto并导航到JournalDev页面。 通常,我们为开发的Portlet添加了一个Portal页面。 讨论了创建Portal页面并在其上添加Portlet的过程。

摘要 (Summary)

Apache Struts is an elegant framework that’s used for creating an MVC-based enterprise application. Apache has also provided you a ready made Portlet bridge that could be used for creating JSR-168/286 Struts-based Portlet. Contribute us by commenting below and find the downloaded source code.

Apache Struts是一个优雅的框架,用于创建基于MVC的企业应用程序。 Apache还为您提供了现成的Portlet桥,可用于创建基于JSR-168 / 286基于Struts的Portlet。 通过在下面评论来贡献我们,并找到下载的源代码。

翻译自:

adalm pluto

转载地址:http://ouqzd.baihongyu.com/

你可能感兴趣的文章
VsVim - Shortcut Key (快捷键)
查看>>
C++练习 | 模板与泛式编程练习(1)
查看>>
HDU5447 Good Numbers
查看>>
08.CXF发布WebService(Java项目)
查看>>
java-集合框架
查看>>
RTMP
查看>>
求一个数的整数次方
查看>>
点云PCL中小细节
查看>>
铁路信号基础
查看>>
RobotFramework自动化2-自定义关键字
查看>>
[置顶] 【cocos2d-x入门实战】微信飞机大战之三:飞机要起飞了
查看>>
BABOK - 需求分析(Requirements Analysis)概述
查看>>
第43条:掌握GCD及操作队列的使用时机
查看>>
Windows autoKeras的下载与安装连接
查看>>
CMU Bomblab 答案
查看>>
微信支付之异步通知签名错误
查看>>
2016 - 1 -17 GCD学习总结
查看>>
linux安装php-redis扩展(转)
查看>>
Vue集成微信开发趟坑:公众号以及JSSDK相关
查看>>
技术分析淘宝的超卖宝贝
查看>>