portlet_Portlet Servlet JSP

portlet

In the previous tutorials that we’ve examined before, a RenderResponse writer is used mainly for writing the Portlets’ fragments into Portal page. This way of forming the Portlets’ contents isn’t used elegantly as it’s also doesn’t adhere the separation of concern (SoC) concept.

在我们之前检查过的先前教程中,RenderResponse编写器主要用于将Portlet的片段写入Portal页面。 形成Portlet内容的这种方式没有很好地使用,因为它也不遵循关注点分离(SoC)概念。

Combining the business code and UI fragments cohesively would lead us to code hard to maintain, hard to trace and less agility. As such, it’s important for you to make some sort of separation between your parts; UI and Business.

统一地结合业务代码和UI片段将导致我们难以维护,难以跟踪且缺乏敏捷性的代码。 因此,对您的各个部分进行某种分离非常重要。 用户界面和业务。

Portlet Servlet JSP (Portlet Servlet JSP)

This tutorial will help you getting all of these concepts achieved as it’s would show you a full example of how can orchestrate between Portlets, JSPs and Servlets for making an employee registration mission so organized.

本教程将帮助您实现所有这些概念,因为它向您展示了如何在Portlet,JSP和Servlet之间进行协调以使员工注册任务如此有条理的完整示例。

Registration form that we’re going to implement, is a full-fledged one, as you can fill in the all required information for the employee that you may want be registered. Information like employee identifier, employee name, employee job and employee salary the Portlet accepts and the database should retain.

我们将要执行的注册表格是完整的表格,因为您可以填写想要注册的员工的所有必需信息。 Portlet接受并且数据库应保留的信息,例如员工标识符,员工姓名,员工职位和员工薪水。

Any professional application must provide the end users a confirmation messages either the process has finished successfully or something went wrongly.

任何专业的应用程序都必须向最终用户提供确认消息,说明该过程已成功完成或出现了错误。

In between, you will learn the all detailed fine-grained information that may help you achieve the integration between Portlets, JSPs and Servlets. Different integration principles like RequestDispatcher, Portlet Tag Library, handling exceptions and the way in which can leverage all of these principles to get everything done smoothly.

在这两者之间,您将学习所有详细的细粒度信息,这些信息可以帮助您实现Portlet,JSP和Servlet之间的集成。 不同的集成原则,例如RequestDispatcher,Portlet标记库,处理异常以及可以利用所有这些原则来顺利完成所有工作的方式。

Portlet标签库 (Portlet Tag Library)

JavaServer Pages can use Portlet Tag Library to get access of Portlet functionality. Any JSP pages can import the Portlet Tag library that’s already provided by pluto-taglib dependency.

JavaServer Pages可以使用Portlet标记库来访问Portlet功能。 任何JSP页面都可以导入pluto-taglib依赖项已经提供的Portlet标记库。

<defineObjects/>, <param/>, <actionURL/>, <renderURL/> and <namespace/>, all of these are provided Tags for being used by the JavaServer Pages.

<defineObjects/><param/><actionURL/><renderURL/><namespace/> ,所有这些都提供了标记,供JavaServer Pages使用。

The <defineObjects/> Tag, is used to define several objects from the calling Portlet’s request in the JSP page. Using of <defineObjects/> would define three different variables to be used from within your JSP scriptlets. These variables are portletConfig, renderRequest and renderResponse.

<defineObjects/>标记用于在JSP页面中根据调用Portlet的请求定义几个对象。 使用<defineObjects/>将在您的JSP脚本中定义三个不同的变量。 这些变量是portletConfigrenderRequestrenderResponse

The <param> Tag, is used to send a parameters for the <actionURL/> and <renderURL/>. Every parameter must be a pair of name and value.

<param>标记用于发送<actionURL/><renderURL/> 。 每个参数必须是一对名称和值。

The <actionURL/> and <renderURL/> are used for generating an action URL for calling action phase and a render URL for calling render phase, respectively. Both of them has provided a var attribute that would be used later on in the form action or link’s target.

<actionURL/><renderURL/>分别用于生成用于调用操作阶段的操作URL和用于调用渲染阶段的渲染URL。 两者都提供了var属性,稍后将在表单操作或链接的目标中使用。

The <namespace/> is used for generating a unique name that would be used with the JavaScript code for making unique JavaScript variables, libraries or resources.

<namespace/>用于生成唯一的名称,该名称将与JavaScript代码一起使用,以生成唯一JavaScript变量,库或资源。

Portlet请求分派器 (Portlet Request Dispatcher)

Similar like Servlet, RequestDispacther is to dispatch the request into another Web resource. However, PortletRequestDispatcher is the object that you may got if you’ve called getRequestDispatcher() or getNamedDispatcher() against PortletContext object.

与Servlet类似, RequestDispacther请求分派到另一个Web资源中。 但是,如果针对PortletContext对象调用了getRequestDispatcher()getNamedDispatcher() ,则可能会获得PortletRequestDispatcher

The difference here is that, the getRequestDispatcher() has used a path for locating a Web resource, while getNamedDispatcher() has used a defined name for locating a Web resource.

此处的区别在于, getRequestDispatcher()使用了路径来定位Web资源,而getNamedDispatcher()使用了已定义的名称来定位Web资源。

You may invoke include and forward upon your PortletRequestDispatcher. Using of forward will close the output stream after it has been invoked, whereas, the include method leaves the output stream open.

您可以在PortletRequestDispatcher调用includeforward 。 使用forward将在调用输出流后将其关闭,而include方法将使输出流保持打开状态。

员工表设计 (Employee Table Design)

Before getting started implementing the registration form, let’s see the structure of the Table and its relevant columns as well as the SQL statement that lead you to create similar one into your database.

在开始实施注册表单之前,让我们看一下Table的结构及其相关的列,以及使您在数据库中创建类似表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=4 DEFAULT CHARSET=utf8;

员工PO​​JO (Employee POJO)

As we’ve stated the Employee Table previously, it’s very easy for you to expect the Employee POJO.

正如我们之前所说的Employee Table,您很容易期望Employee POJO。

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

As you’ve seen, Employee POJO is just a normal Java bean that’s contained for four different attributes with their gets and sets methods. id, name, job and salary are attributes that the user must provide for getting employee registered normally.

如您所见,Employee POJO只是一个普通的Java bean,它包含四个具有get和set方法的不同属性。 ID,名称,工作和薪水是用户必须提供的属性,以使雇员正常注册。

设计图 (Design View)

Mainly, vast amount of frameworks that were implemented had considered MVC (Model, View & Controller) as a base design for them. MVC is a design pattern, that’s aimed to make concern separation in order to allow develop components in a loosely coupled manner.

主要是,已实施的大量框架已将MVC(模型,视图和控制器)视为其基本设计。 MVC是一种设计模式,旨在分离关注点,以允许以松散耦合的方式开发组件。

Being MVC is a design pattern, it’s applicable for you to design your Portlets to be MVC-compliance. JSPs can be used for viewing purposes, Portlets as a controllers and a simple POJO (Plain Old Java Object) can be your models.

成为MVC是一种设计模式,适用于将Portlet设计为符合MVC的情况。 JSP可以用于查看目的,Portlet作为控制器,简单的POJO(普通Java对象)可以作为您的模型。

Find below sequence diagram that shows you the way in which the registration process being handled and how the proposed parts are working collectively making this mission possible.

在下面的序列图中查找,该流程图向您显示了处理注册过程的方式以及所提议的部分如何共同工作,从而使此任务成为可能。

Here’s detailed explanation for the diagram listed above:

这是上面列出的图的详细说明:

  • RegisterEmployee JSP page is the view that it would be used for gathering the information for employee being registered.

    RegisterEmployee JSP页面是用于收集正在注册的员工信息的视图。
  • RegisterEmployeePortlet is the controller, it would be used for handling the business and dispatching into next coming view. We’ve added a RegisterEmployeeServlet as a complement component that’s aimed to handle the employee registration business.

    RegisterEmployeePortlet是控制器,它将用于处理业务并将其分派到下一个即将到来的视图中。 我们添加了RegisterEmployeeServlet作为补充组件,旨在处理员工注册业务。
  • EmployeeDAO and ConnectionUtility are just a components that are contained all relevant database code.

    EmployeeDAO和ConnectionUtility只是包含所有相关数据库代码的组件。

员工注册视图 (Employee Registration Views)

We’ve defined different views for the employee registration purpose, as the process of registration may result in a success or failure status, we’ve added two additional views for the main one (registerEmployee.jsp). The success.jsp and failure.jsp should help the user getting a confirmation messages, to know whether the process has been completed successfully or it’s failed and what’s the reason of failure.

我们为员工注册目的定义了不同的视图,因为注册过程可能会导致成功或失败状态,所以我们为主要视图添加了另外两个视图( registerEmployee.jsp )。 success.jspfailure.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'%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Register Employee</title>
</head>
<body>
	<portlet:actionURL var="registerLink"/>
	<form action="<%=registerLink%>" method="POST">
		<table width="100%">
			<tr width="60%">
				<td>Enter Employee ID:</td>
				<td><input name="employeeID" /></td>
			</tr>
			<tr width="60%">
				<td>Enter Employee Name:</td>
				<td><input name="employeeName" /></td>
			</tr>
			<tr width="60%">
				<td>Enter Employee Job:</td>
				<td><input name="employeeJob" /></td>
			</tr>
			<tr width="60%">
				<td>Enter Employee Salary:</td>
				<td><input name="employeeSalary" /></td>
			</tr>
			<tr width="60%" align="center">
				<td colspan="2"><input type="submit" value="Register" /></td>
			</tr>
		</table>
	</form>
</body>
</html>

Here’s detailed explanation for the code listed above:

这是上面列出的代码的详细说明:

  • The form of employee registration doesn’t contain any strange code except that’s related for <portlet:actionURL/> Tag. Mainly, action URL is used for generating a URL would call the prcoessAction() when it’s clicked.

    员工注册的形式不包含任何奇怪的代码,除了与<portlet:actionURL/>标记相关的代码。 主要是,操作URL用于生成单击URL时会调用prcoessAction()的URL。
  • We’ve used generated action URL to form the action of the whole form. Notice using of Scriptlets for accessing the generated URL.

    我们使用生成的动作URL来构成整个表单的动作。 请注意使用Scriptlets访问生成的URL。

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'%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Register Employee</title>
</head>
	<portlet:renderURL var="registerAnother">
		<portlet:param name="status" value="initiate"/>
	</portlet:renderURL>
	<img src="<%=request.getContextPath()%>/images/success.jpg" name="<portlet:namespace/>Success"/>
	<body>
		<span>Congratulations ! you've just add a new employee</span><br/><a href="<%=registerAnother%>">Register Another</a>
	</body>
</html>

Here’s detailed explanation for the code listed above:

这是上面列出的代码的详细说明:

  • We’ve used <renderURL/> to generate a render URL that’s used for invoking render phase. One parameter has been passed, it’s status which will be used for dispatching purpose.

    我们已经使用<renderURL/>来生成用于调用渲染阶段的渲染URL。 已传递一个参数,该参数的状态将用于调度目的。
  • Implicit objects like request, response that are received by the JSP and Servlet can be used but with a limitation as many of their methods either perform no operation or return null when used inside a Portlet container.

    可以使用JSP和Servlet接收的隐式对象(例如requestresponse ,但是有一个局限性,因为它们的许多方法在Portlet容器中使用时都不执行任何操作或返回null。

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'%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Register Employee</title>
</head>
	<portlet:defineObjects/>
	<portlet:renderURL var="registerAnother">
		<portlet:param name="status" value="initiate"/>
	</portlet:renderURL>
	<body>
		<span>Unfortunately ! you may not be able of registering a new employee cause the reason below</span>
		<br/>
		<br/>
		<img src="<%=request.getContextPath()%>/images/failed.jpg" name="<portlet:namespace/>Failed"/>
		<span style="font-size:small ;font-style: italic;color: red;font-weight: bold;">
			<%=renderRequest.getAttribute("exception")%>
		</span>
		<br/>
		<br/>
		<a href="<%=registerAnother%>">Try Again</a>
	</body>
</html>

Here’s detailed explanation for the code listed above:

这是上面列出的代码的详细说明:

  • We’ve used two different Portlet Tags, <renderURL/> and <defineObjects/>.

    我们使用了两个不同的Portlet标记<renderURL/><defineObjects/>
  • We never be able of accessing the implicit object renderRequest, if we don’t use the <defineObjects/> Portlet Tag.

    如果不使用<defineObjects/> Portlet标记,我们将永远无法访问隐式对象renderRequest。
  • Implicit objects like request, response that are received by the JSP and Servlet can be used but with a limitation as many of their methods either perform no operation or return null when used inside a Portlet container.

    可以使用JSP和Servlet接收的隐式对象(例如requestresponse ,但是有一个局限性,因为它们的许多方法在Portlet容器中使用时都不执行任何操作或返回null。

员工注册门户 (Employee Registration Portlet)

As we’ve defined the Views that are needed for covering the all scenarios that you may face while employee registration. It’s time to define the controller, following below RegisterEmployeePortlet that would help you dispatching into required views.

正如我们定义的视图一样,它涵盖了员工注册时可能遇到的所有情况。 现在是时候定义控制器了,下面RegisterEmployeePortlet可以帮助您分派到所需的视图中。

package com.journaldev.portlet;

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
			PortletRequestDispatcher 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
			PortletRequestDispatcher 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
			PortletRequestDispatcher 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
			PortletRequestDispatcher 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
		PortletRequestDispatcher 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 listed above:

这是上面列出的代码的详细说明:

  • RegisterEmployeePortlet overrode two methods from its GenericPortlet parent class.

    RegisterEmployeePortlet覆盖了其GenericPortlet父类中的两个方法。
  • The doView() method will determine which view it should be delegate for based on the status parameter.

    doView()方法将根据status参数确定应委派哪个视图。
  • The processAction() will handle the registration action as it should delegate the action into RegisterEmployeeServlet.

    processAction()将处理注册动作,因为它将动作委托给RegisterEmployeeServlet
  • In case the RegisterEmployeeServlet has completed its work sucessfully, a status successparameter will be set as a render parameter for getting accessed by the render phase after then.

    如果RegisterEmployeeServlet成功完成工作,则将状态success参数设置为呈现参数,然后在此之后由呈现阶段进行访问。
  • In case the RegisterEmployeeServlet has initiated an exception the catch block will handle it and put a status failed as a render parameter for getting accessed by the render phase after then.

    如果RegisterEmployeeServlet启动了异常,则catch块将处理该异常并将状态failed作为渲染参数,以供之后的渲染阶段访问。
  • JSPs are located using the getRequestDispatcher() while Servlet is located using the getNamedDispatcher(). We’ve passed the name of the Servlet that’s registered in the deployment descriptor as a parameter.

    使用getRequestDispatcher() getNamedDispatcher() JSP,而使用getNamedDispatcher() Servlet。 我们已将在部署描述符中注册的Servlet的名称作为参数传递。

员工注册Servlet (Employee Registration Servlet)

RegisterEmployeeServlet is used to complete the registration process.

RegisterEmployeeServlet用于完成注册过程。

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

}

Here’s detailed explanation for the code listed above:

这是上面列出的代码的详细说明:

  • As the form that was initiated the action has used a POST method, the Servlet should provide an implementation for it.

    由于动作的发起形式已经使用POST方法,因此Servlet应该为其提供实现。
  • The employee object has been created by extracting its properties from the request object.

    雇员对象是通过从请求对象中提取其属性来创建的。
  • It’s Using an EmployeeDAO for creating the employee.

    它使用EmployeeDAO创建员工。
  • It’s Handling the exception in case you’ve got one, and throw a new one for Portlet informing purpose.

    如果您有一个异常,它会处理异常,并为Portlet通知目的而抛出一个新异常。

员工DAO和ConnectionUtility (EmployeeDAO & ConnectionUtility)

We’ve implemented two different singleton classes for handling the employee’s database operations and acquiring the needed connections respectively.

我们实现了两种不同的单例类,分别用于处理员工的数据库操作和获取所需的连接。

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

}

It’s important to know that the username and password of the database are read from connection.properties file that’s defined in the resources.

重要的是要知道数据库的用户名和密码是从资源中定义的connection.properties文件中读取的。

部署描述符 (Deployment Descriptor)

<!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "https://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Employee Registration</display-name>
  <servlet>
  	<servlet-class>com.journaldev.servlet.RegisterEmployeeServlet</servlet-class>
  	<servlet-name>RegisterEmployeeServlet</servlet-name>
  </servlet>
  <servlet-mapping>
  	<servlet-name>RegisterEmployeeServlet</servlet-name>
  	<url-pattern>/registerEmployeeServlet</url-pattern>
  </servlet-mapping>
  <taglib>
  	<taglib-uri>https://java.sun.com/portlet</taglib-uri>
  	<taglib-location>/WEB-INF/portlet.tld</taglib-location>
  </taglib>
</web-app>

Maven构建文件 (Maven Build File)

<project xmlns="https://maven.apache.org/POM/4.0.0" xmlns:xsi="https://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="https://maven.apache.org/POM/4.0.0 https://maven.apache.org/maven-v4_0_0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>com.journaldev</groupId>
	<artifactId>EmployeeRegistrationApp</artifactId>
	<packaging>war</packaging>
	<version>0.0.1-SNAPSHOT</version>
	<name>EmployeeRegistrationApp</name>
	<url>https://maven.apache.org</url>
	<properties>
		<deployFolder>D:/Apache Pluto/pluto-2.0.3/webapps</deployFolder>
	</properties>
	<dependencies>
		<!-- Java Portlet Specification V2.0 -->
		<dependency>
			<groupId>org.apache.portals</groupId>
			<artifactId>portlet-api_2.0_spec</artifactId>
			<version>1.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.4</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>jsp-api</artifactId>
			<version>2.0</version>
			<scope>provided</scope>
		</dependency>
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.3</version>
		</dependency>
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>1.2.17</version>
		</dependency>
		<dependency>
			<groupId>org.apache.pluto</groupId>
			<artifactId>pluto-taglib</artifactId>
			<version>1.1.7</version>
		</dependency>
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.32</version>
		</dependency>

	</dependencies>
	<build>
		<finalName>${project.artifactId}</finalName>
		<plugins>
			<!-- bind 'pluto2:assemble' goal to 'process-resources' lifecycle -->
			<!-- This plugin will read your portlet.xml and web.xml and injects required
				lines -->
			<plugin>
				<groupId>org.apache.portals.pluto</groupId>
				<artifactId>maven-pluto-plugin</artifactId>
				<version>2.1.0-M3</version>
				<executions>
					<execution>
						<phase>generate-resources</phase>
						<goals>
							<goal>assemble</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<!-- configure maven-war-plugin to use updated web.xml -->
			<!-- This plugin will make sure your WAR will contain the updated web.xml -->
			<plugin>
				<artifactId>maven-war-plugin</artifactId>
				<version>2.1.1</version>
				<configuration>
					<webXml>${project.build.directory}/pluto-resources/web.xml</webXml>
				</configuration>
			</plugin>
			<plugin>
				<artifactId>maven-antrun-plugin</artifactId>
				<executions>
					<execution>
						<id>copy</id>
						<phase>integration-test</phase>
						<configuration>
							<tasks>
								<copy file="target/${project.artifactId}.war" tofile="${deployFolder}/${project.artifactId}.war" />
							</tasks>
						</configuration>
						<goals>
							<goal>run</goal>
						</goals>
					</execution>
					<execution>
						<id>delete</id>
						<phase>clean</phase>
						<configuration>
							<tasks>
								<delete file="${deployFolder}/${project.artifactId}.war" />
								<delete dir="${deployFolder}/${project.artifactId}" />
							</tasks>
							<detail>true</detail>
						</configuration>
						<goals>
							<goal>run</goal>
						</goals>
					</execution>
				</executions>
			</plugin>
			<plugin>
				<groupId>org.apache.maven.plugins</groupId>
				<artifactId>maven-compiler-plugin</artifactId>
				<version>3.1</version>
				<configuration>
					<source>1.7</source>
					<target>1.7</target>
				</configuration>
			</plugin>
		</plugins>
	</build>
</project>

员工注册演示 (Employee Registration Demo)

It’s now time of executing the application that’s just developed. At the beginning, make sure that you’re deploying the application into your Pluto Portal and you get access to JournalDev page.

现在该执行刚刚开发的应用程序了。 开始时,请确保将应用程序部署到Pluto Portal中,并且可以访问JournalDev页面。

Once, you’ve got this page, be sure that the doView() method has been executed and it checks for status variable that’s already null. As a result, the doView() method has dispatched the request into registerEmployee.jsp. Just fill in all the employee’s information.

一旦获得了该页面,请确保已执行doView()方法并检查状态变量是否为null。 结果,doView()方法已将请求分派到registerEmployee.jsp中。 只需填写所有员工信息。

By clicking on Register, your RegisterEmployeePortlet’s processAction() is executed and the RegisterEmployeeServlet will handle the whole registration process. As a result, the employee must be registered and the user must be confirmed about that.

通过单击Register,将执行RegisterEmployeePortlet的processAction(),并且RegisterEmployeeServlet将处理整个注册过程。 结果,必须对员工进行注册,并必须确认用户。

Employee Is Registered
Now, you have the opportunity to get back into registration form by clicking on the Register Another link. This link is associated with the <renderURL/> as it’s passed a status value. What’s happened if you try to register the same employee with the same identifier. You’re mostly got an exception relevant for the database.

员工注册
现在,您有机会通过单击“注册另一个”链接重新进入注册表单。 该链接与<renderURL />关联,因为它已传递了状态值。 如果您尝试使用相同的标识符注册同一名员工,将会发生什么情况。 您通常会遇到与数据库相关的异常。

摘要 (Summary)

Using of Portlets with respect to JSP and Servlet is consider so attractive things as it contains a lot of details you must be aware of. We’re already handled that on behalf of you as you can download the source code to know how’s everything going on. Contribute us by commenting below and let us know if you have any concern or questions want to be answered.

就JSP和Servlet而言,使用Portlet是一件非常吸引人的事情,因为它包含许多您必须了解的细节。 我们已经代表您处理过此事,您可以下载源代码以了解所有情况。 请在下方评论,为我们提供帮助,如果您有任何疑问或想回答的问题,请告诉我们。

翻译自: https://www.journaldev.com/4957/portlet-jsp-servlet

portlet

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值