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

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

adalm pluto

Apache Pluto provides you a vast amount of integration types that you could use when it comes to deal with the Portlet development missions. We’ve previously, introduced you different types of Portlets; , , , , and now a Portlet of type Groovy.

Apache Pluto为您提供了大量的集成类型,可用于处理Portlet开发任务。 之前,我们为您介绍了不同类型的Portlet。 , , , , ,现在是Groovy类型的Portlet。

Groovy is a Java Virtual Language (JVM) that’s working inside a JVM seamlessly like any Java Class you may write. Apache Pluto provides you a Groovy Bridge that enables you exposing a Groovy Portlet into your Portal Page without any need for additional cosmetics.

Groovy是一种Java虚拟语言(JVM),可以像您可能编写的任何Java类一样在JVM中无缝运行。 Apache Pluto为您提供了Groovy桥,使您可以将Groovy Portlet暴露到门户页面中,而无需其他外观。

This tutorial is intended for providing you a full-fledged example for registering employees, in which an initial page will be displayed for employee’s information gathering. Once the user has submitted the form the employee registration will start and the confirmation message will be displayed too.

本教程旨在为您提供一个完整的员工注册示例,其中将显示初始页面以收集员工的信息。 用户提交表单后,员工注册将开始,并且确认消息也将显示。

项目结构 (Project Structure)

This figure below should help you recognize one of the best location for putting your Groovy classes as well as showing you the different accompanies files for the project.

下图可以帮助您识别放置Groovy类的最佳位置,并为您显示该项目的不同随附文件。

员工表 (Employee Table)

As being we have a registration employee form, let’s look at the form of the Employee Table and its relevant columns.

由于我们拥有一个注册员工表单,因此让我们看一下“员工表”及其相关列的表单。

As also, you can use below SQL create statement to get Employee Table created into your Schema.

同样,您可以使用下面SQL create语句将Employee Table创建到Schema中。

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;

员工模式 (Employee Model)

In the MVC design pattern and according for the concept of Separation of Concern, we must have an Employee Model that it takes the form of:

在MVC设计模式中,并根据关注分离的概念,我们必须具有以下形式的Employee模型:

Employee.java

Employee.java

package com.journaldev.data;public class Employee {	private int id;	private String name;	private String job;	private int salary;	public int getId() {		return id;	}	public void setId(int 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 int getSalary() {		return salary;	}	public void setSalary(int salary) {		this.salary = salary;	}}

This model will hold the data that’s going back and forth between the different components defined in the application.

该模型将保存在应用程序中定义的不同组件之间来回传递的数据。

将Groovy插件安装到Eclipse中 (Install Groovy Plugin Into Your Eclipse)

To make sure you’re able of getting Groovy sources inside your Maven project, you must install Eclipse Groovy into your Eclipse IDE.

为了确保可以在Maven项目中获取Groovy源,必须将Eclipse Groovy 安装到Eclipse IDE中。

Installing of Eclipse Plugin wouldn’t take much time as you can do that by using the Eclipse install new software facility.

Eclipse插件的安装不会花费很多时间,因为您可以使用Eclipse安装新软件工具来完成安装。

  • From help menu, choose Install New Software.

    从帮助菜单中,选择“ 安装新软件”
  • Paste copied link into Work with input and waiting until Eclipse show you the listed supposed updates that plugin contains.

    将复制的链接粘贴到“使用输入”中,然后等待Eclipse向您显示插件包含的列出的假定更新。
  • Select Groovy-Eclipse (Required) & Click next.

    选择Groovy-Eclipse(必需)并单击下一步。
  • Proceed until your eclipse has installed the Groovy Plugin and restart your Eclipse to make sure your installed Plugin takes effect.

    继续进行操作,直到您的Eclipse安装了Groovy插件,然后重新启动Eclipse以确保已安装的插件生效。
  • Now, from your Maven Project (That you’ve created before), create a Groovy class normally.

    现在,从您之前创建的Maven项目中,正常创建一个Groovy类。

RegisterEmployeePortlet Groovy Portlet (RegisterEmployeePortlet Groovy Portlet)

RegisterEmployeePortlet will be built using the same manner that’s happened inside our introduced example. One major difference that it’s now a Groovy class, where no need for a package declaration nor for a variable types.

RegisterEmployeePortlet将使用与我们介绍的示例中相同的方式构建。 现在它是Groovy类的一个主要区别是,该类不需要包声明或变量类型。

You may write a code analogous for what you’ve written inside your RegisterEmployeePortlet Java class, but for make a distinction we removed those optional constructs that Groovy doesn’t require.

您可以编写类似于您在RegisterEmployeePortlet Java类中编写的代码的代码,但是为了区别起见,我们删除了Groovy不需要的那些可选结构。

RegisterEmployeePortlet.groovy

RegisterEmployeePortlet.groovy

import java.io.IOException;import javax.portlet.ActionRequest;import javax.portlet.ActionResponse;import javax.portlet.GenericPortlet;import javax.portlet.PortletException;import javax.portlet.PortletRequestDispatcher;import javax.portlet.RenderRequest;import javax.portlet.RenderResponse;public class RegisterEmployeePortlet extends GenericPortlet{	public void doView(RenderRequest request, RenderResponse response) throws PortletException, IOException {		if(request.getParameter("status") == null){			// Create a dispatcher			def dispatcher =  this.getPortletContext().getRequestDispatcher("/register/registerEmployee.jsp");			dispatcher.include(request, response);		}		else if(request.getParameter("status") != null &&  request.getParameter("status").equals("initiate")){			// Create a dispatcher			def dispatcher =  this.getPortletContext().getRequestDispatcher("/register/registerEmployee.jsp");			dispatcher.include(request, response);		}		else if(request.getParameter("status") != null &&  request.getParameter("status").equals("success")){			// Create a dispatcher			def dispatcher =  this.getPortletContext().getRequestDispatcher("/register/success.jsp");			dispatcher.include(request, response);		}		else if(request.getParameter("status") != null &&  request.getParameter("status").equals("failed")){			// Create a dispatcher			def dispatcher =  this.getPortletContext().getRequestDispatcher("/register/failure.jsp");			request.setAttribute("exception", request.getParameter("exception"));			dispatcher.include(request, response);		}			}	public void processAction(ActionRequest request, ActionResponse response) throws PortletException, IOException{		// Create request dispatcher		def dispatcher =  this.getPortletContext().getNamedDispatcher("RegisterEmployeeServlet");		try {			// Include			dispatcher.include(request, response);			// Set render parameter			response.setRenderParameter("status", "success");		}		catch(Exception ex){			// Set render parameter			response.setRenderParameter("status", "failed");			response.setRenderParameter("exception", ex.getMessage());		}	}}

Here’s detailed explanation for the code mentioned above:

以下是上述代码的详细说明:

  • RegisterEmployeePortlet Groovy class doesn’t reference a package, as it’s contained inside your resources in the Project Structure above.

    RegisterEmployeePortlet Groovy类未引用包,因为它包含在上面的“项目结构”中的资源内。
  • Groovy is a dynamic language, and so, it’s applicable for you to miss out in the variable types. Alternatively, you must use a def keyword and the Groovy engine would expect the type of the variable from the context.

    Groovy是一种动态语言,因此,它适用于您错过变量类型。 或者,您必须使用def关键字,并且Groovy引擎会从上下文中期望变量的类型。
  • Groovy class is also able of accessing any defined Servlet inside your application.

    Groovy类还能够访问应用程序内部的任何已定义Servlet。

RegisterEmployeePortlet Groovy Portlet描述符 (RegisterEmployeePortlet Groovy Portlet Descriptor)

As you’ve already used a Groovy class for creating a Portlet to be consumed by Apache Pluto, you know that the Portlet must be mentioned in the Portlet deployment descriptor (Portlet.xml).

正如您已经使用Groovy类创建要由Apache Pluto使用的Portlet一样,您知道该Portlet必须在Portlet部署描述符(Portlet.xml)中提及。

The definition of Groovy Portlet inside your Portlet descriptor is little bit different as it’s also contained for additional detailes you must be aware of. Let’s first look at the Portlet.xml and see what are the major differences.

Portlet描述符中的Groovy Portlet的定义稍有不同,因为它也包含在您必须了解的其他细节中。 首先让我们看一下Portlet.xml,看看主要区别是什么。

portlet.xml

portlet.xml

Register Employee
RegisterEmployee
org.apache.portals.bridges.groovy.GroovyPortlet
script-source
classpath:RegisterEmployeePortlet.groovy
auto-refresh
true
Employee Registration
text/html
VIEW
Employee Registration
employee, registration
Employee Registration

Here’s detailed explanation for the code mentioned above:

以下是上述代码的详细说明:

  • Your Groovy Portlet should be of org.apache.portals.bridge.groovy.GroovyPortlet class.

    您的Groovy Portlet应该属于org.apache.portals.bridge.groovy.GroovyPortlet类。
  • You must provide the script-source which will be used later on for specifying the Groovy class that’s responsible of handling the initiated Portlet request.

    您必须提供脚本源 ,该脚本源将在以后用于指定负责处理启动的Portlet请求的Groovy类。
  • You have the ability of providing an optional auto-refresh parameter for enabling applying your modifications instantly. So, just make your modification and refresh the Portlet to get it executed directly.

    您可以提供一个可选的自动刷新参数,以便立即应用您的修改。 因此,只需进行修改并刷新Portlet即可直接执行它。
  • Script-source parameter accepts different types of paths; full physical file, url, uri or by using the reserved keyword classpath as be shown.

    脚本源参数接受不同类型的路径。 完整的物理文件,url,uri或使用保留关键字classpath ,如图所示。

应用程序部署描述符和Maven构建文件 (Application Deployment Descriptor & Maven Build File)

There is no any change on the web deployment descriptor, the same file is used as it’s defined in the Tutorial.

Web部署描述符没有任何变化,使用的文件与教程中定义的文件相同。

web.xml

web.xml

Employee Registration
com.journaldev.servlet.RegisterEmployeeServlet
RegisterEmployeeServlet
RegisterEmployeeServlet
/registerEmployeeServlet
https://java.sun.com/portlet
/WEB-INF/portlet.tld

Just note that Apache Pluto assemble plugin will add some fragments into your web.xml while it builds the application for making the Portlet accessible.

只需注意,Apache Pluto组装插件将在构建使Portlet可以访问的应用程序时将一些片段添加到web.xml中

At the other hand, the all required dependencies are maintained by the Maven build file, look below at the used pom.xml.

另一方面,所有必需的依赖关系都由Maven构建文件维护,请在下面查看使用的pom.xml

pom.xml

pom.xml

4.0.0
com.journaldev
GroovyBridge
war
0.0.1-SNAPSHOT
GroovyBridge
https://maven.apache.org
D:/Apache Pluto/pluto-2.0.3/webapps
org.apache.portals
portlet-api_2.0_spec
1.0
provided
javax.servlet
servlet-api
2.4
provided
javax.servlet
jsp-api
2.0
provided
log4j
log4j
1.2.17
org.apache.pluto
pluto-taglib
1.1.7
mysql
mysql-connector-java
5.1.32
org.codehaus.groovy
groovy
1.1-rc-2
antlr
antlr
2.7.6
asm
asm
2.2
org.apache.portals.bridges
portals-bridges-groovy
1.0.4
org.apache.portals.jetspeed-2
jetspeed-api
${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.6
1.6

EmployeeDAO和ConnectionUtility –数据库处理 (EmployeeDAO & ConnectionUtility – Database Handling)

EmployeeDAO.java

EmployeeDAO.java

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, employee.getId());		query.setString(2, employee.getName());		query.setString(3, employee.getJob());		query.setInt(4, 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;	}}

ConnectionUtility.java

ConnectionUtility.java

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;	}}

RegisterEmployeeServlet –业务处理 (RegisterEmployeeServlet – Business Handling)

If you have noticed that the Groovy class hasn’t provided any code relevant for the registration process, on the contrary, it’s used mainly for handling the required business delegation and the actual work of employee registration got defined inside our RegisterEmployeeServlet, that’s applying the concept of Separation of concern (Soc). Look at below:

相反,如果您注意到Groovy类没有提供与注册过程相关的任何代码,则它主要用于处理所需的业务委托,并且在我们的RegisterEmployeeServlet内部定义了员工注册的实际工作这就是在应用该概念关注分离(Soc)。 看下面:

RegisterEmployeeServlet.java

RegisterEmployeeServlet.java

package com.journaldev.servlet;import java.io.IOException;import javax.servlet.ServletException;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import org.apache.log4j.Logger;import com.journaldev.dao.EmployeeDAO;import com.journaldev.data.Employee;public class RegisterEmployeeServlet extends HttpServlet {	private static final long serialVersionUID = 1L;	Logger logger = Logger.getLogger(RegisterEmployeeServlet.class);    public RegisterEmployeeServlet() {        super();    }	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {		// Create employee		Employee employee = new Employee();		// Fill in required data from the request sent		employee.setId(Integer.parseInt(request.getParameter("employeeID")));		employee.setName(request.getParameter("employeeName"));		employee.setJob(request.getParameter("employeeJob"));		employee.setSalary(Integer.parseInt(request.getParameter("employeeSalary")));		try {			// Asking employeeDAO creating the employee against registered database			Employee createdEmployee = EmployeeDAO.getInstance().createEmployee(employee);			// Print out the created employee information			logger.info("Employee Created"+createdEmployee);		} catch (Exception e) {			// Log the exception			logger.error("Employee Creation Failed", e);			// Throw another exception for notifying the Portlet			throw new ServletException(e);		}	}}

JSP视图 (JSP Views)

As you’ve noticed above, your Groovy Portlet has delegated the control into three different JSP pages:

如上所述,您的Groovy Portlet已将控件委派到三个不同的JSP页面中:

registerEmployee.jsp

registerEmployee.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri='https://java.sun.com/portlet' prefix='portlet'%>
Register Employee
Enter Employee ID:
Enter Employee Name:
Enter Employee Job:
Enter Employee Salary:

success.jsp

success.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri='https://java.sun.com/portlet' prefix='portlet'%>
Register Employee
Congratulations ! you've just add a new employee
Register Another

failure.jsp

failure.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%@ taglib uri='https://java.sun.com/portlet' prefix='portlet'%>
Register Employee
Unfortunately ! you may not be able of registering a new employee cause the reason below
<%=renderRequest.getAttribute("exception")%>
Try Again

员工注册演示 (Employee Registration Demo)

Before getting started demonstrate the employee registration sample, you must have an installed instance of Apache Pluto as well as a JournalDev Portal page. If you didn’t create it before, you need to return back into for getting everything done.

在开始演示员工注册样本之前,您必须已安装Apache Pluto实例以及JournalDev Portal页面。 如果您以前没有创建过它,则需要返回到以完成所有操作。

And you should be able of seeing a new Employee saved against your database:

而且您应该能够看到新的Employee已保存到数据库中:

And if you’ve tried to register the user with the same used ID, you should be able of seeing a message tells you the actual cause of error.

而且,如果您尝试使用相同的使用ID注册用户,则应该能够看到一条消息,告诉您错误的实际原因。

摘要 (Summary)

Groovy is a dynamic JVM language, it’s amazing as you don’t need to be aware of a lot of things you must be aware of when you’re going to use Java language. If you want a Portlet that provides you the maximum gauge of Dynamicity, choose the Groovy as you can change your classes while your JVM is running.

Groovy是一种动态JVM语言,当您在使用Java语言时无需了解很多必须了解的事情时,它就很棒。 如果希望Portlet为您提供最大的动态范围,请选择Groovy,因为您可以在JVM运行时更改类。

Contribute us by commenting below and find below downloaded source code for your practice.

通过在下面评论,为我们贡献力量,并在下面找到您所练习的下载源代码。

翻译自:

adalm pluto

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

你可能感兴趣的文章
学习日记
查看>>
EasyNVR RTSP转RTMP-HLS流媒体服务器前端构建之:内部搜索功能的实现
查看>>
四则运算--封装5.1
查看>>
Python中dunder名称的来历
查看>>
不知道下一步该怎么走
查看>>
并查集,合根植物
查看>>
C++中String类的字符串分割实现
查看>>
HelloWorld
查看>>
CSS3-animations
查看>>
轮廓系数
查看>>
【Luogu1272】重建道路(动态规划)
查看>>
一次开发逻辑规范的总结
查看>>
Android 中 Movie 类显示GIF图片
查看>>
python学习---朴素贝叶斯算法的简单实现
查看>>
Eclipse使用技巧汇总
查看>>
RabbitMQ
查看>>
composite模式(摘自博客园博客)
查看>>
iOS程序执行顺序和UIViewController 的生命周期(整理)
查看>>
Embedding 文献收藏
查看>>
(笔试题)关于C++的虚函数和多态性
查看>>