Mkyong-中文博客翻译-十-

Mkyong 中文博客翻译(十)

原文:Mkyong

协议:CC BY-NC-SA 4.0

Struts 2 + Spring + Hibernate 集成示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-spring-hibernate-integration-example/

Download it – Struts2-Spring-Hibernate-Integration-Example.zip

在本教程中,展示了“ Struts2 + Spring + Hibernate 之间的集成。在继续之前,请务必检查以下教程。

  1. Struts 2 + Hibernate 集成示例
  2. Struts 2 + Spring 集成示例
  3. Struts 1.x + Spring + Hibernate 集成示例

查看集成步骤摘要:

  1. 获取所有的依赖库(很多)。
  2. 注册弹簧的 ContextLoaderListener 以整合支柱 2 和弹簧。
  3. 使用 Spring 的 LocalSessionFactoryBean 来集成 Spring 和 Hibernate。
  4. 完成,全部连接。

查看关系:

 Struts 2 <-- (ContextLoaderListener) --> Spring <-- (LocalSessionFactoryBean) --> Hibernate 

This will be a very long tutorial with little explanation, make sure you check the above 3 articles for details explanation.

教程开始…

它将创建一个客户页面,添加客户和列出客户功能。前端使用 Struts 2 进行显示, Spring 作为依赖注入引擎, Hibernate 进行数据库操作。让我们开始…

1.项目结构

项目文件夹结构。

Struts2 Spring Hibernate Project StructureStruts2 Spring Hibernate Project Structure ## 2.MySQL 表脚本

客户的表脚本。

 DROP TABLE IF EXISTS `mkyong`.`customer`;
CREATE TABLE  `mkyong`.`customer` (
  `CUSTOMER_ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `ADDRESS` varchar(255) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8; 

3.依赖库

本教程需要许多依赖库。

支柱 2…

 <!-- Struts 2 -->
        <dependency>
	    <groupId>org.apache.struts</groupId>
	    <artifactId>struts2-core</artifactId>
	    <version>2.1.8</version>
        </dependency>
	<!-- Struts 2 + Spring plugins -->
	<dependency>
            <groupId>org.apache.struts</groupId>
	    <artifactId>struts2-spring-plugin</artifactId>
	    <version>2.1.8</version>
        </dependency> 

MySQL…

 <!-- MySQL database driver -->
	<dependency>
		<groupId>mysql</groupId>
		<artifactId>mysql-connector-java</artifactId>
		<version>5.1.9</version>
	</dependency> 

春天……

 <!-- Spring framework --> 
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring</artifactId>
		<version>2.5.6</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>2.5.6</version>
	</dependency> 

冬眠…

 <!-- Hibernate core -->
	<dependency>
		<groupId>org.hibernate</groupId>
		<artifactId>hibernate</artifactId>
		<version>3.2.7.ga</version>
	</dependency>

	<!-- Hibernate core library dependency start -->
	<dependency>
		<groupId>dom4j</groupId>
		<artifactId>dom4j</artifactId>
		<version>1.6.1</version>
	</dependency>

	<dependency>
		<groupId>commons-logging</groupId>
		<artifactId>commons-logging</artifactId>
		<version>1.1.1</version>
	</dependency>

	<dependency>
		<groupId>commons-collections</groupId>
		<artifactId>commons-collections</artifactId>
		<version>3.2.1</version>
	</dependency>

	<dependency>
		<groupId>cglib</groupId>
		<artifactId>cglib</artifactId>
		<version>2.2</version>
	</dependency>
	<!-- Hibernate core library dependency end -->

	<!-- Hibernate query library dependency start -->
	<dependency>
		<groupId>antlr</groupId>
		<artifactId>antlr</artifactId>
		<version>2.7.7</version>
	</dependency>
	<!-- Hibernate query library dependency end --> 

4.冬眠…

只需要模型和映射文件,因为 Spring 将处理 Hibernate 配置。

Customer.java–为客户表创建一个类。

 package com.mkyong.customer.model;

import java.util.Date;

public class Customer implements java.io.Serializable {

	private Long customerId;
	private String name;
	private String address;
	private Date createdDate;

	//getter and setter methods
} 

customer . hbm . XML–客户的 Hibernate 映射文件。

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC "-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<!-- Generated 20 Julai 2010 11:40:18 AM by Hibernate Tools 3.2.5.Beta -->
<hibernate-mapping>
    <class name="com.mkyong.customer.model.Customer" 
		table="customer" catalog="mkyong">
        <id name="customerId" type="java.lang.Long">
            <column name="CUSTOMER_ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="NAME" length="45" not-null="true" />
        </property>
        <property name="address" type="string">
            <column name="ADDRESS" not-null="true" />
        </property>
        <property name="createdDate" type="timestamp">
            <column name="CREATED_DATE" length="19" not-null="true" />
        </property>
    </class>
</hibernate-mapping> 

5.Struts 2…

实现 Bo 和 DAO 设计模式。Spring 将在 Spring bean 配置文件中 DI 所有的 Bo 和 DAO。在 DAO 中,make 它扩展 Spring 的 HibernateDaoSupport 来集成 Spring 和 Hibernate 的集成。

CustomerBo.java

 package com.mkyong.customer.bo;

import java.util.List;
import com.mkyong.customer.model.Customer;

public interface CustomerBo{

	void addCustomer(Customer customer);
	List<Customer> listCustomer();

} 

CustomerBoImpl.java

 package com.mkyong.customer.bo.impl;

import java.util.List;
import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.model.Customer;

public class CustomerBoImpl implements CustomerBo{

	CustomerDAO customerDAO;
	//DI via Spring
	public void setCustomerDAO(CustomerDAO customerDAO) {
		this.customerDAO = customerDAO;
	}

	//call DAO to save customer
	public void addCustomer(Customer customer){
		customerDAO.addCustomer(customer);
	}

	//call DAO to return customers
	public List<Customer> listCustomer(){
		return customerDAO.listCustomer();
	}
} 

CustomerDAO.java

 package com.mkyong.customer.dao;

import java.util.List;
import com.mkyong.customer.model.Customer;

public interface CustomerDAO{

	void addCustomer(Customer customer);
	List<Customer> listCustomer();	

} 

CustomerDAOImpl.java

 package com.mkyong.customer.dao.impl;

import java.util.List;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;
import com.mkyong.customer.dao.CustomerDAO;
import com.mkyong.customer.model.Customer;

public class CustomerDAOImpl extends HibernateDaoSupport 
    implements CustomerDAO{

	//add the customer
	public void addCustomer(Customer customer){
		getHibernateTemplate().save(customer);
	}

	//return all the customers in list
	public List<Customer> listCustomer(){
		return getHibernateTemplate().find("from Customer");		
	}

} 

CustomerAction.java–支柱 2 动作不再需要伸出动作支架,弹簧会处理它。

 package com.mkyong.customer.action;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.model.Customer;
import com.opensymphony.xwork2.ModelDriven;

public class CustomerAction implements ModelDriven{

	Customer customer = new Customer();
	List<Customer> customerList = new ArrayList<Customer>();

	CustomerBo customerBo;
	//DI via Spring
	public void setCustomerBo(CustomerBo customerBo) {
		this.customerBo = customerBo;
	}

	public Object getModel() {
		return customer;
	}

	public List<Customer> getCustomerList() {
		return customerList;
	}

	public void setCustomerList(List<Customer> customerList) {
		this.customerList = customerList;
	}

	//save customer
	public String addCustomer() throws Exception{

		//save it
		customer.setCreatedDate(new Date());
		customerBo.addCustomer(customer);

		//reload the customer list
		customerList = null;
		customerList = customerBo.listCustomer();

		return "success";

	}

	//list all customers
	public String listCustomer() throws Exception{

		customerList = customerBo.listCustomer();

		return "success";

	}

} 

6.春天…

几乎所有的配置都是在这里完成的,毕竟 Spring 是专门做集成工作的:)。

customer bean . XML–声明春天的豆子:Action、BO、DAO。

 <?xml version="1.0" encoding="UTF-8"?>
<beans 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 	<bean id="customerAction" class="com.mkyong.customer.action.CustomerAction">
		<property name="customerBo" ref="customerBo" />	
	</bean>

	<bean id="customerBo" class="com.mkyong.customer.bo.impl.CustomerBoImpl" >
		<property name="customerDAO" ref="customerDAO" />
	</bean>

   	<bean id="customerDAO" class="com.mkyong.customer.dao.impl.CustomerDAOImpl" >
		<property name="sessionFactory" ref="sessionFactory" />
	</bean>

</beans> 

database . properties–声明数据库细节。

 jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyong
jdbc.username=root
jdbc.password=password 

data source . XML–创建一个数据源 bean。

 <beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean 
   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location">
     <value>WEB-INF/classes/config/database/properties/database.properties</value>
   </property>
</bean>

  <bean id="dataSource" 
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
  </bean>

</beans> 

hibernatesessionfactory . XML–创建一个 sessionFactory bean 来集成 Spring 和 Hibernate。

 <?xml version="1.0" encoding="UTF-8"?>
<beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!-- Hibernate session factory -->
<bean id="sessionFactory" 
    class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>

    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
    </property>

    <property name="mappingResources">
		<list>
          <value>com/mkyong/customer/hibernate/Customer.hbm.xml</value>
		</list>
    </property>	

</bean>
</beans> 

Spring beans . XML–创建一个核心 Spring 的 bean 配置文件,作为中心 bean 管理。

 <beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<!-- Database Configuration -->
	<import resource="config/spring/DataSource.xml"/>
	<import resource="config/spring/HibernateSessionFactory.xml"/>

	<!-- Beans Declaration -->
	<import resource="com/mkyong/customer/spring/CustomerBean.xml"/>

</beans> 

7.JSP 页面

显示带有 Struts 2 标记的元素的 JSP 页面。

customer.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>

<body>
<h1>Struts 2 + Spring + Hibernate integration example</h1>

<h2>Add Customer</h2>
<s:form action="addCustomerAction" >
  <s:textfield name="name" label="Name" value="" />
  <s:textarea name="address" label="Address" value="" cols="50" rows="5" />
  <s:submit />
</s:form>

<h2>All Customers</h2>

<s:if test="customerList.size() > 0">
<table border="1px" cellpadding="8px">
	<tr>
		<th>Customer Id</th>
		<th>Name</th>
		<th>Address</th>
		<th>Created Date</th>
	</tr>
	<s:iterator value="customerList" status="userStatus">
		<tr>
			<td><s:property value="customerId" /></td>
			<td><s:property value="name" /></td>
			<td><s:property value="address" /></td>
			<td><s:date name="createdDate" format="dd/MM/yyyy" /></td>
		</tr>
	</s:iterator>
</table>
</s:if>
<br/>
<br/>

</body>
</html> 

8.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>
 	<constant name="struts.devMode" value="true" />

	<package name="default" namespace="/" extends="struts-default">

		<action name="addCustomerAction" 
			class="customerAction" method="addCustomer" >
		    <result name="success">pages/customer.jsp</result>
		</action>

		<action name="listCustomerAction"
			class="customerAction" method="listCustomer" >
		    <result name="success">pages/customer.jsp</result>
		</action>

	</package>

</struts> 

9.支柱 2 +弹簧

要集成 Struts 2 和 Spring,只需注册 ContextLoaderListener 监听器类,定义一个“ contextConfigLocation 参数,让 Spring container 解析“ SpringBeans.xml ”而不是默认的“ applicationContext.xml ”。

web.xml

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

<web-app>
  <display-name>Struts 2 Web Application</display-name>

  <filter>
	<filter-name>struts2</filter-name>
	<filter-class>
	  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
	</filter-class>
  </filter>

  <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>

  <context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>/WEB-INF/classes/SpringBeans.xml</param-value>
  </context-param>

  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

</web-app> 

10.演示

测试一下:http://localhost:8080/struts 2 example/listcustomeraction . action

Struts2 Spring Hibernate ExampleStruts2 Spring Hibernate Example

参考

  1. Struts 2 + Hibernate 集成示例
  2. Struts 2 + Spring 集成示例
  3. 带有完整 Hibernate 插件的 Struts 2 + Hibernate 示例
  4. Struts 1.x + Spring + Hibernate 集成示例

hibernate integration spring struts2

Struts 2 + Spring 集成示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-spring-integration-example/

Download it – Struts2-Spring-Integration-Example.zip

在本教程中,它展示了 Struts 2 和 Spring 之间的集成。

1.项目结构

这是本教程的项目文件夹结构。

Struts 2 Spring integration example

2.Struts 2 + Spring 插件

要集成 Struts 2 和 Spring,获取并在项目类路径中包含"Struts 2-Spring-plugin-XXX . jar"库。

pom.xml

 <!-- Struts 2 -->
        <dependency>
                <groupId>org.apache.struts</groupId>
	        <artifactId>struts2-core</artifactId>
	        <version>2.1.8</version>
        </dependency>

	<!-- Spring framework --> 
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring</artifactId>
		<version>2.5.6</version>
	</dependency>

	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>2.5.6</version>
	</dependency>

	<!-- Struts 2 + Spring plugins -->
	<dependency>
                 <groupId>org.apache.struts</groupId>
	         <artifactId>struts2-spring-plugin</artifactId>
	         <version>2.1.8</version>
         </dependency> 

3.春天的听众

web.xml 文件中配置 Spring 监听器"org . Spring framework . web . context . context loader listener"。

web.xml

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

<web-app>
  <display-name>Struts 2 Web Application</display-name>

  <filter>
	<filter-name>struts2</filter-name>
	<filter-class>
         org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
        </filter-class>
  </filter>

  <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>
      org.springframework.web.context.ContextLoaderListener
    </listener-class>
  </listener>

</web-app> 

3.注册春豆

applicationContext.xml 文件中注册所有 Spring 的 Beans,Spring 监听器将自动定位这个 xml 文件。

applicationContext.xml

 <beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<bean id="userBo" class="com.mkyong.user.bo.impl.UserBoImpl" />

	<bean id="userSpringAction" class="com.mkyong.user.action.UserSpringAction">
		<property name="userBo" ref="userBo" />	
	</bean>

</beans> 

UserBo.java

 package com.mkyong.user.bo;

public interface UserBo{

	public void printUser();

} 

UserBoImpl.java

 package com.mkyong.user.bo.impl;

import com.mkyong.user.bo.UserBo;

public class UserBoImpl implements UserBo{

	public void printUser(){
		System.out.println("printUser() is executed...");
	}

} 

user springaction . Java

 package com.mkyong.user.action;

import com.mkyong.user.bo.UserBo;

public class UserSpringAction{

	//DI via Spring
	UserBo userBo;

	public UserBo getUserBo() {
		return userBo;
	}

	public void setUserBo(UserBo userBo) {
		this.userBo = userBo;
	}

	public String execute() throws Exception {

		userBo.printUser();
		return "success";

	}
} 

5.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>
 	<constant name="struts.devMode" value="true" />

	<package name="default" namespace="/" extends="struts-default">

		<action name="userAction" 
			class="com.mkyong.user.action.UserAction" >
			<result name="success">pages/user.jsp</result>
		</action>

		<action name="userSpringAction" 
			class="userSpringAction" >
			<result name="success">pages/user.jsp</result>
		</action>

	</package>

</struts> 

6.演示

现在,所有 Struts 2 和 Spring 的集成工作都完成了,现在看下面的用例来访问 Spring 的"userBobean。

  • 案例 1:让 Spring 充当 Struts 2 操作类,并访问 Spring 的 bean。
  • 案例 2:在 Struts 2 操作类中访问 Spring 的 bean。

案例 1

在这个例子中,userpspringaction作为 Struts 2 的 Action 类,你可以用普通的 Spring 方式来定义 Spring 的 userBo bean。

 //struts.xml
<action name="userSpringAction" 
	class="userSpringAction" >
	<result name="success">pages/user.jsp</result>
</action>

//applicationContext.xml
<bean id="userSpringAction" class="com.mkyong.user.action.UserSpringAction">
	<property name="userBo" ref="userBo" />	
</bean> 

要访问此操作,请使用以下 URL:http://localhost:8080/struts 2 example/userpspringaction

案例 2

默认情况下,Spring listener 通过匹配 bean 名称来启用自动连接。因此,它会通过 setUserBo() 自动将 Spring 的“userBo”bean 传递给 UserAction。见下面 Struts 2 的动作:

The Spring’s autowiring feature can change to name(default), type, auto or constructor, you may need to consult this Struts 2 Spring plugin documentation.

user action . Java

 package com.mkyong.user.action;

import com.mkyong.user.bo.UserBo;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport{

	//DI via Spring
	UserBo userBo;

	public UserBo getUserBo() {
		return userBo;
	}

	public void setUserBo(UserBo userBo) {
		this.userBo = userBo;
	}

	public String execute() throws Exception {

		userBo.printUser();
		return SUCCESS;

	}
} 

要访问此操作,请使用 URL:http://localhost:8080/struts 2 example/user action

WebApplicationContextUtils
Alternatively, you can use the Spring’s generic WebApplicationContextUtils class to get the Spring’s bean directly.

 package com.mkyong.user.action;

import org.apache.struts2.ServletActionContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.mkyong.user.bo.UserBo;
import com.opensymphony.xwork2.ActionSupport;

public class UserAction extends ActionSupport{

	public String execute() throws Exception {

		WebApplicationContext context =
			WebApplicationContextUtils.getRequiredWebApplicationContext(
                                    ServletActionContext.getServletContext()
                        );

		UserBo userBo1 = (UserBo)context.getBean("userBo");
		userBo1.printUser();

		return SUCCESS;

	}
} 

一篇非常冗长乏味的文章,请确保下载完整的项目源代码进行练习。

参考

  1. Struts 2 Spring 插件文档
  2. Struts + Spring 集成示例

integration spring struts2

Struts 2 + Spring 2.5.6 + Quartz 1.6 调度器集成示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-spring-quartz-scheduler-integration-example/

Struts 2 + Spring 2.5.6 + Quartz 调度器集成示例

在本教程中,我们将向您展示如何将Struts 2+Spring 2 . 5 . 6+Quartz 1 . 6 . 5调度器集成在一起。这种关系看起来像这样:

 Struts 2 <-- Plugin --> Spring <--(Helper)--> Quartz <---> Scheduler task 

使用的工具

  1. 弹簧 2.5.6
  2. 石英
  3. Struts 2.1.8
  4. 支柱 2-弹簧-插件 2.1.8
  5. Maven 2
  6. Eclipse 3.6

Note
You may also interest at this – Struts 2 + Spring 3 + Quartz 1.8.6 integration example..

1.项目文件夹

这是项目文件夹结构。

Struts 2 Spring Quartz integration example ## 2.依赖库

获取所有的依赖库,你需要 Spring,Struts2,struts 2-Spring-Plugin 和 Quartz jar 文件。

文件:pom.xml

 ...
  <dependencies>

	<!-- Struts 2 -->
	<dependency>
          <groupId>org.apache.struts</groupId>
	  <artifactId>struts2-core</artifactId>
	  <version>2.1.8</version>
        </dependency>

	<!-- Quartz framework -->
	<dependency>
          <groupId>opensymphony</groupId>
	  <artifactId>quartz</artifactId>
	  <version>1.6.3</version>
	</dependency>

	<!-- Quartz dependency library-->
	<dependency>
	  <groupId>commons-collections</groupId>
	  <artifactId>commons-collections</artifactId>
	  <version>3.2.1</version>
	</dependency>

	<!-- Spring framework --> 
	<dependency>
	  <groupId>org.springframework</groupId>
	  <artifactId>spring</artifactId>
	  <version>2.5.6</version>
	</dependency>

	<dependency>
	  <groupId>org.springframework</groupId>
	  <artifactId>spring-web</artifactId>
	  <version>2.5.6</version>
	</dependency>

	<!-- Struts 2 + Spring plugins -->
	<dependency>
          <groupId>org.apache.struts</groupId>
	  <artifactId>struts2-spring-plugin</artifactId>
	  <version>2.1.8</version>
        </dependency>

  </dependencies>
  ... 

3.调度程序任务

将所有调度程序逻辑放在这个类中。

文件:SchedulerTask.java

 package com.mkyong.quartz;

public class SchedulerTask {

   public void printSchedulerMessage() {

	   System.out.println("Struts 2 + Spring + Quartz ......");

   }
} 

4.弹簧+石英

要集成 Spring 和 Quartz,创建一个扩展org.springframework.scheduling.quartz.QuartzJobBean的类,通过 setter 方法引用调度器任务(【SchedulerTask.java】)并将调度器逻辑放在executeInternal()方法中。

文件:SchedulerJob.java

 package com.mkyong.quartz;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class SchedulerJob extends QuartzJobBean
{
	private SchedulerTask schedulerTask;

	public void setSchedulerTask(SchedulerTask schedulerTask) {
		this.schedulerTask = schedulerTask;
	}

	protected void executeInternal(JobExecutionContext context)
	throws JobExecutionException {

		schedulerTask.printSchedulerMessage();

	}
} 

文件:application context . XML——创建一个applicationContext.xml文件,把所有 Spring + Quartz 集成的东西放在里面。有关详细信息,请阅读 XML 注释。

 <beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

   <!-- Scheduler task -->
   <bean name="schedulerTask" class="com.mkyong.quartz.SchedulerTask" />

   <!-- Scheduler job -->
   <bean name="schedulerJob" 
     class="org.springframework.scheduling.quartz.JobDetailBean">

     <property name="jobClass" value="com.mkyong.quartz.SchedulerJob" />

     <property name="jobDataAsMap">
	 <map>
	    <entry key="schedulerTask" value-ref="schedulerTask" />
	 </map>
      </property>
   </bean>

   <!-- Cron Trigger, run every 10 seconds -->
   <bean id="cronTrigger"
	class="org.springframework.scheduling.quartz.CronTriggerBean">

	<property name="jobDetail" ref="schedulerJob" />
	<property name="cronExpression" value="0/10 * * * * ?" />

   </bean>

   <!-- Scheduler -->
   <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
	<property name="jobDetails">
	   <list>
	      <ref bean="schedulerJob" />
	   </list>
	</property>

	<property name="triggers">
	    <list>
		<ref bean="cronTrigger" />
	    </list>
	</property>
   </bean>

</beans> 

5.支柱 2 +弹簧

要集成 Struts 2 + Spring ,只需将org.springframework.web.context.ContextLoaderListener监听器类放在web.xml文件中。

文件:web.xml

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

<web-app>
  <display-name>Struts 2 Web Application</display-name>

  <filter>
	<filter-name>struts2</filter-name>
	<filter-class>
	  org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter
	</filter-class>
  </filter>

  <filter-mapping>
	<filter-name>struts2</filter-name>
	<url-pattern>/*</url-pattern>
  </filter-mapping>

  <listener>
    <listener-class>
	  org.springframework.web.context.ContextLoaderListener
	</listener-class>
  </listener>

</web-app> 

6.演示

启动 Strut2 时,它调用 Spring 并运行定义的 Quartz 的作业——每 10 秒调用SchedulerTask.printSchedulerMessage()

 INFO: ... initialized Struts-Spring integration successfully
16 Julai 2010 12:51:38 PM org.apache.coyote.http11.Http11Protocol start
INFO: Starting Coyote HTTP/1.1 on http-8080
16 Julai 2010 12:51:38 PM org.apache.jk.common.ChannelSocket init
INFO: JK: ajp13 listening on /0.0.0.0:8009
16 Julai 2010 12:51:38 PM org.apache.jk.server.JkMain start
INFO: Jk running ID=0 time=0/21  config=null
16 Julai 2010 12:51:38 PM org.apache.catalina.startup.Catalina start
INFO: Server startup in 2110 ms
Struts 2 + Spring + Quartz ......
Struts 2 + Spring + Quartz ......
Struts 2 + Spring + Quartz ......
Struts 2 + Spring + Quartz ......
Struts 2 + Spring + Quartz ...... 

下载源代码

Download it – Struts2-Spring-Quartz-Integration-Example.zip

参考

  1. Struts 2 + Spring 集成示例
  2. Struts 2 Spring 插件文档
  3. Struts + Spring 集成示例
  4. Struts + Quartz 集成示例
  5. 支柱+弹簧+石英集成示例

integration quartz scheduler spring struts2

Struts 2 单选按钮示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-sradio-radio-button-example/

Download It – Struts2-Radio-Button-Example.zip

在 Struts 2 中,可以使用 < s:radio > 标签创建一个 HTML 单选按钮。有趣的是,有很多方法可以将数据填充到单选按钮中,通过列表、OGNL 或对象。看看下面的例子就知道怎么做了。

Struts 2 示例

这个例子展示了如何使用列表、OGNL 和对象向通过 Struts 2 标签创建的单选按钮填充数据。

1.行动

为单选按钮创建性别和语言值列表的操作类。

RadioButtonAction.java

 package com.mkyong.common.action;

import java.util.ArrayList;
import java.util.List;

import com.mkyong.common.model.Language;
import com.opensymphony.xwork2.ActionSupport;

public class RadioButtonAction extends ActionSupport{

	private List<String> genders;
	private List<Language> languages ;

	private String yourGender;
	private String yourAnswer;
	private String yourLanguage;

	private static final String MALE = "male";
	private static final String FEMALE = "female";
	private static final String UNKNOWN = "unknown";

	public RadioButtonAction(){

		genders = new ArrayList<String>();
		genders.add(MALE);
		genders.add(FEMALE);
		genders.add(UNKNOWN);

		languages = new ArrayList<Language>();
		languages.add( new Language("EN", "English") );
		languages.add( new Language("FR", "France") );
		languages.add( new Language("CN_ZH", "Chinese") );
		languages.add( new Language("DE", "German") );

	}

	//return default gender value
	public String getDefaultGenderValue(){
		return UNKNOWN;
	}

	//return default language value
	public String getDefaultLanguageValue(){
		return "CN_ZH";
	}

	public String execute() {
		return SUCCESS;
	}
	public String display() {
		return NONE;
	}

	//getter ad setter methods
} 

Language.java

 package com.mkyong.common.model;

public class Language{

	private String languageCode;
	private String languageDisplay;

	//getter and setter methods

	public Language(String languageCode, String languageDisplay) {
		this.languageCode = languageCode;
		this.languageDisplay = languageDisplay;
	}
} 

2.结果页面

使用 Struts 2 " s:radio "通过列表、OGNL 和对象创建三个单选按钮的结果页。

radiobutton.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>

<body>
<h1>Struts 2 radio button example</h1>

<s:form action="resultAction" namespace="/">

<h2>
  <s:radio label="Gender" name="yourGender" list="genders" value="defaultGenderValue" />
  <s:radio label="Gender" name="yourLanguage" list="languages" 
      listKey="languageCode" listValue="languageDisplay" value="defaultLanguageValue" />
  <s:radio label="Answer" name="yourAnswer" list="#{'1':'Yes','2':'No'}" value="2" />
</h2> 

<s:submit value="submit" name="submit" />

</s:form>

</body>
</html>a 

result.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>

<body>
<h1>Struts 2 radio button example</h1>

<h2>
  Your Selected Gender : <s:property value="yourGender"/>
</h2> 
<h2>
  Your Selected Language : <s:property value="yourLanguage"/>
</h2> 
<h2>
  Your Selected Answer : <s:property value="yourAnswer"/>
</h2> 

</body>
</html> 

3.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>

<constant name="struts.devMode" value="true" />

  <package name="" namespace="/" extends="struts-default">

    <action name="radioButtonAction" 
         class="com.mkyong.common.action.RadioButtonAction" method="display">
		<result name="none">pages/radiobutton.jsp</result>
    </action>

    <action name="resultAction" class="com.mkyong.common.action.RadioButtonAction">
		<result name="success">pages/result.jsp</result>
    </action>
  </package>

</struts> 

5.演示

http://localhost:8080/struts 2 example/radio button action . action

Struts2 radio button screen

http://localhost:8080/struts 2 example/result action . action

Struts2 radio button screenTo understand how to preselect a value, read this article – preselect a radio button value in Struts 2

参考

  1. http://struts.apache.org/2.0.11.2/docs/radio.html
  2. http://struts . Apache . org/2 . 1 . 8 . 1/docs/struts-2-form-tags . html
  3. 如何在 Struts 2 中预选单选按钮值

radio button struts2

Struts 2

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-sselect-drop-down-box-example/

Download It – Struts2-Select-DropDown-Box-Example.zip

在 Struts 2 中,可以使用 < s:select > 标签创建一个 HTML 下拉框。

 <s:select label="What's your favor search engine" 
		headerKey="-1" headerValue="Select Search Engines"
		list="searchEngine" 
		name="yourSearchEngine" /> 

产生以下 HTML 代码…

 <td class="tdLabel">
   <label for="resultAction_yourSearchEngine" class="label">
       What's your favor search engine:
   </label>
</td> 
<td>
<select name="yourSearchEngine" id="resultAction_yourSearchEngine"> 
    <option value="-1">Select Search Engines</option> 
    <option value="google.com">google.com</option> 
    <option value="bing.com">bing.com</option> 
    <option value="yahoo.com">yahoo.com</option> 
    <option value="baidu.com">baidu.com</option> 
</select> 
</td> 

语法是不言自明的,但是“ headerKey 和“ headerValue ”。“ headerKey 是下拉列表中第一项的键,“ headerValue 是下拉列表中第一项的值表达式。

To auto select a default value for drop down box, read this artcle : Auto select drop down box value in Struts 2

Struts 2 < s:select > 示例

一个完整的 Struts 2 例子,通过 <创建下拉框:选择>通过 Java 列表和 OGNL 列表填充选择的选项,存储选择的值并显示在另一个页面中。

1.行动

操作类来生成和保存所选的下拉框选项。
SelectAction.java

 package com.mkyong.common.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class SelectAction extends ActionSupport{

	private List<String> searchEngine;

	private String yourSearchEngine;
	private String yourMonth;

	public String getYourMonth() {
		return yourMonth;
	}

	public void setYourMonth(String yourMonth) {
		this.yourMonth = yourMonth;
	}

	public List<String> getSearchEngine() {
		return searchEngine;
	}

	public void setSearchEngine(List<String> searchEngine) {
		this.searchEngine = searchEngine;
	}

	public String getYourSearchEngine() {
		return yourSearchEngine;
	}

	public void setYourSearchEngine(String yourSearchEngine) {
		this.yourSearchEngine = yourSearchEngine;
	}

	public String getDefaultSearchEngine() {
		return "yahoo.com";
	}

	public SelectAction(){

		searchEngine = new ArrayList<String>();
		searchEngine.add("google.com");
		searchEngine.add("bing.com");
		searchEngine.add("yahoo.com");
		searchEngine.add("baidu.com");
	}

	public String execute() {
		return SUCCESS;
	}

	public String display() {
		return NONE;
	}

} 

2.结果页面

通过“ < s:select > ”标签呈现下拉框,通过 Java list 和 OGNL list 填充选择选项

select.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>

<body>
<h1>Struts 2 drop down box example</h1>

<s:form action="resultAction" namespace="/">

<h2>
	<s:select label="What's your favor search engine" 
		headerKey="-1" headerValue="Select Search Engines"
		list="searchEngine" 
		name="yourSearchEngine" 
		value="defaultSearchEngine" />
</h2> 

<h2>
	<s:select label="Select a month" 
		headerKey="-1" headerValue="Select Month"
		list="#{'1':'Jan', '2':'Feb', '3':'Mar', '4':'Apr'}" 
		name="yourMonth" 
		value="2" />
</h2> 

<s:submit value="submit" name="submit" />

</s:form>

</body>
</html> 

result.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>

<body>
<h1>Struts 2 drop down box example</h1>

<h2>
  Favor search engine : <s:property value="yourSearchEngine"/>
</h2> 

<h2>
  Selected month : <s:property value="yourMonth"/>
</h2> 

</body>
</html> 

3.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>

 <constant name="struts.devMode" value="true" />

<package name="default" namespace="/" extends="struts-default">

   <action name="selectAction" 
         class="com.mkyong.common.action.SelectAction" method="display">
	<result name="none">pages/select.jsp</result>
   </action>

   <action name="resultAction" class="com.mkyong.common.action.SelectAction">
	<result name="success">pages/result.jsp</result>
   </action>
  </package>

</struts> 

5.演示

http://localhost:8080/struts 2 example/select action . action

Struts2 drop down box example

http://localhost:8080/struts 2 example/result action . action

Struts2 drop down box example

参考

  1. Struts 2 选择文档

dropdown struts2

Struts 2

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-stextarea-textarea-example/

Download It – Struts2-TextArea–Example.zip

在 Struts 2 中,你可以使用 < s:textarea > 来创建一个 HTML textarea 字段。

 <s:textarea label="Address" name="address" cols="40" rows="10"/> 

它将呈现为以下 HTML 代码。

 <textarea name="address" cols="40" rows="10" id="formaction_address"></textarea> 

Struts 2

一个页面包含一个地址文本区字段,并在表单提交后显示文本区值。

1.行动

TextAreaAction.java

 package com.mkyong.common.action;

import com.opensymphony.xwork2.ActionSupport;

public class TextAreaAction extends ActionSupport{

	private String address;

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	public String execute() {
		return SUCCESS;
	}

} 

2.查看页面

Struts 2 " s:textarea "标记来创建一个 textarea 字段。

textarea.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>

<body>
<h1>Struts 2 - textarea example</h1>

<s:form action="helloTextarea" namespace="/">

<h2>
  <s:textarea label="Address" name="address" cols="40" rows="10"/>
</h2> 

<s:submit value="submit" name="submit" />

</s:form>

</body>
</html> 

welcome.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>

<body>
<h1>Struts 2 - textarea example</h1>

<h2>
  <s:property value="address"/>
</h2> 

</body>
</html> 

3.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>

 <constant name="struts.devMode" value="true" />

 <package name="" namespace="/" extends="struts-default">
	<action name="textarea">
	      <result>pages/textarea.jsp</result>
	</action>
	<action name="helloTextarea" 
              class="com.mkyong.common.action.TextAreaAction">
	      <result name="success">pages/welcome.jsp</result>
	</action>
  </package>

</struts> 

4.演示

http://localhost:8080/struts 2 example/textarea . action

Struts2 textarea example

参考

  1. Struts 2 文本区文档

struts2 textarea

Struts 2 文本框示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-stextfield-textbox-example/

Download It – Struts2-textbox-Example.zip

在 Struts 2 中,你可以使用 < s:textfield > 来创建一个 HTML 输入框。例如,您可以用一个键属性或标签和名称属性来声明“ s:textfield ”。

 <s:textfield key="username" />
//or
<s:textfield label="Username" name="username" /> 

两者都生成相同的 HTML 输出(默认的 xhtml 主题)。

 <td class="tdLabel">
  <label for="registerUser_username" class="label">Username:</label>
</td>
<td>
  <input type="text" name="username" value="" id="registerUser_username"/>
</td> 

In Struts 2, the “name” will maps to the JavaBean property automatically. In this case, on form submit, the textbox value with “name=’username'” will call the corresponds Action’s setUsername(String xx) to set the value.

Struts 2 示例

在 Struts 2 中创建文本框输入字段的快速指南。

1.属性文件

存储消息的两个属性文件。

global.properties

 #Global messages
username = Username
submit = Submit 

register action . properties

 #error message
username.required = Username is required 

2.行动

一个简单的 Action 类,通过验证来确保用户名不为空,否则返回一个错误消息。

RegisterAction.java

 package com.mkyong.user.action;

import com.opensymphony.xwork2.ActionSupport;

public class RegisterAction extends ActionSupport{

	private String username;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	//business logic
	public String execute() {

		return "SUCCESS";

	}

	//simple validation
	public void validate(){
		if("".equals(getUsername())){
			addFieldError("username", getText("username.required"));
		}
	}
} 

3.查看页面

使用 Struts 2 " s:textfield "创建 HTML 文本框输入字段的结果页面。

register.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>

<body>
<h1>Struts 2 - textbox example</h1>

<s:form action="registerUser" namespace="/user">

	<s:textfield key="username" />
	<s:submit key="submit" name="submit" />

</s:form>

</body>
</html> 

welcome.jsp

 <%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>

<body>
<h1>Struts 2 - textbox example</h1>

<h2><s:property value="username"/></h2>
or
<h2><s:property value="%{username}"/></h2> 

</body>
</html> 

4.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>

   <constant name="struts.custom.i18n.resources" value="global" />
   <constant name="struts.devMode" value="true" />

   <package name="user" namespace="/user" extends="struts-default">
	<action name="register">
		<result>pages/register.jsp</result>
	</action>
	<action name="registerUser" 
                class="com.mkyong.user.action.RegisterAction">
		<result name="SUCCESS">pages/welcome.jsp</result>
		<result name="input">pages/register.jsp</result>
	</action>
   </package>

</struts> 

5.演示

http://localhost:8080/struts 2 example/user/register . action

Struts 2 textbox exampleStruts 2 textbox example

参考

  1. Struts 2 文本字段文档

struts2 textbox

Struts 2 子集标记示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-subset-tag-example/

Download It – Struts2-Subset-Tag-Example.zip

Struts 2 subset 标签用于输出迭代器元素的子集或部分。在本教程中,您将创建一个" numbers "列表,包含 10 个元素(从 1 到 10),并使用 subset 标签" start & count 属性和 decider 方法来输出一个迭代器的子集(列表)。

1.行动

将元素填充到列表中的 Action 类,以及过滤要显示的元素的 decider 方法。

If the decider method return a “true” means display this value; otherwise ignore it. You can do whatever filter logic here.

SubsetTagAction.java

 package com.mkyong.common.action;

import java.util.ArrayList;
import java.util.List;

import org.apache.struts2.util.SubsetIteratorFilter.Decider;
import com.opensymphony.xwork2.ActionSupport;

public class SubsetTagAction extends ActionSupport{

	private List<String> numbers = new ArrayList<String>();

	public String execute() {

		numbers.add("Number 1");
		numbers.add("Number 2");
		numbers.add("Number 3");
		numbers.add("Number 4");
		numbers.add("Number 5");
		numbers.add("Number 6");
		numbers.add("Number 7");
		numbers.add("Number 8");
		numbers.add("Number 9");
		numbers.add("Number 10");

		return SUCCESS;
	}

	public List<String> getNumbers() {
		return numbers;
	}

	public void setNumbers(List<String> numbers) {
		this.numbers = numbers;
	}

	public Decider getNumberDecider() {
	     return new Decider() {
	         public boolean decide(Object obj) throws Exception {
	             String number = ((String)obj).toString();

	             if(("Number 7").equals(number)){
	            	 return true;//display it
	             }else{
	            	 return false;//ignore
	             }
	         }
	     };
	}	
} 

2.子集标签示例

一个 JSP 页面,展示了如何使用 subset 标签来输出迭代器的子集。

The “start” and “count” attribute in the subset tag is start from 0 , which means <s:subset source=”numbers” start=”1″ count=”5″> will extract the element from #2 to #6.

subset.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
 <html>
<head>
</head>

<body>
<h1>Struts 2 Subset tag example</h1>

<table border="1px" cellpadding="8px">
<tr valign="top">
<td>
1\. Display all numbers.
<ol>
<s:subset source="numbers">
   <s:iterator>
      	<li><s:property /></li>
   </s:iterator>
</s:subset>
</ol>
</td>

<td>
2\. Display numbers , from #2 to #6
<ol>
<s:subset source="numbers" start="1" count="5">
   <s:iterator>
      	<li><s:property /></li>
   </s:iterator>
</s:subset>
</ol>
</td>

<td>
3\. Display numbers 7 only, with decider
<ol>
<s:subset source="numbers" decider="numberDecider">
   <s:iterator>
     	<li><s:property /></li>
   </s:iterator>
</s:subset>
</ol>
</td>
</tr>
</table>

</body>
</html> 

3.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>
 	<constant name="struts.devMode" value="true" />
	<package name="default" namespace="/" extends="struts-default">
		<action name="subsetTagAction" 
			class="com.mkyong.common.action.SubsetTagAction" >
			<result name="success">pages/subset.jsp</result>
		</action>
	</package>
</struts> 

4.演示

http://localhost:8080/struts 2 example/subsettagaction . action

输出

Struts 2 subset tag example

参考

  1. Struts 2 子集标签文档

struts2

Struts 2 文本标签示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-text-tag-example/

Download It – Struts2-Text-Tag-Example.zip

Struts 2 " text "标签用于从与 action 类捆绑在一起的资源包中获取消息。并遵循三个顺序:

  1. 显示资源包中的消息,遵循 Struts 2 资源包搜索顺序
  2. 如果在资源包中没有找到消息,那么将显示标记的主体。
  3. 如果标记体为空,那么将显示标记中“name”属性的值。

一个完整的例子很好地说明了这一点:

1.行动

转发请求的操作类。

文本标签 Action.java

 package com.mkyong.common.action;

import com.opensymphony.xwork2.ActionSupport;

public class TextTagAction extends ActionSupport{

	public String execute() throws Exception {

		return SUCCESS;
	}
} 

2.属性文件

一个简单的属性文件,包含两个关键字“ name.msg 和“ name.msg.param ”。

texttagaction . properties

 name.msg = "This is a message from properties file"
name.msg.param = "This is a message from properties file - param : {0}" 

3.文本标签示例

它显示了“文本”标签的使用。

text.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
</head>

<body>
<h1>Struts 2 text tag example</h1>

<h2>1.<s:text name="name.msg" /></h2> 
Output : <s:text name="name.msg" />

<h2>2\. <s:text name="name.msg.unknow">message doesn't exists</s:text></h2> 
Output : <s:text name="name.msg.unknow">message doesn't exists</s:text>

<h2>3\. <s:text name="name.msg.unknow" /></h2> 
Output : <s:text name="name.msg.unknow" />

<h2>4\. <s:text name="name.msg.param" ><s:param >mkyong</s:param>
</s:text></h2> 
Output :
<s:text name="name.msg.param" >
	<s:param >mkyong</s:param>
</s:text>

</body>
</html> 

它是如何工作的?
1。s:text name = " name . msg "/>
从与当前操作类(TextTagAction.action)关联的资源包(text tag action . properties)中获取并显示消息。

 "This is a message from properties file" 

2。<s:text name = " name . msg . unknow ">消息不存在< /s:text >
在资源包“text tag action . properties”或任何搜索顺序中找不到关键字,因此显示标记体。

 message doesn't exists 

3。<s:text name = " name . msg . unknow "/>

 name.msg.unknow 

4。<s:text name = " name . msg . param ">s:param>mkyong</s:param></s:text>
通过< param >标签将参数传入资源包。

 "This is a message from properties file - param : mkyong" 

4.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>
 	<constant name="struts.devMode" value="true" />
	<package name="default" namespace="/" extends="struts-default">

		<action name="textTagAction" 
			class="com.mkyong.common.action.TextTagAction" >
			<result name="success">pages/text.jsp</result>
		</action>

	</package>
</struts> 

5.演示

http://localhost:8080/struts 2 example/text tag action . action

输出

Struts 2 text tag example

参考

  1. Struts 2 文本标签文档

struts2

Struts 2 教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/struts-2-tutorials/

Struts 2 tutorials

Apache Struts 2 ,另一个流行的 Java 模型-视图-控制器(MVC)框架,结合了成功的 WebWorkStruts 1.x web 框架。

Apache Struts 2 与 Struts 1 完全不同,它的核心功能都是通过拦截器、“值堆栈”概念、OGNL 表达式和 Struts 2 标签来处理应用程序数据,以及许多注释和约定来实现的,从而使该框架更易于使用。在本教程中,它提供了许多关于使用 Struts 2 MVC 框架的分步示例和解释。

快乐学习 Struts 2。🙂

Struts 2 快速入门

Struts 2 快速入门示例。

Struts 2 配置

任何关于 Struts 2 配置文件的信息。

Struts 2 操作和表单

Struts 2 动作和表单数据管理。

Struts 2 拦截器

关于 Struts 2 拦截器的一件事。

Struts 2 UI 标签

Struts 2 UI 标签,用于呈现 HTML 表单和非表单组件。

Struts 2 控制标签

Struts 2 控制标签或逻辑标签,帮助做条件处理,迭代,操作和显示数据。

  • 迭代器标签示例
    Struts 2 迭代器标签用于迭代一个值,可以是 java.util.Collection 或 java.util.Iterator 中的任意一个
  • if、elseIf、else 标签示例
    Struts 2 If、ElseIf、Else 标签用于进行基本条件检查。
  • append 标签示例
    Struts 2 append 标签用于将几个迭代器(由 List 或 Map 创建)组合成一个迭代器。
  • 生成器标签示例
    Struts 2 生成器标签用于根据页面中提供的“val”属性生成迭代器。
  • merge 标签示例
    Struts 2 merge 标签用于将几个迭代器(由 List 或 Map 创建)合并成一个迭代器。
  • 排序标签示例
    Struts 2 排序标签用于使用 java.util.Comparator 对列表进行排序
  • subset 标签示例
    Struts 2 subset 标签用于输出迭代器元素的子集或部分。

Struts 2 数据标签

Struts 2 数据标签,帮助从 ValueStack 获取数据,或者将数据放入 values stack。

  • 一个标签示例
    Struts 2 一个标签用于呈现一个 HTML“<一个>标签。
  • action 标签示例
    Struts 2 action 标签用于从 JSP 页面中直接调用 action 类。
  • bean 标签示例
    Struts 2 bean 标签用于在 JSP 页面中实例化一个类。
  • 日期标签示例
    Struts 2 日期标签用于格式化 JSP 页面中的日期对象。
  • 调试标签示例
    Struts 2 调试标签是一个非常有用的调试标签,可以输出 JSP 页面中“值堆栈”的内容以及“堆栈上下文”的详细信息。
  • include 标签示例
    Struts 2 include 标签用于将 JSP 或 HTML 页面直接包含到当前页面中。
  • i18n 标签示例
    Struts 2 i18n 标签用于从任何声明的资源包中获取消息,而不仅仅是与当前动作相关联的资源包。
  • param 标签示例
    Struts 2 param 标签用于参数化其他标签。
  • 属性标签示例
    Struts 2 属性标签用于从一个类中获取属性值,该属性将默认为当前 Action 类。
  • push 标签示例
    Struts 2 push 标签用于将值推送到栈顶,以便于访问或引用。
  • set 标签示例
    Struts 2 set 标签用于为指定范围(应用、会话、请求、页面或动作)内的变量赋值。
  • 文本标签示例
    Struts 2 文本标签用于从与 action 类捆绑在一起的资源包中获取消息。
  • url 标签示例
    Struts 2 的“url”标签用于创建一个 url 并将其输出为文本格式。

Struts 2 资源包和本地化

支持 web 本地化特性的 Struts 2 资源包(多语言)。

Struts 2 主题

Struts 2 的布局是由“xhtml”主题设计的,理解 Struts 2 的主题概念是“必须的”。

Struts 2 与其他框架集成

关于 Struts 2 与其他框架的集成——Spring、Hibernate、Quartz、Log4j……

Struts 2 常见问题

Struts 2 常见问题。

Struts 2 常见错误

Struts 2 常见错误。

Struts 2 参考

Tags : struts2 tutorials

struts 2 up down 选择示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-updownselect-example/

Download It – Struts2-UpDownSelect-Example.zip

在 Struts 2 中, < s:updownselect > 标签用于创建一个 HTML 选择组件,并带有按钮来上下移动选择组件中的选项。提交表单时,所有选择选项将按排列顺序提交。

< s:updownselect >示例

 <s:updownselect
list="#{'KFC':'KFC', 'McDonald':'McDonald', 'Burger King':'Burger King',
'Pizza Hut':'Pizza Hut', 'Fat Boy King':'Fat Boy King'}"
name="favFastFood"
headerKey="-1"
headerValue="--- Please Order ---" 
size="7"
/> 

产生下面的 HTML 代码,选择组件,按钮和 JavaScript 来上下移动选择组件中的选项。(默认 xhtml 主题)

 <tr> 
<td class="tdLabel"></td> 
<td><script type="text/javascript" src="/Struts2Example/struts/optiontransferselect.js">
</script> 
<table> 
<tr><td> 
<select name="favFastFood" size="7" 
id="resultAction_favFastFood" multiple="multiple"> 
    <option value="-1">--- Please Order ---</option> 
    <option value="KFC">KFC</option> 
    <option value="McDonald">McDonald</option> 
    <option value="Burger King">Burger King</option> 
    <option value="Pizza Hut">Pizza Hut</option> 
    <option value="Fat Boy King">Fat Boy King</option> 
</select> 
<input type="hidden" id="__multiselect_resultAction_favFastFood" 
name="__multiselect_favFastFood" value="" /> 
</td></tr> 
<tr><td> 
 <input type="button" value="^" onclick="
moveOptionUp(document.getElementById('resultAction_favFastFood'), 'key', '-1');" />

 <input type="button" value="v" onclick="
moveOptionDown(document.getElementById('resultAction_favFastFood'), 'key', '-1');" />

 <input type="button" value="*" onclick="selectAllOptionsExceptSome(
document.getElementById('resultAction_favFastFood'), 'key', '-1');" />
</td></tr> 
</table></td> 
</tr> 
<script type="text/javascript"> 

var containingForm = document.getElementById("resultAction");
StrutsUtils.addEventListener(containingForm, "submit", 
   function(evt) {
     var updownselectObj = document.getElementById("resultAction_favFastFood");
     selectAllOptionsExceptSome(updownselectObj, "key", "-1");
   }, true);
</script> 

Struts 2 示例

< s:updownselect > 标签的完整示例,展示了如何使用 OGNL 和 Java 列表将数据填充到 updown 选择列表中。

1.动作类

操作类来生成和存储选择选项。

UpDownSelectAction.java

 package com.mkyong.common.action;

import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class UpDownSelectAction extends ActionSupport{

	private List<String> moviesList = new ArrayList<String>();

	private String favMovie;
	private String favFastFood;

	public UpDownSelectAction(){

		moviesList.add("Spider Man");
		moviesList.add("Matrix");
		moviesList.add("Super Man");
		moviesList.add("Dark Knight");
		moviesList.add("BraveHeart");
		moviesList.add("Ultraman");

	}

	public String getFavFastFood() {
		return favFastFood;
	}

	public void setFavFastFood(String favFastFood) {
		this.favFastFood = favFastFood;
	}

	public List<String> getMoviesList() {
		return moviesList;
	}

	public void setMoviesList(List<String> moviesList) {
		this.moviesList = moviesList;
	}

	public String getFavMovie() {
		return favMovie;
	}

	public void setFavMovie(String favMovie) {
		this.favMovie = favMovie;
	}

	public String execute() throws Exception{

		return SUCCESS;
	}

	public String display() {
		return NONE;
	}

} 

2.结果页面

通过“ < s:updownselect > ”标签渲染 updown select 组件。

updownselect.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>

<body>
<h1>Struts 2 updownselect example</h1>

<s:form action="resultAction" namespace="/" method="POST" >

<s:updownselect
list="#{'KFC':'KFC', 'McDonald':'McDonald', 'Burger King':'Burger King',
'Pizza Hut':'Pizza Hut', 'Fat Boy King':'Fat Boy King'}"
name="favFastFood"
headerKey="-1"
headerValue="--- Please Order ---" 
size="7"
/>

<s:updownselect
list="moviesList"
name="favMovie"
headerKey="-1"
headerValue="--- Please Order ---"
size="10"
moveUpLabel="Move Up"
moveDownLabel="Move Down"
selectAllLabel="Select All" />

<s:submit value="submit" name="submit" />

</s:form>

</body>
</html> 

result.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>

<body>
<h1>Struts 2 updownselect example</h1>

<h2>
   Favor fast food : <s:property value="favFastFood"/> 
</h2> 

<h2>
   Favor movies : <s:property value="favMovie"/> 
</h2> 

</body>
</html> 

3.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>

    <constant name="struts.devMode" value="true" />

   <package name="default" namespace="/" extends="struts-default">

   <action name="updownSelectAction" 
       class="com.mkyong.common.action.UpDownSelectAction" method="display">
       <result name="none">pages/updownselect.jsp</result>
   </action>

   <action name="resultAction" class="com.mkyong.common.action.UpDownSelectAction" >
       <result name="success">pages/result.jsp</result>
   </action>
  </package>

</struts> 

4.演示

http://localhost:8080/struts 2 example/updownselectaction . action
选择选项并上下移动。

Struts 2 updownselect example

提交时,所有选项将按排列顺序提交。

Struts 2 updownselect example

参考

  1. Struts 2 updownselect 示例
  2. http://www . mkyong . com/struts 2/struts-2-sdoubleselect-example/

struts2

Struts 2 上传多个文件示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-upload-multiple-files-example/

Download It – Struts2-Multiple-Files-Upload-Example.zip

在最后一个 Struts 2 文件上传示例中,允许用户选择单个文件并上传到服务器。在本教程中,您将学习如何允许用户上传多个文件到服务器。

1.动作类

在 Action 类中,可以使用 List 或 Array 来存储上传的文件。

FileUploadAction.java

 package com.mkyong.common.action;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import com.opensymphony.xwork2.ActionSupport;

public class MultipleFileUploadAction extends ActionSupport{

	private List<File> fileUpload = new ArrayList<File>();
	private List<String> fileUploadContentType = new ArrayList<String>();
	private List<String> fileUploadFileName = new ArrayList<String>();

	public List<File> getFileUpload() {
		return fileUpload;
	}

	public void setFileUpload(List<File> fileUpload) {
		this.fileUpload = fileUpload;
	}

	public List<String> getFileUploadContentType() {
		return fileUploadContentType;
	}

	public void setFileUploadContentType(List<String> fileUploadContentType) {
		this.fileUploadContentType = fileUploadContentType;
	}

	public List<String> getFileUploadFileName() {
		return fileUploadFileName;
	}

	public void setFileUploadFileName(List<String> fileUploadFileName) {
		this.fileUploadFileName = fileUploadFileName;
	}

	public String upload() throws Exception{

	    for (File file: fileUpload) {
	        System.out.println("File :" + file);
	    }

	    for (String fileName: fileUploadFileName) {
	        System.out.println("Filename : " + fileName);
	    }

	    for (String fileContentType: fileUploadContentType) {
	        System.out.println("File type : " + fileContentType);
	    }

	    return SUCCESS;

	}

	public String display() {
		return NONE;
	}

} 

2.结果页面

使用 < s:file > 标签渲染多个文件上传组件,将表单 enctype 类型设置为“multipart/form-data”

fileupload.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<s:head />
</head>

<body>
<h1>Struts 2 upload multiple files example</h1>

<s:form action="resultAction" namespace="/" 
method="POST" enctype="multipart/form-data">

<s:file label="File 1" name="fileUpload" size="40" />
<s:file label="File 2" name="fileUpload" size="40" />
<s:file label="FIle 2" name="fileUpload" size="40" />

<s:submit value="submit" name="submit" />

</s:form>

</body>
</html> 

result.jsp

 <%@ taglib prefix="s" uri="/struts-tags" %>
<html>

<body>
<h1>Struts 2 upload multiple files example</h1>

<script async src="//pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script>

<script>
(adsbygoogle = window.adsbygoogle || []).push({});
</script><h2>
   File Name : <s:property value="fileUploadFileName"/> 
</h2> 

<h2>
   Content Type : <s:property value="fileUploadContentType"/> 
</h2> 

<h2>
   File : <s:property value="fileUpload"/> 
</h2> 

</body>
</html> 

3.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>

 	<constant name="struts.devMode" value="true" />

	<package name="default" namespace="/" extends="struts-default">

	<action name="multipleFileUploadAction" 
	    class="com.mkyong.common.action.MultipleFileUploadAction" 
            method="display">
		<result name="none">pages/multiplefileupload.jsp</result>
	</action>

	<action name="resultAction" 
	     class="com.mkyong.common.action.MultipleFileUploadAction" 
             method="upload">
		 <result name="success">pages/result.jsp</result>
	</action>
   </package>

</struts> 

4.演示

http://localhost:8080/struts 2 example/multiplefileuploadaction . action

Struts 2 Multiple files upload exampleStruts2 Multiple files upload example

参考

  1. Struts 2 文件上传示例
  2. Struts 2 文件文档
  3. http://struts.apache.org/2.0.14/docs/file-upload.html
  4. http://struts . Apache . org/2 . 0 . 14/docs/how-do-we-upload-files . html
  5. http://www.mkyong.com/struts/struts-file-upload-example/

file upload struts2 (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190225092247/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

Struts 2 URL 标记示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts2/struts-2-url-tag-example/

Download It – Struts2-URL-Tag-Example.zip

Struts 2 " url "标签用于创建一个 url 并以文本格式输出。它本身从不工作,但它可以提供其他标签的 URL,如 < s:a > 创建超链接或 < img > 呈现图像。在本教程中,它展示了 Struts 2 " url 标签的 5 个常见用例。

1.行动

转发请求的操作类。

尖叫。java

 package com.mkyong.common.action;

import com.opensymphony.xwork2.ActionSupport;

public class URLTagAction extends ActionSupport{

	public String execute() {
		return SUCCESS;
	}

} 

2.Url 标记示例

下面的 5 个例子展示了 Struts 2 " url 标签的使用。

  1. Create an image url.

     <img src="<s:url valueimg/man.jpg"/>" /> 
    

    输出(假设根上下文名是“Struts2Example”)

     <img src="/Struts2Exampimg/man.jpg" /> 
    
  2. Create a “Google” text and link it to http://www.google.com.

     <a href="<s:url value="http://www.google.com"  />" target="_blank">Google</a> 
    

    输出

     <a href="http://www.google.com" target="_blank">Google</a> 
    

    When you define the URL value with starting of “http” or “www” words, Struts 2 will render it as it is, without add the extra root context name as example 1.

  3. Create an Action URL with a “id” parameter, and output it as a text format.

     <s:url action="urlTagAction.action" >
        <s:param name="id">123</s:param>
    </s:url> 
    

    输出

     /Struts2Example/urlTagAction.action?id=123 
    
  4. Create an Action URL with a “name” parameter, and combine with <s:a> tag via <s:property>.

     <s:url action="urlTagAction.action" var="urlTag" >
        <s:param name="name">mkyong</s:param>
    </s:url>
    <a href="<s:property value="#urlTag" />" >URL Tag Action (via property)</a> 
    

    输出

     <a href="/Struts2Example/urlTagAction.action?name=mkyong" >URL Tag Action (via property)</a> 
    
  5. Create an Action URL with a “age” parameter, and combine with <s:a> tag via “%{urlTag}“.

     <s:url action="urlTagAction.action" var="urlTag" >
        <s:param name="age">99</s:param>
    </s:url>
    <s:a href="%{urlTag}">URL Tag Action (via %)</s:a> 
    

    输出

     <a href="/Struts2Example/urlTagAction.action?age=99">URL Tag Action (via %)</a> 
    

完整的 JSP 页面代码…

URL . JSP

 <%@ taglib prefix="s" uri="/struts-tags" %>
 <html>
<head>
</head>

<body>
<h1>Struts 2 URL tag example</h1>

<ol>
<li>
<img src="<s:url valueimg/man.jpg"/>" />
</li>

<li>
<a href="<s:url value="http://www.google.com"  />" target="_blank">Google</a>
</li>

<li>
<s:url action="urlTagAction.action" >
    <s:param name="id">123</s:param>
</s:url>
</li>

<li>
<s:url action="urlTagAction.action" var="urlTag" >
    <s:param name="name">mkyong</s:param>
</s:url>
<a href="<s:property value="#urlTag" />" >URL Tag Action (via property)</a>
</li>

<li>
<s:url action="urlTagAction.action" var="urlTag" >
    <s:param name="age">99</s:param>
</s:url>
<s:a href="%{urlTag}">URL Tag Action (via %)</s:a>
</li>

</ol>

</body>
</html> 

3.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>
    <constant name="struts.devMode" value="true" />
    <package name="default" namespace="/" extends="struts-default">

	<action name="urlTagAction" 
		class="com.mkyong.common.action.URLTagAction" >
		<result name="success">pages/url.jsp</result>
	</action>

    </package>		
</struts> 

4.演示

http://localhost:8080/struts 2 example/urltagaction . action

输出

Struts 2 url tag example

参考

  1. Struts 2 Url 标记文档

struts2 url

Struts DispatchAction 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-dispatchaction-example/

DispatchAction 类(org . Apache . struts . Actions . dispatch action)提供了一种将所有相关函数分组到单个 action 类中的方法。这是一种有用机制,可以避免为每个函数创建单独的 action 类。

Download this Struts DispatchAction example – Struts-DispatchAction-Example.zip

要实现这个机制,您的 Action 类需要扩展org . Apache . struts . actions . dispatch action类,这个 action 类不需要像普通 action 类那样实现 execute() 方法。相反,DispatchAction 类将根据传入的请求参数执行方法—方法。例如,如果参数是“method=chinese”,那么将执行 chinese()方法。

例子

action 类扩展了 DispatchAction,并包含四种方法来将 locale 设置到本地化的 Struts 会话属性中。

 public class LanguageSelectAction extends DispatchAction{

	public ActionForward chinese(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {

		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.SIMPLIFIED_CHINESE);

		return mapping.findForward("success");
	}

	public ActionForward english(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {

		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.ENGLISH);

		return mapping.findForward("success");
	}

	public ActionForward german(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {

		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.GERMAN);

		return mapping.findForward("success");
	}

	public ActionForward france(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {

		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.FRANCE);

		return mapping.findForward("success");
	}

} 

这个 Struts html 标记将执行 chinese()方法。

Chinese

这个 Struts html 标记将执行 english()方法。

English

这个 Struts html 标记将执行 german()方法。

German

这个 Struts html 标记将执行 france()方法。

France

struts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190223075601/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

struts–从网站下载文件示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-download-file-from-website-example/

要让用户从您的 Struts web 项目下载文件,您必须通知" HttpServletResponse "返回一个应用程序文件,而不是普通的 HTML 页面。

 response.setContentType("application/octet-stream");
response.setHeader("Content-Disposition",
"attachment;filename=downloadfilename.csv"); 

在服务器端,你可以从三种不同的方式获得下载文件

1.文件系统

从文件系统获取

 FileInputStream in = 
  new FileInputStream(new File("C:\\filename.zip")); 
2.项目 web 路径

假设您的文件位于“http://yourname.com/StrutsExample/upload/filename.zip”,并且“支撑示例是您的项目名称(serlvet 上下文)。

 //jndi:/yourname.com/StrutsExample/upload/filename.zip
URL url = getServlet().getServletContext().getResource("upload/filename.zip");
InputStream in = url.openStream(); 
3.字节数组

如果您从数据库中检索文件或 blob 数据,它通常以字节数组的形式返回。

 byte[] bytes = new byte[4096];
InputStream in = new ByteArrayInputStream(bytes); 

Download this Struts download file example – Struts-Download-File-Example.zip

1.动作类

一个 action 类,返回一个应用程序文件而不是普通的 HTML 页面,并获得“superfish.zip”文件供用户下载。

 package com.mkyong.common.action;

import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;

import javax.servlet.ServletContext;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class DownloadFileAction extends Action{

   @Override
   public ActionForward execute(ActionMapping mapping, ActionForm form,
     HttpServletRequest request, HttpServletResponse response)
     throws Exception {

     //return an application file instead of html page
     response.setContentType("application/octet-stream");
     response.setHeader("Content-Disposition","attachment;filename=superfish.zip");

     try 
     {
       	//Get it from file system
       	FileInputStream in = 
      		new FileInputStream(new File("C:\\superfish.zip"));

        //Get it from web path
        //jndi:/localhost/StrutsExample/upload/superfish.zip
        //URL url = getServlet().getServletContext()
        //               .getResource("upload/superfish.zip");
        //InputStream in = url.openStream();

        //Get it from bytes array
        //byte[] bytes = new byte[4096];
        //InputStream in = new ByteArrayInputStream(bytes);

        ServletOutputStream out = response.getOutputStream();

        byte[] outputByte = new byte[4096];
        //copy binary content to output stream
        while(in.read(outputByte, 0, 4096) != -1){
        	out.write(outputByte, 0, 4096);
        }
        in.close();
        out.flush();
        out.close();

     }catch(Exception e){
    	e.printStackTrace();
   }

   return null;
  }
} 

2.JSP 页面

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

Download file from server - 
struts-tutorial.zip 

3.struts-config.xml

Struts 配置文件。

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

		<action
			path="/DownloadPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/display.jsp"/>

		<action
			path="/DownloadIt"
			type="com.mkyong.common.action.DownloadFileAction"
			>
		</action>

	</action-mappings>

</struts-config> 

4.测试一下

http://localhost:8080/struts example/download page . do

struts-download-file-example1download file struts

Struts DynaActionForm 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-dynaactionform-example/

Struts DynaActionForm 类是一个有趣的特性,它允许您以动态和声明的方式创建表单 bean。它使您能够在 Struts 配置文件中创建一个“虚拟”表单 bean,而不是创建一个真正的 Java 表单 bean 类。它可以避免您创建许多简单但繁琐的表单 bean 类。

例如,DynaActionForm 包含一个“用户名”属性。

 <form-bean name="dynaUserForm"   
	type="org.apache.struts.action.DynaActionForm">
    <form-property name="username" type="java.lang.String"/>
</form-bean> 

“DynaActionForm”和“ActionForm”的区别

  • 创建真正的 Java 类不需要 DynaActionForm(只需在 Struts 配置文件中声明),但 ActionForm 需要。
  • 在 DynaActionForm 中,表单验证是在 Action 类中实现,而 ActionForm 是在自己的类中实现的。

DynaActionForm 示例

Strutshtml:texttextbox 示例将被重构为使用“DynaActionForm”而不是普通的“ActionForm”。

Download Struts DynaActionForm example – Struts-DynaActionForm-Example.zip

1.struts-config.xml

在 Struts 配置文件中声明“DynaActionForm ”,并像 normal 一样将其链接到 Action 类。

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		<!--<form-bean
			name="userForm"
			type="com.mkyong.common.form.UserForm"/>
		-->
		<form-bean name="dynaUserForm"   
		      type="org.apache.struts.action.DynaActionForm">
		      <form-property name="username" type="java.lang.String"/>
		</form-bean>

	</form-beans>

	<action-mappings>

	        <action
			path="/LoginPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/login.jsp"/>

		<action
			path="/Login"
			type="com.mkyong.common.action.UserAction"
			name="dynaUserForm"
			>	

			<forward name="success" path="/pages/welcome.jsp"/>
			<forward name="failed" path="/pages/login.jsp"/>

		</action>
	</action-mappings>

	<message-resources
		parameter="com.mkyong.common.properties.Common" />

</struts-config> 

2.行动

将所有表单验证方法移动到 Action 类中,通过“ get() ”方法获取“DynaActionForm”属性。

user action . Java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.action.ActionMessages;
import org.apache.struts.action.DynaActionForm;

public class UserAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		DynaActionForm userForm = (DynaActionForm)form;

		ActionMessages errors = new ActionMessages();

		//do the form validation in action class
	    if( userForm.get("username") == null || 
                         ("".equals(userForm.get("username")))) {

	       errors.add("common.name.err",
                    new ActionMessage("error.common.name.required"));

	    }

	    saveErrors(request,errors);

	    if(errors.isEmpty()){
	        return mapping.findForward("success");
	    }else{
	        return mapping.findForward("failed");
	    }

	}

} 

结论

你应该选择 DynaActionForm 吗?此功能可以节省您创建 ActionForm 类的大量时间,但是它有局限性,有时您必须使用真正的 ActionForm 来完成某些任务。在大型项目环境中,维护总是要考虑的第一优先事项,您必须创建一个“表单标准”来遵循,混合使用这两者是不实际的,除非您有非常坚实的理由来支持。就我个人而言,我很少使用 DynaActionForm,有了 Eclipse IDE,ActionForm 毕竟不是很难创建。

hello botsstruts

Struts 错误–NoSuchMethodError:digester . parse(Ljava/net/URL;)Ljava/lang/Object

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-error-nosuchmethoderror-digester-parseljavaneturlljavalangobject/

问题

在 Struts 初始化期间,它会遇到以下错误消息。

 SEVERE: Unable to initialize Struts ActionServlet due to an unexpected exception or error thrown, 
so marking the servlet as unavailable.  Most likely, this is due to an incorrect or missing library dependency.
java.lang.NoSuchMethodError: org.apache.commons.digester.Digester.parse(Ljava/net/URL;)Ljava/lang/Object;
	at org.apache.commons.chain.config.ConfigParser.parse(ConfigParser.java:190)
	at org.apache.struts.action.ActionServlet.initChain(ActionServlet.java:1687) 

解决办法

这是由于某些方法在 commons 消化器库中找不到。您需要将您的 commons-digester.jar 升级到最新版本。

在这种情况下,我使用的是“Struts 1 . 3 . 10+commons-digester-1.6 . jar+Struts-tiles 1 . 3 . 10”组合,并点击上面的错误消息。升级到最新的 commons-digester-2.0.jar 后,错误信息消失了。

struts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190209023720/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

Struts 文件上传示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-file-upload-example/

在本教程中,您将学习如何使用 Struts < html:file > 标签将文件上传到服务器文件系统。

Download this Struts file upload example – Struts-FileUpload-Example.zip

1.动作形式

在 Action form 中,创建一个org . Apache . struts . upload . form file变量来保存上传的文件,以及上传文件的表单验证。

 package com.mkyong.common.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;
import org.apache.struts.upload.FormFile;

public class FileUploadForm extends ActionForm{

	private FormFile file;

	public FormFile getFile() {
		return file;
	}

	public void setFile(FormFile file) {
		this.file = file;
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
	   HttpServletRequest request) {

	    ActionErrors errors = new ActionErrors();

	    if( getFile().getFileSize()== 0){
	       errors.add("common.file.err",
	    	new ActionMessage("error.common.file.required"));
	       return errors;
	    }

	    //only allow textfile to upload
	    if(!"text/plain".equals(getFile().getContentType())){
	        errors.add("common.file.err.ext",
	    	 new ActionMessage("error.common.file.textfile.only"));
	        return errors;
	    }

            //file size cant larger than 10kb
	    System.out.println(getFile().getFileSize());
	    if(getFile().getFileSize() > 10240){ //10kb
	       errors.add("common.file.err.size",
		    new ActionMessage("error.common.file.size.limit", 10240));
	       return errors;
	    }

	    return errors;
	}
} 

2.行动

在 Action 类中,只需获取上传的文件并将其保存到服务器文件系统中,并将新创建的文件详细信息存储到一个会话中以备后用。

 package com.mkyong.common.action;

import java.io.File;
import java.io.FileOutputStream;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.upload.FormFile;

import com.mkyong.common.form.FileUploadForm;

public class FileUploadAction extends Action{

	@Override
	public ActionForward execute(ActionMapping mapping, ActionForm form,
	    HttpServletRequest request, HttpServletResponse response)
	    throws Exception {

	    FileUploadForm fileUploadForm = (FileUploadForm)form;

	    FormFile file = fileUploadForm.getFile();

	    //Get the servers upload directory real path name
	    String filePath = 
               getServlet().getServletContext().getRealPath("/") +"upload";

	    //create the upload folder if not exists
	    File folder = new File(filePath);
	    if(!folder.exists()){
	    	folder.mkdir();
	    }

	    String fileName = file.getFileName();

	    if(!("").equals(fileName)){  

	        System.out.println("Server path:" +filePath);
	        File newFile = new File(filePath, fileName);

	        if(!newFile.exists()){
	          FileOutputStream fos = new FileOutputStream(newFile);
	          fos.write(file.getFileData());
	          fos.flush();
	          fos.close();
	        }  

	        request.setAttribute("uploadedFilePath",newFile.getAbsoluteFile());
	        request.setAttribute("uploadedFileName",newFile.getName());
	    }
		return mapping.findForward("success");
	}
} 

3.JSP

你要将 < html:form > 标签的编码类型设置为“ multipart/form-data ”,并将 HTTP 方法指定为“ post ”。

fileupload.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

<message key="label.common.title"></message>

:

display.jsp


	File uploaded to : <%= request.getAttribute("uploadedFilePath") %>

	">
        Click here to download it

4.struts-config.xml

将所有连接在一起

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		<form-bean
			name="fileUploadForm"
			type="com.mkyong.common.form.FileUploadForm"/>

	</form-beans>

	<action-mappings>

		<action
			path="/UploadPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/fileupload.jsp"/>

		<action
			path="/Upload"
			type="com.mkyong.common.action.FileUploadAction"
			name="fileUploadForm"
			validate="true"
			input="/pages/fileupload.jsp"
			>
			<forward name="success" path="/pages/display.jsp"/>
		</action>

	</action-mappings>

	<message-resources
		parameter="com.mkyong.common.properties.Common" />

</struts-config> 

测试一下

http://localhost:8080/struts example/upload page . do
选择一个文件,点击提交按钮。

Struts-file-upload-example1

http://localhost:8080/struts example/upload . do
它会转发到 display.jsp 并显示上传的文件详情。

Struts-file-upload-example2file upload struts

Struts ForwardAction 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-forwardaction-example/

Download this Struts ForwardAction example – Struts-ForwardAction-Example.zip

在 Struts MVC 模型中,你必须通过动作控制器来获得一个新的视图页面。在某些情况下,你真的只需要得到一个指定的 JSP 页面,例如,创建一个动作控制器类来把页面转发给你是很愚蠢的

 public ActionForward execute(ActionMapping mapping,ActionForm form,
	HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

	return mapping.findForward("success");
} 
 <action path="/Welcome"
	type="com.mkyong.common.action.WelcomeAction">
	<forward name="success" path="/Welcome.jsp"/>
   </action> 

Struts 附带了一个特殊的动作控制器类,名为forward action(org . Apache . struts . actions . forward action),如名称所述执行“只进任务,并允许您直接访问指定的 JSP 页面。

例子

声明一个“/Welcome”web 路径,类型属性为 ForwardAction 类,转发到【Welcome.jsp】页面

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

		<action
			path="/Welcome"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/Welcome.jsp"/>

	</action-mappings>

</struts-config> 

Welcome.jsp


这是欢迎页面

创建一个index.jsp页面,当用户点击链接时,它会转到/欢迎(返回 Welcome.jsp)

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

ForwardAction 示例
<link page="/Welcome.do">点击我进入 JSP 欢迎页面 

http://localhost:8080/struts example/,点击链接。

struts-forwardaction-example1

会转发到http://localhost:8080/struts example/welcome . do

struts-forwardaction-example2struts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190309053058/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

struts–自定义异常处理程序示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-global-custom-exception-example/

Download this example – Struts-Global-Exception-Example.zip

在 Struts 框架中, <全局异常> 用于显示您自定义的错误页面,而不是默认的经典 HTTP Status 500 错误页面:

struts-global-exception-1

默认错误页面看起来很难看,一点也不专业。此外,错误消息的描述性足以将您的系统信息泄露给最终用户。

1. +默认异常处理程序

这里有一个 <全局异常> 示例,在“struts.config.xml”中声明了默认异常处理程序,用您的自定义描述性错误页面替换默认 HTTP 500 错误页面。

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		//...
	</form-beans>

        <global-exceptions>
	    <exception
	      key="error.global.mesage"
	      type="java.io.IOException"
	      path="/pages/error.jsp" />
	</global-exceptions>

	<action-mappings>
		//...
	</action-mappings>

</struts-config> 

在上面的例子中,当一个动作抛出任何 IOException 时,都会调用默认的 Struts 异常处理程序"org . Apache . Struts . Action . exception handler,并将其转发到 error.jsp 文件。该键是消息资源属性文件中的一个键。

公共属性

 #common module error message
error.global.mesage = 
   Ooooppps... Sometime wraong in this site, please come back later 

error.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

Struts 全局异常示例

2. +自定义异常处理程序

在默认的异常处理程序中,您无法控制如何处理异常。在大多数情况下,您可能需要记录该异常以供进一步分析。为此,您需要一个定制的异常处理程序来将所有异常记录到另一个数据存储中,如文件系统或数据库。

这里有一个自定义异常处理程序的例子,可以为" java.lang.Exception "配置,这样它就可以被 Action 抛出的任何异常调用。要创建自定义异常处理程序,您需要子类化“org . Apache . struts . action . exception handler”并覆盖 execute 方法。

MyCustomExceptionHandler.java

 package com.mkyong.common.exception;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.log4j.Logger;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ExceptionHandler;
import org.apache.struts.config.ExceptionConfig;

public class MyCustomExceptionHandler extends ExceptionHandler{

  private static final Logger logger = 
      Logger.getLogger(MyCustomExceptionHandler.class);

  @Override
  public ActionForward execute(Exception ex, ExceptionConfig ae,
	ActionMapping mapping, ActionForm formInstance,
	HttpServletRequest request, HttpServletResponse response)
	throws ServletException {

	//log the error message
	logger.error(ex);

	return super.execute(ex, ae, mapping, formInstance, request, response);
  }
} 
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		//...
	</form-beans>

        <global-exceptions>
	    <exception
	      key="error.global.mesage"
	      type="java.io.IOException"
	      handler="com.mkyong.common.exception.MyCustomExceptionHandler"
	      path="/pages/error.jsp" />
	</global-exceptions>

	<action-mappings>
		//...
	</action-mappings>

</struts-config> 

在上面的代码中,当异常被 Action 抛出时,它将调用您的自定义异常处理程序 MyCustomExceptionHandler 的 execute() 方法,而不是默认的异常处理程序。

参考

  1. Struts 异常处理程序-http://struts . Apache . org/1 . x/user guide/building _ controller . html

exception handler struts

struts–XML 解析异常

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-global-exception-xml-parsing-exception/

问题

struts-config.xml 中的一个 <全局异常> 异常处理程序示例

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<global-exceptions>
	    <exception
	      key="error.io.key"
	      type="java.io.IOException"
	      path="/error.jsp" />
	</global-exceptions>

	<form-beans>
		<form-bean name="dynaUserForm"   
		      type="org.apache.struts.action.DynaActionForm">
		      <form-property name="username" type="java.lang.String"/>
		</form-bean>
	</form-beans>

	<action-mappings>
	    //...
	</action-mappings>

</struts-config> 

部署过程中,提示org . Apache . commons . digester . digester错误。

 19 April 2010 6:50:13 PM org.apache.commons.digester.Digester error
SEVERE: Parse Error at line 52 column 17: The content of element type 
"struts-config" must match "(display-name?,description?,form-beans?,
global-exceptions?,global-forwards?,action-mappings?,controller?,
message-resources*,plug-in*)". 

<全局异常> 语法绝对正确,你发现错误了吗?

解决办法

struts-config.xml " 的元素必须以正确的顺序出现。再次查看错误消息:

 "struts-config" must match 
display-name?,
description?,
form-beans?,
global-exceptions?,
global-forwards?,
action-mappings?,
controller?,
message-resources*,
plug-in* 

<表单-bean>必须出现在 <全局-异常> 之前。您需要将 struts-config.xml 更改为以下顺序:

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		<form-bean name="dynaUserForm"   
		      type="org.apache.struts.action.DynaActionForm">
		      <form-property name="username" type="java.lang.String"/>
		</form-bean>
	</form-beans>

        <global-exceptions>
	    <exception
	      key="error.io.key"
	      type="java.io.IOException"
	      path="/error.jsp" />
	</global-exceptions>

	<action-mappings>
	    //...
	</action-mappings>

</struts-config> 

struts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190209023104/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

Struts Hello World 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-hello-world-example/

在本教程中,我们将向您展示如何使用经典的 Struts 1.3 框架开发 hello world web 应用程序。

使用的工具和技术:

  1. Struts 1.3.10
  2. 胃 2.x
  3. Eclipse 3.6

最终项目结构

我们先来看看最终的文件夹结构。

Struts-Hello-World-Maven

1.Maven 模板

用 Maven 命令“ mvn 原型:生成”生成快速入门 Java 项目结构,选择模板 18 为简单的 Java web 项目模板。

 Define value for groupId: : com.mkyong.common
Define value for artifactId: : StrutsExample
Define value for version:  1.0-SNAPSHOT: :
Define value for package:  com.mkyong.common: : com.mkyong.common
...
[INFO] ------------------------------------------------------------------------
[INFO] BUILD SUCCESSFUL
[INFO] ------------------------------------------------------------------------
[INFO] Total time: 1 minute 5 seconds
[INFO] Finished at: Thu Apr 08 11:29:30 SGT 2010
[INFO] Final Memory: 8M/14M
[INFO] ------------------------------------------------------------------------ 

2.pom.xml 文件配置

在 pom.xml 中添加 Struts 依赖项,在 Struts 1.x 中,核心模块需要 struts-core.jar ,标签库需要 struts-taglib.jar

 <project  
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
  http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mkyong.common</groupId>
  <artifactId>StrutsExample</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>StrutsExample Maven Webapp</name>
  <url>http://maven.apache.org</url>
  <dependencies>
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>3.8.1</version>
      <scope>test</scope>
    </dependency>

    <dependency>
      <groupId>org.apache.struts</groupId>
	  <artifactId>struts-core</artifactId>
      <version>1.3.10</version>
    </dependency>

    <dependency>
      <groupId>org.apache.struts</groupId>
	  <artifactId>struts-taglib</artifactId>
      <version>1.3.10</version>
    </dependency>

  </dependencies>
  <build>
    <finalName>StrutsExample</finalName>
  </build>
</project> 

3.Eclipse IDE

用 Maven 命令“mvn Eclipse:Eclipse-Dwtpversion = 1.5”将这个项目转换成 Eclipse web 项目。所有 Struts 相关的库将自动下载到您的 Maven 本地存储库中,在您的项目类路径中链接它,并将其转换为 Eclipse 的 web 项目风格。

 E:\workspace\struts\StrutsExample>mvn eclipse:eclipse -Dwtpversion=1.5
[INFO] Scanning for projects...
[INFO] Searching repository for plugin with prefix: 'eclipse'.
[INFO] ------------------------------------------------------------------------
[INFO] Building StrutsExample Maven Webapp 

只需将其导入 Eclipse IDE。

4.动作形式

稍后创建一个 Struts 动作表单来保存“hello world”数据。

 package com.mkyong.common.form;

import org.apache.struts.action.ActionForm;

public class HelloWorldForm extends ActionForm{

	String message;

	public String getMessage() {
		return message;
	}

	public void setMessage(String message) {
		this.message = message;
	}

} 

5.动作(控制器)

创建一个 Struts Action (Action Controller)文件来控制 Struts 如何转发请求,只需在这里用自己的逻辑覆盖 execute() 方法。

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mkyong.common.form.HelloWorldForm;

public class HelloWorldAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response)
        throws Exception {

		HelloWorldForm helloWorldForm = (HelloWorldForm) form;
		helloWorldForm.setMessage("Hello World! Struts");

		return mapping.findForward("success");
	}

} 

6.JSP 视图页面

创建一个 JSP 页面,通过 Struts 标记库访问动作表单对象,并打印它的消息属性。

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

7.struts-config.xml

为 struts 配置细节创建一个 struts-config.xml 文件,放入 WEB-INF 文件夹。

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
	   <form-bean name="helloWorldForm" 
		type="com.mkyong.common.form.HelloWorldForm"/>
	</form-beans>

	<action-mappings>
	   <action path="/helloWorld"
		type="com.mkyong.common.action.HelloWorldAction"
		name="helloWorldForm">
		<forward name="success" path="/HelloWorld.jsp"/>

	   </action>
	</action-mappings>

</struts-config> 

定义一个名为" helloWorldForm "的表单 bean 和动作控制器映射" HelloWorldAction ,将 /helloWorld web 路径匹配到 HelloWorldAction 。这意味着所有来自 /helloWorld web path 的请求都将被重定向到 HelloWorldAction 。“name”属性用于定义哪个动作形式将传递给这个 HelloWorldAction

8.Web 应用程序部署描述符

web.xml 文件中,配置 Struts ActionServlet 实例,并将其映射为 url-pattern "*。做”,以便容器意识到所有的 *。do "模式将重定向到 Struts ActionServlet

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

<web-app>
  <display-name>Maven Struts Examples</display-name>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app> 

9.Java EE 模块依赖性(可选)

如果您想在 Eclipse IDE 中进行调试工作,您必须确保检查了 Java EE 模块依赖关系,以便 Eclipse 将所有依赖关系部署到正确的文件夹中。详见此处

10.运行它

在 Eclipse IDE 中,创建一个新的服务器插件并启动它。您可以在下面的 URL 中访问这个示例。

http://localhost:8080/struts example/hello world . do

Struts-Hello-World-Maven2HttpServletRequest class not found?
If you hit above error, make sure you include the javaee.jar (exists in your JDK/lib folder). Due to license issue, this javaee.jar is not able to use Maven to download it, you have to include it manually.

[计] 下载

Download It – Struts-Hello-World-Example.zip

参考

Struts + Hibernate 集成示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-hibernate-integration-example/

一个教程,展示了如何在用 Apache Struts 1.x 开发的 web 应用程序中集成 Hibernate。

Download It – Struts-Hibernate-Example.zip

整合步骤:

  1. 创建一个新的 Hibernate Struts 插件文件,在 servlet 上下文中设置 Hibernate 会话工厂,并将该文件包含在 struts-config.xml 文件中。
  2. 在 Struts 中,从 servlet 上下文中获取 Hibernate 会话工厂,并执行您想要的任何 Hibernate 任务。

1.Hibernate Struts 插件

创建一个 Hibernate Struts 插件,获取 Hibernate 会话工厂,将其存储到 servlet 上下文中,供以后的用户使用—servlet . getservletcontext()。setAttribute(KEY_NAME,factory);

 package com.mkyong.common.plugin;

import java.net.URL;
import javax.servlet.ServletException;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.hibernate.HibernateException;
import org.hibernate.MappingException;
import org.hibernate.SessionFactory;
import org.hibernate.cfg.Configuration;

public class HibernatePlugin implements PlugIn {
   private Configuration config;
   private SessionFactory factory;
   private String path = "/hibernate.cfg.xml";
   private static Class clazz = HibernatePlugin.class;

   public static final String KEY_NAME = clazz.getName();

   public void setPath(String path) {
      this.path = path;
   }

   public void init(ActionServlet servlet, ModuleConfig modConfig)
      throws ServletException {

      try {

    	 //save the Hibernate session factory into serlvet context
         URL url = HibernatePlugin.class.getResource(path);
         config = new Configuration().configure(url);
         factory = config.buildSessionFactory();
         servlet.getServletContext().setAttribute(KEY_NAME, factory);

      } catch (MappingException e) {
         throw new ServletException();
      } catch (HibernateException e) {
         throw new ServletException();
      }

   }

   public void destroy() {
      try {
         factory.close();
      } catch (HibernateException e) {
         e.printStackTrace();
      }
   }
} 

2.struts-config.xml

Hibernate Struts 插件包含到 Struts 配置文件( struts-config.xml )中。

 <struts-config>
    ...
    <plug-in className="com.mkyong.common.plugin.HibernatePlugin">
      	<set-property property="path" value="/hibernate.cfg.xml"/>
    </plug-in>
	...
<struts-config> 

3.获取 Hibernate 会话工厂

在 Struts action 类中,可以从 servlet 上下文中获得 Hibernate 会话工厂。

 servlet.getServletContext().getAttribute(HibernatePlugin.KEY_NAME); 

并像平常一样执行任何休眠任务。

 package com.mkyong.customer.action;

import java.util.Date;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.hibernate.Session;
import org.hibernate.SessionFactory;

import com.mkyong.common.plugin.HibernatePlugin;
import com.mkyong.customer.form.CustomerForm;
import com.mkyong.customer.model.Customer;

public class AddCustomerAction extends Action{

  public ActionForward execute(ActionMapping mapping,ActionForm form,
	HttpServletRequest request,HttpServletResponse response) 
  throws Exception {

        SessionFactory sessionFactory = 
	         (SessionFactory) servlet.getServletContext()
                            .getAttribute(HibernatePlugin.KEY_NAME);

	Session session = sessionFactory.openSession();

	CustomerForm customerForm = (CustomerForm)form;
	Customer customer = new Customer();

	//copy customerform to model
	BeanUtils.copyProperties(customer, customerForm);

	//save it
	customer.setCreatedDate(new Date());

	session.beginTransaction();
	session.save(customer);
	session.getTransaction().commit();

	return mapping.findForward("success");

  }
} 

完成了。

hibernate integration struts

Struts 复选框示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-htmlcheckbox-checkbox-example/

Download this Struts check box example – Struts-CheckBox-Example.zip

在这个 Struts 示例中,您将学习如何创建一个带有 StrutsHTML:checkbox标签的 HTML 复选框输入字段

1.文件夹结构

这是 Maven 创建的最终项目结构。请创建相应的文件夹。

## 2.动作类

创建一个 Action 类,除了转发请求什么也不做。

HtmlCheckBoxAction.java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class HtmlCheckBoxAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		return mapping.findForward("success");
	}

} 

3.属性文件

创建一个属性文件,并声明错误和标签消息。

公共属性

 #error message
error.common.html.checkbox.required = Please tick the checkbox.

#label message
label.common.html.checkbox.name = CheckBox
label.common.html.checkbox.button.submit = Submit
label.common.html.checkbox.button.reset = Reset 

4.动作形式

创建一个 ActionForm,接受一个复选框值。

HtmlCheckBoxForm.java

 package com.mkyong.common.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class HtmlCheckBoxForm extends ActionForm{

	String checkboxValue;

	public String getCheckboxValue() {
		return checkboxValue;
	}

	public void setCheckboxValue(String checkboxValue) {
		this.checkboxValue = checkboxValue;
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
			HttpServletRequest request) {

	    ActionErrors errors = new ActionErrors();

	    if( getCheckboxValue() == null || ("".equals(getCheckboxValue()))) {
	       errors.add("common.checkbox.err",
	    	  new ActionMessage("error.common.html.checkbox.required"));
	    }

	    return errors;
	}

	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		// reset properties
		checkboxValue = "";
	}

} 

5.JSP 页面

使用 Struts 的 html 标签 < html:checkbox > 创建一个 HTML 复选框输入字段。

checkbox.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

Struts html:复选框示例

:

显示复选框值。

display.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

复选框值:

6.struts-config.xml

创建一个 Struts 配置文件,并将它们链接在一起。

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		<form-bean
			name="htmlCheckBoxForm"
			type="com.mkyong.common.form.HtmlCheckBoxForm"/>

	</form-beans>

	<action-mappings>

	        <action
			path="/CheckBoxPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/checkbox.jsp"/>

		<action
			path="/CheckBox"
			type="com.mkyong.common.action.HtmlCheckBoxAction"
			name="htmlCheckBoxForm"
			validate="true"
			input="/pages/checkbox.jsp"
			>	

			<forward name="success" path="/pages/display.jsp"/>
		</action>

	</action-mappings>

	<message-resources
		parameter="com.mkyong.common.properties.Common" />

</struts-config> 

7.web.xml

最后一步,为 Strut 框架集成创建一个 web.xml。

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

<web-app>
  <display-name>Maven Struts Examples</display-name>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app> 

访问它

http://localhost:8080/struts example/checkbox page . do

勾选复选框并按下提交按钮,它将转发到

http://localhost:8080/struts example/checkbox . do

如果复选框被选中,则值为“开”,否则为空值。

checkbox struts

Struts 单选选项示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-htmlradio-radio-option-example/

Download this Struts radio option example – Struts-Radio-Example.zip

在这个 Struts 示例中,您将学习如何使用 Struts 标记创建 HTML 单选选项。

1.文件夹结构

这是 Maven 创建的最终项目结构。请创建相应的文件夹。

Struts-radio-folder ## 2.动作类

创建一个 Action 类,除了转发请求什么也不做。

HtmlRadioAction.java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mkyong.common.form.HtmlRadioForm;

public class HtmlRadioAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		HtmlRadioForm htmlRadioForm = (HtmlRadioForm)form;

		return mapping.findForward("success");
	}

} 

3.属性文件

创建一个属性文件,并声明错误和标签消息。

公共属性

 #error message
error.common.html.radio.required = Please select a radio option.

#label message
label.common.html.radio.name = Select Sex
label.common.html.radio.sex.male = Male
label.common.html.radio.sex.female = Female
label.common.html.radio.button.submit = Submit
label.common.html.radio.button.reset = Reset 

4.动作形式

创建一个 ActionForm,包含单选选项和表单验证的性别变量–validate()。

HtmlRadioForm.java

 package com.mkyong.common.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class HtmlRadioForm extends ActionForm{

	String sex;

	public String getSex() {
		return sex;
	}

	public void setSex(String sex) {
		this.sex = sex;
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
		HttpServletRequest request) {

	    ActionErrors errors = new ActionErrors();

	    if( getSex() == null || ("".equals(getSex())))
	    {
	       errors.add("common.radio.err",
	    	  new ActionMessage("error.common.html.radio.required"));
	    }

	    return errors;
	}

	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		// reset properties
		sex = "";
	}
} 

5.JSP 页面

使用 Struts 的 HTML 标签创建一个 HTML 单选按钮。

radio.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

Struts html:单选示例

:

从 htmlRadioForm 表单中获取单选按钮值并显示它

display.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

您选择的值是:

6.struts-config.xml

创建一个 Struts 配置文件,并将它们链接在一起。

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		<form-bean
			name="htmlRadioForm"
			type="com.mkyong.common.form.HtmlRadioForm"/>

	</form-beans>

	<action-mappings>

	        <action
			path="/RadioPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/radio.jsp"/>

		<action
			path="/Radio"
			type="com.mkyong.common.action.HtmlRadioAction"
			name="htmlRadioForm"
			validate="true"
			input="/pages/radio.jsp"
			>	

			<forward name="success" path="/pages/display.jsp"/>
		</action>
	</action-mappings>

	<message-resources
		parameter="com.mkyong.common.properties.Common" />

</struts-config> 

7.web.xml

最后一步,创建一个 web.xml 并集成 Struts 框架。

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

<web-app>
  <display-name>Maven Struts Examples</display-name>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app> 

访问它

http://localhost:8080/struts example/radio page . do

Struts-radio-example1

选择一个性别并按下提交按钮,它将转发到

http://localhost:8080/struts example/radio . do

并显示选择单选选项。

radio button struts

Struts 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-htmlrewrite-example/

Struts < html:rewrite >

例如

1.Css 文件

Struts 重写以在 HTML 页面中包含一个 CSS 文件。

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

它将转换成下面的 HTML 代码。

2.Javascript 文件

Struts 重写以在 HTML 页面中包含一个 Javascript 文件。

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

它将被转换成下面的 HTML 代码。

“StrutsExample”是 Struts 项目的根文件夹。

参考

http://struts . Apache . org/1 . x/struts-taglib/TLD doc/html/rewrite . html

struts

Struts

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-htmlselect-drop-down-box-example/

Download this Struts select option (drop down box) example – Struts-Select-Option-Example.zip

在这个 Struts 示例中,您将学习如何用 Struts <select><option>标签创建一个 HTML 选择选项(下拉框)。<select>标签用于创建一个选择列表(下拉列表);而 select 元素中的<option>标签定义了列表中的可用选项。

1.文件夹结构

这是 Maven 创建的最终项目结构。请创建相应的文件夹。

Struts-select-option-folder ## 2.动作类

创建一个 Action 类,除了转发请求什么也不做。

html 选择选项 Action.java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mkyong.common.form.HtmlSelectOptionForm;

public class HtmlSelectOptionAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

	  HtmlSelectOptionForm htmlSelectOptionForm = (HtmlSelectOptionForm)form;

	  return mapping.findForward("success");
	}

} 

3.属性文件

创建一个属性文件,并声明错误和标签消息。

公共属性

 #error message
error.common.html.select.required = Please select a year.

#label message
label.common.html.select.name = Select a year 
label.common.html.select.button.submit = Submit
label.common.html.select.button.reset = Reset 

4.动作形式

创建一个 ActionForm,包含一个 year 变量来保存选择选项值。

HtmlSelectOptionForm.java

 package com.mkyong.common.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class HtmlSelectOptionForm extends ActionForm{

	String year;

	public String getYear() {
		return year;
	}

	public void setYear(String year) {
		this.year = year;
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
	  HttpServletRequest request) {

	    ActionErrors errors = new ActionErrors();

	    if( getYear() == null || ("".equals(getYear())))
	    {
	       errors.add("common.select.err",
	    	 new ActionMessage("error.common.html.select.required"));
	    }

	    return errors;
	}

	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		// reset properties
		year = "";
	}

} 

5.JSP 页面

使用 Struts 的 HTML 标签

select.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

Struts html:选择示例

:

从 htmlSelectOptionForm 表单中获取选定的下拉框值并显示它

display.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

您选择的年份是:

6.struts-config.xml

创建一个 Struts 配置文件,并将它们链接在一起。

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		<form-bean
			name="htmlSelectOptionForm"
			type="com.mkyong.common.form.HtmlSelectOptionForm"/>

	</form-beans>

	<action-mappings>

	        <action
			path="/SelectPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/select.jsp"/>

		<action
			path="/Select"
			type="com.mkyong.common.action.HtmlSelectOptionAction"
			name="htmlSelectOptionForm"
			validate="true"
			input="/pages/select.jsp"
			>	

			<forward name="success" path="/pages/display.jsp"/>
		</action>
	</action-mappings>

	<message-resources
		parameter="com.mkyong.common.properties.Common" />

</struts-config> 

7.web.xml

最后一步,创建一个 web.xml 并集成 Struts 框架。

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

<web-app>
  <display-name>Maven Struts Examples</display-name>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app> 

访问它

http://localhost:8080/struts example/select page . do

Struts-select-option-example1

选择一年并按下提交按钮,它将转发到

http://localhost:8080/struts example/select . do

并显示选定的下拉框值。

Struts-select-option-example2dropdown struts

Struts 文本框示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-htmltext-textbox-example/

Download this Struts text box example – Struts-TextBox-Example.zip

在这个 Struts 示例中,您将学习如何使用 Struts < html:text > 标签创建 HTML 文本框输入字段,使用 ActionForm 验证文本框,使用 ActionErrors 显示错误消息,以及 JSP 页面中的消息资源。

1.文件夹结构

这是 Maven 创建的最终项目结构。请创建相应的文件夹。

Struts-text-box-folder ## 2.动作类

创建一个 Action 类,除了转发请求什么也不做。

user action . Java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class UserAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		return mapping.findForward("success");
	}

} 

3.属性文件

创建一个属性文件,并声明错误和标签消息。

公共属性

 #common module error message
error.common.name.required = Name is required.

#common module label message
label.common.name = UserName
label.common.button.submit = Submit
label.common.button.reset = Reset 

4.动作形式

创建一个 ActionForm,接受一个用户名并在 validate()方法中验证它。如果用户名为空,从上面的属性文件中获取一条错误消息,并将其作为关键字“ common.name.err 添加到 ActionErrors 中,稍后将使用这个名称“ common.name.err 在 JSP 中显示错误消息。

UserForm.java

 package com.mkyong.common.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class UserForm extends ActionForm{

	String username;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
	HttpServletRequest request) {

	   ActionErrors errors = new ActionErrors();

	    if( getUsername() == null || ("".equals(getUsername()))) {
	       errors.add("common.name.err",
                         new ActionMessage("error.common.name.required"));
	    }

	    return errors;
	}

	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		// reset properties
		username = "";
	}

} 

5.JSP 页面

使用 Struts 的 html 标签 < html:text > 创建一个 HTML 文本框输入字段。标签消息在上述属性文件中声明,您可以直接通过<bean:message key = " label _ name "/>获取。

错误信息可以以两种方式显示:

  1. 显示所有错误信息
  2. 通过指定在 ActionErrors 中声明的错误消息键来显示指定的错误消息。

login.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

Struts html:文本示例

:

显示文本框输入。
welcome.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

欢迎光临

6.struts-config.xml

创建一个 Struts 配置文件,并将它们链接在一起。

在动作标签属性中:

  • path =您访问的 web 路径
  • type =您的操作类
  • name =您的行动表
  • validate = true 将导致 ActionForm 使用 validate()方法进行表单验证
  • input =如果验证为假,将转发到哪里?

您必须在 struts-config.xml 文件中包含您的属性文件,以使 struts 知道您的定制资源消息。

 <message-resources
	parameter="com.mkyong.common.properties.Common" /> 
 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		<form-bean
			name="userForm"
			type="com.mkyong.common.form.UserForm"/>

	</form-beans>

	<action-mappings>

	    <action
			path="/LoginPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/login.jsp"/>

		<action
			path="/Login"
			type="com.mkyong.common.action.UserAction"
			name="userForm"
			validate="true"
			input="/pages/login.jsp"
			>	

			<forward name="success" path="/pages/welcome.jsp"/>
		</action>
	</action-mappings>

	<message-resources
		parameter="com.mkyong.common.properties.Common" />

</struts-config> 

7.web.xml

最后一步,为 Strut 框架集成创建一个 web.xml。

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

<web-app>
  <display-name>Maven Struts Examples</display-name>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app> 

访问它

http://localhost:8080/struts example/log in page . do

Struts-text-box-example1

如果用户没有填写文本框并按下提交按钮,它将显示一条错误消息。

Struts-text-box-example2

如果用户填写文本框并按提交按钮。

Struts-text-box-example3

它会将文本框输入值传递给欢迎页面并显示出来。

Struts-text-box-example4struts textbox

Struts 国际化或本地化示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-internationalizing-or-localization-example/

这是一个 Struts 本地化示例,根据指定的语言显示消息或内容。默认情况下,Struts 将为每个用户在其会话上下文中存储一个 Locale 属性,该属性位于关键字"org . Apache . Struts . action . Locale"下,您所需要做的就是使用这个会话属性。

Download this Struts localization example – Struts-Localization-Example.zip

1.项目结构

这是项目结构。

Struts-localization-folder

2.属性文件

所有本地化消息都在属性文件中声明,格式为“filename _ locale _ code . properties”。你可以在 Java 中查看地区代码。Util.Locale 类。例如

  • 英语–Common . properties 或 Common_en_US.properties
  • 中文–Common _ zh _ cn . properties
  • 法国–Common _ fr .属性
  • 德语–Common _ de .属性

公共属性

 #error message
error.common.username.required = Username is required
error.common.password.required = Password is required

#label message
label.common.message = localization example
label.common.username = Username 
label.common.password = Password
label.common.button.submit = Submit 

公共属性

 #error message
error.common.username.required = Benutzername ist erforderlich
error.common.password.required = Passwort ist erforderlich

#label message
label.common.message = Lokalisierung Beispiel
label.common.username = Benutzername 
label.common.password = Kennwort
label.common.button.submit = Einreichen 

3.动作类

创建一个 action 类,该类扩展 DispatchAction 以实现多种操作目的。

 package com.mkyong.common.action;

import java.util.Locale;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.Globals;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.DispatchAction;

public class LanguageSelectAction extends DispatchAction{

	public ActionForward chinese(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {

		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.SIMPLIFIED_CHINESE);

		return mapping.findForward("success");
	}

	public ActionForward english(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {

		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.ENGLISH);

		return mapping.findForward("success");
	}

	public ActionForward german(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {

		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.GERMAN);

		return mapping.findForward("success");
	}

	public ActionForward france(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {

		request.getSession().setAttribute(
				Globals.LOCALE_KEY, Locale.FRANCE);

		return mapping.findForward("success");
	}

} 

4.动作形式

创建一个动作表单来保存用户名和密码数据,并用于表单验证。

 package com.mkyong.common.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class UserForm extends ActionForm{

	String username;
	String password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
		HttpServletRequest request) {

	    ActionErrors errors = new ActionErrors();

	    if( getUsername() == null || ("".equals(getUsername())))
	    {
	       errors.add("common.username.err",
	    	new ActionMessage("error.common.username.required"));
	    }

	    if( getPassword() == null || ("".equals(getPassword())))
	    {
	       errors.add("common.password.err",
	    	new ActionMessage("error.common.password.required"));
	    }

	    return errors;
	}

	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		// reset properties
		username = "";
		password = "";
	}
} 

5.JSP

创建一个 JSP 页面来显示语言选择、表单值以及错误消息。" /Locale.do?method=chinese 将匹配 DispatchAction chinese() 方法。

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

<message key="label.common.message"></message>

Chinese
English
German
France

: :

6.struts-config.xml

把这些放在一起。

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>
		<form-bean
			name="userForm"
			type="com.mkyong.common.form.UserForm"/>

	</form-beans>

	<action-mappings>

		<action
			path="/LoginPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/multi-language.jsp"/>

		<action
			path="/Submit"
			type="com.mkyong.common.action.LanguageSelectAction"
			name="userForm"
			validate="true"
			input="/pages/multi-language.jsp"
			>
			<forward name="success" path="/pages/multi-language.jsp"/>
		</action>

		<action
			path="/Locale"
			type="com.mkyong.common.action.LanguageSelectAction"
			name="userForm"
			parameter="method"
			validate="false"
			>
			<forward name="success" path="/pages/multi-language.jsp"/>
		</action>

	</action-mappings>

	<message-resources
		parameter="com.mkyong.common.properties.Common" />

</struts-config> 

7 .好的. xml

将 Struts 框架集成到 web 部署描述符文件中。

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

<web-app>
  <display-name>Maven Struts Examples</display-name>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app> 

屏幕截图

http://localhost:8080/struts example/log in page . do

您可以通过语言链接更改界面。

英文界面

Struts-localization-english

中文界面

Struts-localization-chinese

法国界面

Struts-localization-france

德语界面

Struts-localization-germanTags : multiple languages struts

Struts + Log4j 集成示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-log4j-integration-example/

struts 1 and log4j

在本教程中,我们将向您展示如何将 log4j 框架与传统的 Struts 1.3.x web 应用程序集成。没有额外的工作,只需包含log4j.jar并创建一个log4j.xmllog4j.properties文件,并将其放入类路径的根目录(对于 Maven,将其放入 resources 文件夹)。

使用的技术和工具:

  1. Log4j 1.2.17
  2. Struts 1.3.10
  3. maven3
  4. tomcat6
  5. 日食开普勒 4.3

1.项目目录

审查最终的项目结构。

struts1-log4j-directory

2.项目相关性

声明 Struts 和 log4j 依赖关系:

pom.xml

 <properties>
		<struts.version>1.3.10</struts.version>
		<log4j.version>1.2.17</log4j.version>
	</properties>

	<dependencies>

		<!-- Struts 1.x -->
		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts-core</artifactId>
			<version>${struts.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts-taglib</artifactId>
			<version>${struts.version}</version>
		</dependency>

		<dependency>
			<groupId>org.apache.struts</groupId>
			<artifactId>struts-extras</artifactId>
			<version>${struts.version}</version>
		</dependency>

		<!-- Log4j -->
		<dependency>
			<groupId>log4j</groupId>
			<artifactId>log4j</artifactId>
			<version>${log4j.version}</version>
		</dependency>

		<!-- Need this for web -->
		<dependency>
			<groupId>javax.servlet</groupId>
			<artifactId>servlet-api</artifactId>
			<version>2.5</version>
		</dependency>
	</dependencies> 

3.log4j.xml

创建一个 log4j XML 文件,放入resources文件夹,参考步骤#1。它告诉 log4j 将日志消息重定向到控制台和一个文件。

log4j.xml

 <?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">
<log4j:configuration debug="true"
  xmlns:log4j='http://jakarta.apache.org/log4j/'>

  <!-- Console -->
  <appender name="console" class="org.apache.log4j.ConsoleAppender">
	<layout class="org.apache.log4j.PatternLayout">
	    <param name="ConversionPattern" 
               value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
	</layout>
  </appender>

  <!-- file  -->
  <appender name="file" class="org.apache.log4j.RollingFileAppender">
	<param name="append" value="false" />
	<param name="maxFileSize" value="10KB" />
	<param name="maxBackupIndex" value="5" />
	<param name="file" value="${catalina.home}/logs/myStruts1App.log" />
	<layout class="org.apache.log4j.PatternLayout">
	    <param name="ConversionPattern" 
                value="%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n" />
	</layout>
  </appender>

  <root>
	<level value="DEBUG" />
	<appender-ref ref="console" />
	<appender-ref ref="file" />
  </root>
</log4j:configuration> 

4.消息记录

一个返回页面的简单操作,并向您展示了如何使用 log4j 进行日志记录。

WelcomeAction.java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.log4j.Logger;
import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class WelcomeAction extends Action{

	//Get a logger
	private static final Logger logger = Logger.getLogger(WelcomeAction.class);

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		//logs debug
		if(logger.isDebugEnabled()){
			logger.debug("WelcomeAction.execute()");
		}

		//logs exception
		logger.error("This is Error message", new Exception("Testing"));

	    return mapping.findForward("success");

	}

} 

5.Struts 1 配置

简单的 Struts 1 配置等。

web.xml

 <web-app  
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
	  http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	version="2.5">

	<display-name>Log4j + Struts Web Application</display-name>

	<servlet>
		<servlet-name>action</servlet-name>
		<servlet-class>
			org.apache.struts.action.ActionServlet
		</servlet-class>
		<init-param>
			<param-name>config</param-name>
			<param-value>
				/WEB-INF/struts-config.xml
			</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>

	</servlet>

	<servlet-mapping>
		<servlet-name>action</servlet-name>
		<url-pattern>*.do</url-pattern>
	</servlet-mapping>

</web-app> 

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

		<action
			path="/welcome"
			type="com.mkyong.common.action.WelcomeAction"
			>	

			<forward name="success" path="/pages/welcome.jsp"/>

		</action>
	</action-mappings>

</struts-config> 

pages/welcome.jsp

 <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<html>
<head>
</head>
<body>
<h1>
	Struts 1.x + Log4j framework
</h1>
</body>
</html> 

6.演示

运行 Struts 1 web 应用程序,并访问欢迎操作。

网址:http://localhost:8080/log 4 jandstruts 1/welcome . do

struts1-log4j-demo

6.1 Eclipse 控制台。

struts1-log4j-console

6.2 此外,将在 Tomcat 的 logs 文件夹中创建一个日志文件。

struts1-log4j-file

图:D:\ Apache-Tomcat-6 . 0 . 37 \ logs \ mystruts 1 app . log

下载源代码

Download it – Log4jAndStrutsExample.zip (11 KB)

参考

  1. log4j 1.2 官方页面
  2. log4j hello world 示例
  3. Struts 2 异常和日志记录

struts-&示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-logic-empty-logic-notempty-example/

Download this example – Struts-Logic-Empty-NotEmpty-Example.zip

Struts 仅在指定属性为空、零长度字符串或不存在时执行;而 Struts 正在做相反的事情。如果条件匹配,标签的主体将被执行。

下面的例子展示了 Struts & 的使用,并用下面的三个列表进行测试。

  1. list msg 0–包含值的列表。
  2. list msg 1–空列表。
  3. list msg 2–一个不存在的列表

LogicExampleAction.java

 package com.mkyong.common.action;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LogicExampleAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		//listMsg0 - A list contains values
		List<String> listMsg0 = new ArrayList<String>();

		listMsg0.add("Message A");
		listMsg0.add("Message B");
		listMsg0.add("Message C");
		listMsg0.add("Message D");

		request.setAttribute("listMsg0", listMsg0);

		//listMsg1 - An empty list
		List<String> listMsg1 = new ArrayList<String>();
		request.setAttribute("listMsg1", listMsg1);

                //listMsg2 - A list which is doesn't exists

		return mapping.findForward("success");
	}

} 

LogicExample.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>

Struts -测试

 ## listMag0 为空 

 ## listMag1 为空 

 ## listMag2 为空 

Struts -测试

 ## listMag0 不为空

	 <iterate name="listMsg0" id="listMsgId">列出消息 0 -</iterate> 

 ## listMag1 不为空

	 <iterate name="listMsg1" id="listMsgId">列出消息 1 -</iterate> 

 ## listMag2 不为空

	 <iterate name="listMsg2" id="listMsgId">列出消息 2 -</iterate> 

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>
  <action-mappings>

	 <action
		path="/LogicTest"
		type="com.mkyong.common.action.LogicExampleAction">

		<forward name="success" path="/pages/LogicExample.jsp"/>

	</action>

  </action-mappings>
</struts-config> 

结果

http://localhost:8080/struts example/logictest . do

Struts-logic-empty-notempty-example

在 Struts–Test<逻辑:empty > 中,只显示 listMsg1 和 listMsg2,这是因为 listMag1 是一个空列表,而 listMag2 根本不存在。

在 Struts–Test<逻辑中:notEmpty > ,只显示 listMsg0,因为这是唯一包含值的列表。

struts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190213170100/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

struts-&示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-logic-equal-logicnotequal-example/

Download this example – Struts-Logic-Equal-NotEqual-Example.zip

Struts 用于检查给定属性是否等于给定值;而 Struts 用于检查给定属性是否等于给定值,如果条件匹配,标签的主体将被执行。

下面的例子展示了 Struts & 的用法。

User.java

 package com.mkyong.common;

public class User{

	String email;

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

} 

LogicExampleAction.java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mkyong.common.User;

public class LogicExampleAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		User user = new User();
		user.setEmail("mkyong123456@yahoo.com");

		request.setAttribute("user", user);

		return mapping.findForward("success");
	}

} 

LogicExample.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>

Struts -测试<equal></equal>

 ## 用户的电子邮件是平等的 

 ## Struts -测试<notequal></notequal>

 <notequal name="user" property="email" value="mkyong654321@yahoo.com">## 用户的电子邮件不相等</notequal> 

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>
  <action-mappings>

	 <action
		path="/LogicTest"
		type="com.mkyong.common.action.LogicExampleAction">

		<forward name="success" path="/pages/LogicExample.jsp"/>

	</action>

  </action-mappings>
</struts-config> 

结果

http://localhost:8080/struts example/logictest . do

Struts-logic-equal-notequal-examplestruts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190224164320/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

Struts 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-logic-iterate-example/

在 Struts 中,可以使用 <逻辑:iterate > 标签迭代集合。这里有两个例子:

  1. 遍历列表(原始类型)
  2. 遍历列表(对象)

1.迭代列表数组(原始类型)

用一些虚拟字符串创建一个普通列表,并存储到HttpServletRequest,命名为“ listMsg ”。

 ...
public class PrintMsgAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		List<String> listMsg = new ArrayList<String>();

		listMsg.add("Message A");
		listMsg.add("Message B");
		listMsg.add("Message C");
		listMsg.add("Message D");

		request.setAttribute("listMsg", listMsg);

		return mapping.findForward("success");
	}

} 

在逻辑标记中,可以使用“name”属性(listMsg)来获取列表值。

 <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<html>
<head>
</head>
<body>
<h1>Struts <logic:iterate> example</h1>

<logic:iterate name="listMsg" id="listMsgId">
<p>
	List Messages <bean:write name="listMsgId"/>
</p>
</logic:iterate>

</body>
</html> 

2.遍历列表数组(对象)

创建一个包含少量“用户”对象的普通列表,并将其存储到HttpServletRequest中,命名为“列表用户”。

 public class User{

	String username;
	String url;

    //getter and setter methods
} 
 ... 
public class PrintMsgAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		List<User> listUsers = new ArrayList<User>();

		listUsers.add(new User("user1", "http://www.user1.com"));
		listUsers.add(new User("user2", "http://www.user2.com"));
		listUsers.add(new User("user3", "http://www.user3.com"));
		listUsers.add(new User("user4", "http://www.user4.com"));

		request.setAttribute("listUsers", listUsers);

		return mapping.findForward("success");
	}

} 

在逻辑标签内部,可以使用“ name ”属性(listUsers)来获取列表值;而属性属性则显示对象属性值。

 <%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<html>
<head>
</head>
<body>
<h1>Struts <logic:iterate> example</h1>

<logic:iterate name="listUsers" id="listUserId">
<p>
	List Users <bean:write name="listUserId" property="username"/> , 
	<bean:write name="listUserId" property="url"/>
</p>
</logic:iterate>

</body>
</html> 

struts-logic-iterate-example ## 下载源代码

Download it – Struts-logic-Iterate-example.zipstruts

struts-示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-logic-messages-present-logic-messages-notpresent-example/

Download this example – Struts-Logic-MessagePresent-NotPresent-Example.zip

Struts 标签用于检查当前请求上存在的给定消息或错误消息。

  • “消息”是全局键下的操作消息。当前请求中的 MESSAGE_KEY。
  • “错误消息”是 ActionErrors,在关键字 Globals 下。当前请求中的 ERROR_KEY。

这里有几个例子来展示的用法。

  1. 如果有任何错误消息或消息存在于关键字“Globals”下。ERROR_KEY "或" Globals。MESSAGE_KEY”,标签的主体将被执行。

     There are errors on this page! 
     There are no errors on this page! 
    
    
  2. 如果在关键字“Globals”下存在任何错误消息或名为“common.email.err”的消息。ERROR_KEY”,标签的主体将被执行。

     Email address has error messages! Globals.ERROR_KEY 
     Email address has no error messages! - Globals.ERROR_KEY 
    
    
  3. 如果在关键字“Globals”下存在任何错误消息或名为“common.email.err”的消息。MESSAGE_KEY”,标签的主体将被执行。

     Email address has error messages! - Globals.MESSAGE_KEY 
     Email address has no error messages! - Globals.MESSAGE_KEY 
    
    

LogicExampleAction.java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LogicExampleAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		//do nothing

	    return mapping.findForward("success");
	}

} 

EmailForm.java–返回错误消息的动作表单–动作错误。

 package com.mkyong.common.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class EmailForm extends ActionForm{

	String email; 

	public String getEmail() {
		return email;
	}

	public void setEmail(String email) {
		this.email = email;
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
	HttpServletRequest request) {

	   ActionErrors errors = new ActionErrors();

	   errors.add("common.email.err",
		new ActionMessage("error.common.email.required"));

	   return errors;

	}
} 

公共属性

 #common module error message
error.common.email.required = Email is required. 

LogicExample.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>

Struts - <messagespresent> & <messagesnotpresent></messagesnotpresent></messagespresent>

 There are errors on this page! 
 There are no errors on this page! 

 Email address has error messages! Globals.ERROR_KEY 
 Email address has no error messages! - Globals.ERROR_KEY 

 Email address has error messages! - Globals.MESSAGE_KEY 
 Email address has no error messages! - Globals.MESSAGE_KEY 

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<form-beans>

		<form-bean name="emailForm" 
			type="com.mkyong.common.form.EmailForm"></form-bean>

	</form-beans>

	<action-mappings>

	 	<action
			path="/LogicTest"
			type="com.mkyong.common.action.LogicExampleAction"
			name="emailForm"
			validate="true"
			input="/pages/LogicExample.jsp"
			>

			<forward name="success" path="/pages/LogicExample.jsp"/>

		</action>

	</action-mappings>

	<message-resources
		parameter="com.mkyong.common.Common" />

</struts-config> 

结果

http://localhost:8080/struts example/logictest . do

Struts-logic-messages-present-notpresent-example

 Struts - <logic:messagesPresent> & <logic:messagesNotPresent>
There are errors on this page!

Email address has error messages! Globals.ERROR_KEY

Email address has no error messages! - Globals.MESSAGE_KEY 

struts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190209023138/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

struts-示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-logic-present-logic-notpresent-example/

Download this example – Struts-Logic-Present-NotPresent-Example.zip

Struts 标签用于检查给定的对象或属性是否存在或存在于当前请求中;而则反其道而行。

这里有一个例子来展示的用法。

User.java–一个用户类包含一个 url 属性。

 package com.mkyong.common;

public class User{

	String url;

	public String getUrl() {
		return url;
	}

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

LogicExampleAction.java–初始化用户对象,设置 url 属性,并将其存储到请求会话中。

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mkyong.common.User;

public class LogicExampleAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		User user = new User();
		user.setUrl("http://www.mkyong.com");

		request.setAttribute("user", user);

	    return mapping.findForward("success");
	}

} 

LogicExample.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>

Struts - <present>&</present> 

 User object is exists. 
 User object does not exists. 

 Abc object is exists. 
 Abc object does not exists. 

 User object, url property is exists. 
 User object, url property does not exists. 

 User object, email property is exists. 
 User object, email property does not exists. 

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

	 	<action
			path="/LogicTest"
			type="com.mkyong.common.action.LogicExampleAction"
			>

			<forward name="success" path="/pages/LogicExample.jsp"/>

		</action>

	</action-mappings>

</struts-config> 

结果

http://localhost:8080/struts example/logictest . do

Struts-logic-present-notpresent-example

 Struts - <logic:present> & <logic:notPresent>
User object is exists.

Abc object does not exists.

User object, url property is exists.

User object, email property does not exists. 

struts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190224153322/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

struts-示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-logicgreaterthan-logicgreaterequal-logiclessthan-logiclessequal-example/

Download this example – Struts-Logic-Number-Condition-Tag-Example.zip

在 Struts 中,有四个数字条件标签可用…

  1. –检查给定属性是否大于给定值。
  2. –检查给定属性是否大于或等于给定值。
  3. –检查给定属性是否小于给定值。
  4. –检查给定属性是否小于或等于给定值。

如果条件匹配,标签的主体将被执行。

下面的例子展示了 Struts 的用法。

LogicExampleAction.java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LogicExampleAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		request.setAttribute("number", 100);

		return mapping.findForward("success");
	}

} 

LogicExample.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>

Struts - <greaterthan></greaterthan>

 ## 数字 100 > 99 =真 

 ## Struts - <greaterequal></greaterequal>

 <greaterequal name="number" value="100">## 数字 100 >= 100 =真</greaterequal> 

## Struts - <lessthan></lessthan>

 <lessthan name="number" value="101">## 数字 100 < 101 =真</lessthan> 

## Struts - <lessequal></lessequal>

 <lessequal name="number" value="100">## 数字 100 <= 100 =真</lessequal> 

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>
  <action-mappings>

	 <action
		path="/LogicTest"
		type="com.mkyong.common.action.LogicExampleAction">

		<forward name="success" path="/pages/LogicExample.jsp"/>

	</action>

  </action-mappings>
</struts-config> 

结果

http://localhost:8080/struts example/logictest . do

Struts-logic-number-condition-examplestruts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190209024221/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

struts-示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-logicmatch-logicnotmatch-example/

Download this example – Struts-Logic-Match-NotMatch-Example.zip

Struts 的标签用于检查给定属性包含的给定值为的子串。例如,一个属性结果“Google 搜索引擎”,值“gle”将匹配,而值“ABC”将不匹配。如果条件匹配,标签的主体将被执行。Struts <逻辑:notMatch >正在做相反的事情。

Struts 的匹配标记有一个必须知道的属性,名为" location ",值为" start 或" end

  1. location = " start "–仅当给定值作为给定属性的起始子串出现时才匹配。例如“谷歌搜索引擎”——匹配“Goog”,不匹配“gine”。
  2. location = " end "–仅当给定值作为给定属性的结束子串出现时才匹配。例如“谷歌搜索引擎”——不匹配“Goog”,匹配“gine”。
  3. 无位置定义–如果给定值作为给定属性的子串出现,则匹配。例如“谷歌搜索引擎”——匹配“Goog”,匹配“gine”。

下面的例子展示了 & 的用法。

LogicExampleAction.java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class LogicExampleAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		request.setAttribute("email", "mkyong123456@yahoo.com");

		return mapping.findForward("success");
	}

} 

LogicExample.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>

Struts - <match> & <notmatch></notmatch></match>

Email - mkyong123456@yahoo.com

1\. Is "yong" is a substring of the email? -
 true 
 false 

2\. Is "yongABC" is a substring of the email? -
 true 
 false 

3\. Is email start with "mkyong"? -
 true 
 false 

4.. Is email start with "yong"? -
 true 
 false 

5\. Is email end with "com"? -
 true 
 false 

6\. Is email end with "net"? -
 true 
 false 

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>
  <action-mappings>

	 <action
		path="/LogicTest"
		type="com.mkyong.common.action.LogicExampleAction">

		<forward name="success" path="/pages/LogicExample.jsp"/>

	</action>

  </action-mappings>
</struts-config> 

结果

http://localhost:8080/struts example/logictest . do

Struts-logic-match-notmatch-example

 Struts - <logic:match> & <logic:notMatch>
Email - mkyong123456@yahoo.com

1\. Is "yong" is a substring of the email? - true

2\. Is "yongABC" is a substring of the email? - false

3\. Is email start with "mkyong"? - true

4.. Is email start with "yong"? - false

5\. Is email end with "com"? - true

6\. Is email end with "net"? - false 

struts (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190209024038/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

struts–MappingDispatchAction 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-mappingdispatchaction-example/

Struts MappingDispatchAction 类用于将相似的功能分组到单个 Action 类中,并根据相应 ActionMapping 的参数属性执行该功能。下面的示例展示了 MappingDispatchAction 的用法。

Download this example – Struts-MappingDispatchAction-Example.zip

1.MappingDispatchAction 类

扩展 MappingDispatchAction 类,并声明两个方法—generate XML()generateExcel()

MyCustomDispatchAction.java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.actions.MappingDispatchAction;

public class MyCustomDispatchAction extends MappingDispatchAction{

	public ActionForward generateXML(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

		request.setAttribute("method", "generateXML is called");

	        return mapping.findForward("success");
	}

	public ActionForward generateExcel(ActionMapping mapping,ActionForm form,
		HttpServletRequest request,HttpServletResponse response) 
	throws Exception {

		request.setAttribute("method", "generateExcel is called");

		return mapping.findForward("success");
	}
} 

2.Struts 配置

声明两个操作映射,每个映射指向具有不同参数属性的同一个 MyCustomDispatchAction 类。

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

	 	<action
			path="/CustomDispatchActionXML"
			type="com.mkyong.common.action.MyCustomDispatchAction"
			parameter="generateXML"
			>

			<forward name="success" path="/pages/DispatchExample.jsp"/>

		</action>

		<action
			path="/CustomDispatchActionExcel"
			type="com.mkyong.common.action.MyCustomDispatchAction"
			parameter="generateExcel"
			>

			<forward name="success" path="/pages/DispatchExample.jsp"/>

		</action>

		<action
			path="/Test"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/TestForm.jsp"
			>
		</action>

	</action-mappings>

</struts-config> 

3.查看页面

在 JSP 页面中,链接的工作方式如下:

  1. /CustomDispatchActionXML 将执行 generateXML() 方法。
    2。/CustomDispatchActionExcel将执行 generateExcel() 方法。

TestForm.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

Struts - DispatchAction 示例

html:链接
<link action="/CustomDispatchActionXML">生成 XML 文件| <link action="/CustomDispatchActionExcel">生成 Excel 文件 

a href
[生成 XML 文件](CustomDispatchActionXML.do) | [生成 Excel 文件](CustomDispatchActionExcel.do) 

DispatchExample.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>

Struts - DispatchAction 示例

4.测试一下

http://localhost:8080/struts example/test . do

Struts-MappingDispatchAction-1-example

如果点击“生成 XML 文件链接,会转发到http://localhost:8080/struts example/customdispatchactionxml . do

Struts-MappingDispatchAction-2-xml-example

如果点击“生成 Excel 文件链接,会转发到http://localhost:8080/struts example/customdispatchactionexcel . do

Struts-MappingDispatchAction-3-excel-examplestruts

struts–多个配置文件示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-multiple-configuration-files-example/

许多开发人员喜欢将所有与 Struts 相关的东西(动作、表单)放在一个 Struts 配置文件中。这对于最初的开发来说很快,但是对于将来的维护来说却很糟糕,而且可能那些开发人员并没有意识到 Struts 允许多个配置文件的特性。

6 years ago, I had joined a large Struts development project which involve 20+ modules. Unfortunately, the prior developers put all the Struts related stuff (action, form and etc) into a single Struts configuration file (struts-config.xml). The struts-config.xml just keep growing extremely fast and finally hit 20++mb, every update to this configuration file will take few minutes, and even wait half an hour for a single debugging deployment in Eclipse IDE. This is a serious performance issue and causing the project keep delay the production date. What a good Struts development experience.

请将 Struts 配置细节拆分到不同的模块中,Struts 可以轻松完成。

Struts 多配置文件示例

这是用于演示的示例项目结构。

Struts-mutiple-configuration-file ## 1.单一模块

单个模块支持多个 Struts 配置文件。

page1.jsp


这是第一页

page2.jsp


这是第二页

struts-config-1.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

		<action
			path="/Page1"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/page1.jsp"/>

	</action-mappings>

</struts-config> 

struts-config-2.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

		<action
			path="/Page2"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/page2.jsp"/>

	</action-mappings>

</struts-config> 

在 web.xml 中,可以用逗号“”分隔多个 Struts 配置文件。
web . XML

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

<web-app>
  <display-name>Maven Struts Examples</display-name>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config-1.xml, /WEB-INF/struts-config-2.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app> 
测试一下
  1. http://localhost:8080/struts example/page 1 . do
    将显示 Page1.do
  2. http://localhost:8080/struts example/common/welcome . do
    它将显示 page2.jsp

两种 Struts 配置都是 loaded 属性。

2.多个模块

多个模块,每个模块都有自己的 Struts 配置文件。

admin/welcome.jsp


欢迎来到管理页面

common/welcome.jsp


欢迎来到公共页面

struts-config-admin.xml ”和“ struts-config-admin.xml ”两个文件包含相同的设置,struts 能够通过 web.xml 中的“ config 参数值对其进行区分

In Struts 2, the “Namespace” is a more efficient way to replace this “config parameter” setting.

struts-config-admin.xml,struts-config-admin.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

		<action
			path="/Welcome"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/welcome.jsp"/>

	</action-mappings>

</struts-config> 

web.xml

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

<web-app>
  <display-name>Maven Struts Examples</display-name>

  <servlet>
    <servlet-name>action</servlet-name>
    <servlet-class>
        org.apache.struts.action.ActionServlet
    </servlet-class>
    <init-param>
        <param-name>config</param-name>
        <param-value>
         /WEB-INF/struts-config-1.xml, /WEB-INF/struts-config-2.xml
        </param-value>
    </init-param>
    <init-param>
        <param-name>config/admin</param-name>
        <param-value>
         /WEB-INF/struts-config-admin.xml
        </param-value>
    </init-param>
    <init-param>
        <param-name>config/common</param-name>
        <param-value>
         /WEB-INF/struts-config-common.xml
        </param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>

  <servlet-mapping>
       <servlet-name>action</servlet-name>
       <url-pattern>*.do</url-pattern>
  </servlet-mapping>

</web-app> 
测试一下

config/admin ”将匹配此 URL 模式-http://localhost:8080/struts example/admin/
config/common”将匹配此 URL 模式-http://localhost:8080/struts example/common/

  1. http://localhost:8080/struts example/admin/welcome . do
    它会显示 admin/welcome.jsp
  2. http://localhost:8080/struts example/common/welcome . do
    它会显示 common/welcome.jsp

每个模块都有自己的 Struts 配置文件。

下载源代码

Download it – Struts-Mutiple-Config-File-Example.zipstruts

Struts 1 + Quartz 2 调度器集成示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-quartz-scheduler-integration-example/

在本教程中,我们将向您展示如何使用 Apache Struts 1.x 创建一个简单的 web 应用程序项目,并与 Quartz scheduler 框架集成。在项目启动期间,它将启动 Quartz 引擎并触发定义的调度程序任务。

总体思路非常简单,您只需要为集成工作创建一个 Quartz Struts 插件

 Struts <--> Quartz Struts Plug-in <--> Quartz 

使用的工具:

  1. Apache Struts 1.3.10
  2. 石英 2.1.5
  3. Eclipse IDE
  4. 专家

Note
Please visit this Quartz 2 scheduler example to learn the basic usage of the Quartz framework.

1.属国

通过 Maven 获取 Struts 和 Quartz 依赖项。

文件:pom.xml

 <dependency>
		<groupId>org.apache.tomcat</groupId>
		<artifactId>servlet-api</artifactId>
		<version>6.0.35</version>
	</dependency>

	<!-- Struts 1.3 framework -->
	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts-core</artifactId>
		<version>1.3.10</version>
	</dependency>

	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts-taglib</artifactId>
		<version>1.3.10</version>
	</dependency>

	<dependency>
		<groupId>org.apache.struts</groupId>
		<artifactId>struts-extras</artifactId>
		<version>1.3.10</version>
	</dependency>

	<!-- Quartz framework -->
	<dependency>
		<groupId>org.quartz-scheduler</groupId>
		<artifactId>quartz</artifactId>
		<version>2.1.5</version>
	</dependency> 

2.Quartz 调度程序作业

创建一个 Quartz 作业来打印消息。

文件:SchedulerJob.java

 package com.mkyong.common.quartz;

import org.quartz.Job;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;

public class SchedulerJob implements Job
{
	public void execute(JobExecutionContext context)
	throws JobExecutionException {

	   System.out.println("Print Print Struts 1.3 + Quartz 2.1.5 integration example ~");

	}
} 

3.Struts 插件

创建一个简单的 Struts 插件并集成 Quartz 框架。在这个插件中,在 Struts 初始化期间,init()方法将被调用,并每 5 秒启动一次 Quartz 调度程序作业。

文件:QuartzPlugin.java

 package com.mkyong.common.plugin;

import javax.servlet.ServletException;

import org.apache.struts.action.ActionServlet;
import org.apache.struts.action.PlugIn;
import org.apache.struts.config.ModuleConfig;
import org.quartz.CronScheduleBuilder;
import org.quartz.JobBuilder;
import org.quartz.JobDetail;
import org.quartz.Scheduler;
import org.quartz.SchedulerException;
import org.quartz.Trigger;
import org.quartz.TriggerBuilder;
import org.quartz.impl.StdSchedulerFactory;

import com.mkyong.common.quartz.SchedulerJob;

public class QuartzPlugin implements PlugIn {

	@Override
	public void destroy() {
		// null
	}

	@Override
	public void init(ActionServlet servlet, ModuleConfig config)
			throws ServletException {

		JobDetail job = JobBuilder.newJob(SchedulerJob.class)
			.withIdentity("anyJobName", "group1").build();

		try {

			Trigger trigger = TriggerBuilder
				.newTrigger()
				.withIdentity("anyTriggerName", "group1")
				.withSchedule(
					CronScheduleBuilder.cronSchedule("0/5 * * * * ?"))
				.build();

			Scheduler scheduler = new StdSchedulerFactory().getScheduler();
			scheduler.start();
			scheduler.scheduleJob(job, trigger);

		} catch (SchedulerException e) {
			e.printStackTrace();
		}

	}

} 

4.声明插件

将上面的 Struts 插件包含到 Struts 配置文件(struts-config.xml)中。

文件:struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

	   <action path="/Welcome" type="org.apache.struts.actions.ForwardAction"
		parameter="/pages/quartz_started.jsp" />

	</action-mappings>

	<plug-in className="com.mkyong.common.plugin.QuartzPlugin" />

</struts-config> 

5.演示

在 Struts 启动期间,触发 Quartz 调度程序任务。

struts and quartz 2 example

下载源代码

Download it – Struts-Quartz-2-Example.zip (24 KB)

参考

  1. 石英官网
  2. Quartz 2 调度器示例

quartz scheduler struts

Struts + Spring + Hibernate 集成示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-spring-hibernate-integration-example/

Download this Struts 1.x + Spring + Hibernate example – Struts-Spring-Hibernate-Example.zip

在本教程中,您将学习如何创建一个简单的客户管理(添加和选择)web 应用程序,Maven 作为项目管理工具,Struts 1.x 作为 web 框架,Spring 作为依赖注入框架,Hibernate 作为数据库 ORM 框架。

整体集成架构如下所示:

 Struts (Web page) <---> Spring DI <--> Hibernate (DAO) <---> Database 

要将所有这些技术集成在一起,您应该..

  1. 用 Spring 的" LocalSessionFactoryBean "类集成 Spring 和 Hibernate。
  2. 通过 Spring 的 ready make Struts 插件将 Spring 与 Struts 集成起来。

1.项目结构

这是最终的项目结构。

struts-spring-hibernate-1struts-spring-hibernate-2 ## 2.表格脚本

创建一个客户表来存储客户详细信息。

 DROP TABLE IF EXISTS `mkyong`.`customer`;
CREATE TABLE  `mkyong`.`customer` (
  `CUSTOMER_ID` bigint(20) unsigned NOT NULL AUTO_INCREMENT,
  `NAME` varchar(45) NOT NULL,
  `ADDRESS` varchar(255) NOT NULL,
  `CREATED_DATE` datetime NOT NULL,
  PRIMARY KEY (`CUSTOMER_ID`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8; 

3.Maven 详细信息

在 pom.xml.
pom.xml 中定义所有的 Struts、Spring 和 Hibernate 依赖库

 <project  
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 
  http://maven.apache.org/maven-v4_0_0.xsd">
  <modelVersion>4.0.0</modelVersion>
  <groupId>com.mkyong.common</groupId>
  <artifactId>StrutsSpringExample</artifactId>
  <packaging>war</packaging>
  <version>1.0-SNAPSHOT</version>
  <name>StrutsExample Maven Webapp</name>
  <url>http://maven.apache.org</url>

  <repositories>
  	<repository>
  		<id>Java.Net</id>
  		<url>http://download.java.net/maven/2/</url>
  	</repository>

	<repository>
		<id>JBoss repository</id>
		<url>http://repository.jboss.com/maven2/</url>
	</repository>

  </repositories>

  <dependencies>

        <!-- Spring framework --> 
	<dependency>
	  <groupId>org.springframework</groupId>
	  <artifactId>spring</artifactId>
	  <version>2.5.6</version>
	</dependency>

        <dependency>
	  <groupId>org.springframework</groupId>
	  <artifactId>spring-web</artifactId>
	  <version>2.5.6</version>
	</dependency>

	<dependency>
	  <groupId>org.springframework</groupId>
	  <artifactId>spring-struts</artifactId>
	  <version>2.0.8</version>
	</dependency>

        <!-- J2EE library -->
	<dependency>
	  <groupId>javax</groupId>
	  <artifactId>javaee-api</artifactId>
	  <version>6.0</version>
	</dependency>

        <!-- Unit Test -->
        <dependency>
          <groupId>junit</groupId>
          <artifactId>junit</artifactId>
          <version>3.8.1</version>
          <scope>test</scope>
        </dependency>

        <!-- Struts 1.3 framework -->
        <dependency>
          <groupId>org.apache.struts</groupId>
	  <artifactId>struts-core</artifactId>
          <version>1.3.10</version>
        </dependency>

        <dependency>
          <groupId>org.apache.struts</groupId>
	  <artifactId>struts-taglib</artifactId>
          <version>1.3.10</version>
        </dependency>

        <dependency>
          <groupId>org.apache.struts</groupId>
	  <artifactId>struts-extras</artifactId>
          <version>1.3.10</version>
        </dependency>

        <!-- MySQL database driver -->
	<dependency>
	  <groupId>mysql</groupId>
	  <artifactId>mysql-connector-java</artifactId>
	  <version>5.1.9</version>
	</dependency>

	<!-- Hibernate core -->
	<dependency>
	  <groupId>org.hibernate</groupId>
	  <artifactId>hibernate</artifactId>
	  <version>3.2.7.ga</version>
	</dependency>

	<!-- Hibernate core library dependecy start -->
	<dependency>
	  <groupId>dom4j</groupId>
	  <artifactId>dom4j</artifactId>
	  <version>1.6.1</version>
	</dependency>

	<dependency>
	  <groupId>commons-logging</groupId>
	  <artifactId>commons-logging</artifactId>
	  <version>1.1.1</version>
	</dependency>

	<dependency>
	  <groupId>commons-collections</groupId>
	  <artifactId>commons-collections</artifactId>
	  <version>3.2.1</version>
	</dependency>

	<dependency>
	  <groupId>cglib</groupId>
	  <artifactId>cglib</artifactId>
	  <version>2.2</version>
	</dependency>
	<!-- Hibernate core library dependecy end -->

	<!-- Hibernate query library dependecy start -->
	<dependency>
	  <groupId>antlr</groupId>
	  <artifactId>antlr</artifactId>
	  <version>2.7.7</version>
	</dependency>
	<!-- Hibernate query library dependecy end -->

  </dependencies>
  <build>
    <finalName>StrutsExample</finalName>
  </build>
</project> 

4.冬眠

在 Hibernate 中不需要太多的配置,只需要声明一个客户 XML 映射文件和模型。
Customer.hbm.xml

 <?xml version="1.0"?>
<!DOCTYPE hibernate-mapping PUBLIC 
"-//Hibernate/Hibernate Mapping DTD 3.0//EN"
"http://hibernate.sourceforge.net/hibernate-mapping-3.0.dtd">
<hibernate-mapping>
    <class name="com.mkyong.customer.model.Customer" 
        table="customer" catalog="mkyong">

        <id name="customerId" type="long">
            <column name="CUSTOMER_ID" />
            <generator class="identity" />
        </id>
        <property name="name" type="string">
            <column name="NAME" length="45" not-null="true" />
        </property>
        <property name="address" type="string">
            <column name="ADDRESS" not-null="true" />
        </property>
        <property name="createdDate" type="timestamp">
            <column name="CREATED_DATE" length="19" not-null="true" />
        </property>
    </class>
</hibernate-mapping> 

Customer.java

 package com.mkyong.customer.model;

import java.util.Date;

public class Customer implements java.io.Serializable {

	private long customerId;
	private String name;
	private String address;
	private Date createdDate;

	//getter and setter methods

} 

5.春天

Spring 的业务对象(BO)和数据访问对象(DAO)的 beans 声明。DAO 类(CustomerDaoImpl.java)是扩展 Spring 的" HibernateDaoSupport "类来方便地访问休眠功能。
customer bean . XML

 <?xml version="1.0" encoding="UTF-8"?>
<beans 
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://www.springframework.org/schema/beans 
	http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

   	<bean id="customerBo" 
                class="com.mkyong.customer.bo.impl.CustomerBoImpl" >
   		<property name="customerDao" ref="customerDao" />
   	</bean>

   	<bean id="customerDao" 
                class="com.mkyong.customer.dao.impl.CustomerDaoImpl" >
   		<property name="sessionFactory" ref="sessionFactory"></property>
   	</bean>

</beans> 

CustomerBo.java

 package com.mkyong.customer.bo;

import java.util.List;

import com.mkyong.customer.model.Customer;

public interface CustomerBo{

	void addCustomer(Customer customer);

	List<Customer> findAllCustomer();

} 

CustomerBoImpl.java

 package com.mkyong.customer.bo.impl;

import java.util.List;

import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.dao.CustomerDao;
import com.mkyong.customer.model.Customer;

public class CustomerBoImpl implements CustomerBo{

	CustomerDao customerDao;

	public void setCustomerDao(CustomerDao customerDao) {
		this.customerDao = customerDao;
	}

	public void addCustomer(Customer customer){

		customerDao.addCustomer(customer);

	}

	public List<Customer> findAllCustomer(){

		return customerDao.findAllCustomer();
	}
} 

CustomerDao.java

 package com.mkyong.customer.dao;

import java.util.List;

import com.mkyong.customer.model.Customer;

public interface CustomerDao{

	void addCustomer(Customer customer);

	List<Customer> findAllCustomer();

} 

CustomerDaoImpl.java

 package com.mkyong.customer.dao.impl;

import java.util.Date;
import java.util.List;

import com.mkyong.customer.dao.CustomerDao;
import com.mkyong.customer.model.Customer;
import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

public class CustomerDaoImpl extends 
       HibernateDaoSupport implements CustomerDao{

	public void addCustomer(Customer customer){

		customer.setCreatedDate(new Date());
		getHibernateTemplate().save(customer);

	}

	public List<Customer> findAllCustomer(){

		return getHibernateTemplate().find("from Customer");

	}
} 

6.春天+冬眠

声明数据库细节,并通过“ LocalSessionFactoryBean ”将 Spring 和 Hibernate 集成在一起。
T3

 jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyong
jdbc.username=root
jdbc.password=password 

DataSource.xml

 <beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

 <bean 
   class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer">
   <property name="location">
     <value>WEB-INF/classes/config/database/properties/database.properties</value>
   </property>
</bean>

  <bean id="dataSource" 
         class="org.springframework.jdbc.datasource.DriverManagerDataSource">
	<property name="driverClassName" value="${jdbc.driverClassName}" />
	<property name="url" value="${jdbc.url}" />
	<property name="username" value="${jdbc.username}" />
	<property name="password" value="${jdbc.password}" />
  </bean>

</beans> 

hibernate session factory . XML

 <?xml version="1.0" encoding="UTF-8"?>
<beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

<!-- Hibernate session factory -->
<bean id="sessionFactory" 
     class="org.springframework.orm.hibernate3.LocalSessionFactoryBean">

    <property name="dataSource">
      <ref bean="dataSource"/>
    </property>

    <property name="hibernateProperties">
       <props>
         <prop key="hibernate.dialect">org.hibernate.dialect.MySQLDialect</prop>
         <prop key="hibernate.show_sql">true</prop>
       </props>
    </property>

    <property name="mappingResources">
	<list>
          <value>com/mkyong/customer/hibernate/Customer.hbm.xml</value>
	</list>
     </property>	

</bean>
</beans> 

SpringBeans.xml

 <beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<!-- Database Configuration -->
	<import resource="config/database/spring/DataSource.xml"/>
	<import resource="config/database/spring/HibernateSessionFactory.xml"/>

	<!-- Beans Declaration -->
	<import resource="com/mkyong/customer/spring/CustomerBean.xml"/>

</beans> 

7.支柱+弹簧

要集成 Spring 和 Struts,需要在 struts-config.xml 文件中注册一个 Spring 的内置 Struts 插件" ContextLoaderPlugIn "。在 Action 类中,它必须扩展 Spring 的“ ActionSupport ”类,您可以通过getWebApplicationContext()获得 Spring bean。

AddCustomerAction.java

 package com.mkyong.customer.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;

import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.form.CustomerForm;
import com.mkyong.customer.model.Customer;

public class AddCustomerAction extends ActionSupport{

public ActionForward execute(ActionMapping mapping,ActionForm form,
	HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

	CustomerBo customerBo =
 	  (CustomerBo) getWebApplicationContext().getBean("customerBo");

	CustomerForm customerForm = (CustomerForm)form;
	Customer customer = new Customer();

	//copy customerform to model
	BeanUtils.copyProperties(customer, customerForm);

	//save it
	customerBo.addCustomer(customer);

	return mapping.findForward("success");

  }
} 

ListCustomerAction.java

 package com.mkyong.customer.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.DynaActionForm;
import org.springframework.web.struts.ActionSupport;

import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.model.Customer;

public class ListCustomerAction extends ActionSupport{

  public ActionForward execute(ActionMapping mapping,ActionForm form,
	HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

	CustomerBo customerBo =
	  (CustomerBo) getWebApplicationContext().getBean("customerBo");

	DynaActionForm dynaCustomerListForm = (DynaActionForm)form;

	List<Customer> list = customerBo.findAllCustomer();

	dynaCustomerListForm.set("customerList", list);

	return mapping.findForward("success");

  }
} 

CustomerForm.java

 package com.mkyong.customer.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class CustomerForm extends ActionForm {

	private String name;
	private String address;

	//getter and setter, basic validation

} 

客户属性

 #customer module label message
customer.label.name = Name
customer.label.address = Address

customer.label.button.submit = Submit
customer.label.button.reset = Reset

#customer module error message
customer.err.name.required = Name is required
customer.err.address.required = Address is required 

add_customer.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

Struts + Spring + Hibernate 示例

添加客户

::

Struts + Spring 集成示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-spring-integration-example/

下面的教程展示了如何在用 Apache Struts 1.x 开发的 web 应用程序中访问 Spring Ioc 容器中声明的 beans。

Download this Struts 1.x + Spring example – Struts-Spring-Hibernate-Example.zip

Spring 为 Spring Ioc 容器中声明的访问 beans 提供了“特定于 Struts”的解决方案。

  1. 在 Struts 配置文件中注册一个 Spring 的现成 Struts 插件。
  2. 更改您的 Struts action 类来扩展 Spring 的 ActionSupport 类,它是 Struts Action 类的子类。
  3. ActionSupport 为您访问 Spring Ioc 容器中声明的 beans 提供了一个方便的getWebApplicationContext()方法。

1.Struts + Spring 依赖项

为了与 Struts 1.x 集成,Spring 需要" spring-web.jar "和" spring-struts.jar "库。你可以从 Spring 网站或者 Maven 下载。
POM . XML

 <!-- Spring framework --> 
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring</artifactId>
		<version>2.5.6</version>
	</dependency>

        <dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>2.5.6</version>
	</dependency>

	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-struts</artifactId>
		<version>2.0.8</version>
	</dependency> 

2.注册 Struts 插件

在您的 struts 配置文件(struts-config.xml)中,注册 Spring 的现成 Struts 插件—“ContextLoaderPlugIn”。

struts-config.xml

 <struts-config>
    <!-- Spring Struts plugin -->
 	<plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
		<set-property property="contextConfigLocation"
			value="/WEB-INF/classes/SpringBeans.xml" />
  	</plug-in>
</struts-config> 

ContextLoaderPlugIn ”将处理 Struts 和 Spring 之间的所有集成工作。您可以将 Spring 的 bean xml 文件加载到“ contextConfigLocation 属性中。

SpringBeans.xml

 <beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

	<!-- Beans Declaration -->
	<import resource="com/mkyong/customer/spring/CustomerBean.xml"/>

</beans> 

3.春天的行动支持

在 Struts Action 类中,扩展了 Spring " ActionSupport "类,通过"getWebApplicationContext()"方法获取 Spring 的 bean。

CustomerBean.xml

 <bean id="customerBo" class="com.mkyong.customer.bo.impl.CustomerBoImpl" >
   		<property name="customerDao" ref="customerDao" />
   	</bean> 

Struts 动作

 package com.mkyong.customer.action;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;
import org.springframework.web.struts.ActionSupport;

import com.mkyong.customer.bo.CustomerBo;
import com.mkyong.customer.model.Customer;

public class ListCustomerAction extends ActionSupport{

  public ActionForward execute(ActionMapping mapping,ActionForm form,
	HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

	CustomerBo customerBo =
		(CustomerBo) getWebApplicationContext().getBean("customerBo");

	...
	return mapping.findForward("success");

  }
} 

完成了。

integration spring struts

Struts 1 + Spring 2.5.6 + Quartz 1.6 调度器示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-spring-quartz-scheduler-integration-example/

在本教程中,您将集成 Struts + Spring + Quartz 框架来执行调度任务。Spring 提供了现成的解决方案来轻松集成支柱和石英。关系如下:

 Struts <--(Plug-In)--> Spring <--(Spring-Helper)--> Quartz <---> Scheduler task 

使用的工具:

  1. Struts 1.3.10
  2. 弹簧 2.5.6
  3. 石英

1.调度程序任务

创建一个调度器任务,printMessage()就是你想要调度的方法。

文件:SchedulerTask.java

 package com.mkyong.common.quartz;

public class SchedulerTask 
{
   public void printMessage() {
	System.out.println("Struts + Spring + Quartz integration example ~");
   }
} 

2.调度程序作业

要集成 Spring 和 Quartz,创建一个扩展 Spring 的QuartzJobBean的 SchedulerJob,而不是 Quartz Job 类。

文件:SchedulerJob.java

 package com.mkyong.common.quartz;

import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.scheduling.quartz.QuartzJobBean;

public class SchedulerJob extends QuartzJobBean
{
	private SchedulerTask schedulerTask;

	public void setSchedulerTask(SchedulerTask schedulerTask) {
		this.schedulerTask = schedulerTask;
	}

	protected void executeInternal(JobExecutionContext context)
	throws JobExecutionException {

		schedulerTask.printMessage();

	}
} 

3.春天的石英助手

Spring 附带了许多 Quartz 助手类来简化整个 Quartz 调度程序流程——调度程序、Trigget、作业和作业细节。

文件:spring-scheduler.xml

 <beans 
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-2.5.xsd">

  <!-- Scheduler task -->
  <bean name="schedulerTask" class="com.mkyong.common.quartz.SchedulerTask" />

   <!-- Scheduler job -->
   <bean name="schedulerJob" 
     class="org.springframework.scheduling.quartz.JobDetailBean">

     <property name="jobClass" 
           value="com.mkyong.common.quartz.SchedulerJob" />

     <property name="jobDataAsMap">
	<map>
	   <entry key="schedulerTask" value-ref="schedulerTask" />
	 </map>
      </property>

   </bean>

   <!-- Cron Trigger -->
   <bean id="cronTrigger"
	class="org.springframework.scheduling.quartz.CronTriggerBean">

	<property name="jobDetail" ref="schedulerJob" />
	<property name="cronExpression" value="0/5 * * * * ?" />

   </bean>

   <!-- Scheduler -->
   <bean class="org.springframework.scheduling.quartz.SchedulerFactoryBean">
	<property name="jobDetails">
	   <list>
	      <ref bean="schedulerJob" />
	   </list>
	</property>

	<property name="triggers">
	    <list>
		<ref bean="cronTrigger" />
	    </list>
	</property>
   </bean>

</beans> 

4.支杆

要集成 Spring 和 Struts,您需要将 Spring 的ContextLoaderPlugIn包含到 Struts 配置文件中。

文件:struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

   <action-mappings>

    <action
	path="/Welcome"
	type="org.apache.struts.actions.ForwardAction"
	parameter="/pages/quartz_started.jsp"/>

   </action-mappings>

   <!-- Spring Struts plugin -->
   <plug-in className="org.springframework.web.struts.ContextLoaderPlugIn">
	<set-property property="contextConfigLocation"
	value="/WEB-INF/spring-scheduler.xml" />
    </plug-in>

</struts-config> 

5.它是如何工作的

在 Struts 初始化期间,它将通过 Spring 的ContextLoaderPlugIn Struts 插件启动 Spring Ioc 容器;当 Spring 初始化时,它将自动启动 Quartz 调度任务。

在本例中,printMessage()方法将每 5 秒执行一次。

下载源代码

Download it – Struts-Spring-Quartz-Example.zip

参考

更多的细节解释,你可以参考下面的教程

  1. Struts + Spring 集成示例
  2. Spring + Quartz 调度器集成示例

integration quartz scheduler spring struts

Struts Tiles 框架示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-tiles-framework-example/

Struts Tiles 框架是一个布局框架,它允许用户在所有网页上有效地维护页眉、页脚和菜单的标准外观。

Download this example – Struts-Tile-Framework-Example.zip

瓷砖模板示例

下面是一个创建 tiles 模板的示例,用于维护 Struts 中所有网页的页眉和页脚细节。

首先,看看这个 Struts tiles 框架关系。

[

](http://web.archive.org/web/20210128124529/http://www.mkyong.com/wp-content/uploads/2010/05/struts-tiles.png)freestar.config.enabled_slots.push({ placementName: "mkyong_incontent_1", slotId: "mkyong_incontent_1" });

1.获取 Struts 图块库

从 struts 分发文件夹或通过 Maven central repository 获取 struts tiles 库

 <dependency>
      <groupId>org.apache.struts</groupId>
	  <artifactId>struts-tiles</artifactId>
      <version>1.3.10</version>
    </dependency> 

并将其包含在项目依赖关系库中。

2.创建模板

为页眉和页脚详细信息创建红色模板和绿色模板。这两个模板只是背景颜色不同的纯 HTML 代码..

Template-Red color
/Template-Red/header . JSP


# [此处为标志]这是红色标题模板

/template-red/footer.jsp


# 这是红色页脚模板

Template-Green color
/Template-Green/header . JSP


# [此处有标志]这是绿色标题模板

/template-green/footer . JSP


# 这是绿色页脚模板

3.瓷砖布局

为所有网页创建标准网页布局。

common-layout.jsp

<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>

4.主体模板

在 body 模板中,您应该始终为 body 细节创建两个页面“user-form.jsp 和 user-form-body.jsp ”,以打破与 tiles 框架的耦合。“user-form.jsp”用于获取 tiles 定义,并将真实的正文内容(user-form-body.jsp)作为正文模板。

user-form.jsp

<%@ taglib uri="http://struts.apache.org/tags-tiles" prefix="tiles" %>

user-form-body.jsp


# 这是正文内容

5.瓷砖定义

所有的模板都做好了,创建一个“tiles-defs.xml”文件并声明一个“company-template”定义为红色的模板。

tiles-defs.xml

 <!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 1.3//EN"
"http://struts.apache.org/dtds/tiles-config_1_3.dtd">
<tiles-definitions>

   <definition name="company-template" path="/pages/tiles/common-layout.jsp">
	<put name="header" value="/pages/tiles/template-red/header.jsp" />
	<put name="footer" value="/pages/tiles/template-red/footer.jsp" />
   </definition>

</tiles-definitions> 

6.包括 TilesPlugin

要使用 Struts tiles 框架,您必须在 Struts 配置文件中声明" TilesPlugin "插件类。

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

		<action
			path="/User"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/user/user-form.jsp"/>

	</action-mappings>

	<plug-in className="org.apache.struts.tiles.TilesPlugin" >
		<set-property property="definitions-config"
		value="/WEB-INF/tiles-defs.xml"/>
	</plug-in>

</struts-config> 

7.演示

在上述情况下,使用红色模板。

http://localhost:8080/struts example/user . do

struts-tile-framework-1

要将其更改为 template green,只需更新“tiles-defs.xml”文件。

tiles-defs.xml

 <!DOCTYPE tiles-definitions PUBLIC
"-//Apache Software Foundation//DTD Tiles Configuration 1.3//EN"
"http://struts.apache.org/dtds/tiles-config_1_3.dtd">
<tiles-definitions>

   <definition name="company-template" path="/pages/tiles/common-layout.jsp">
	<put name="header" value="/pages/tiles/template-green/header.jsp" />
	<put name="footer" value="/pages/tiles/template-green/footer.jsp" />
   </definition>

</tiles-definitions> 

再次访问它

http://localhost:8080/struts example/user . do

struts-tile-framework-2

页眉和页脚的颜色发生了变化(模板为绿色),在 tiles 配置文件中仅有微小的变化。

参考

Struts Tiles 文档—http://struts.apache.org/1.x/struts-tiles/index.html

Tags : struts template tilesfreestar.config.enabled_slots.push({ placementName: "mkyong_leaderboard_btf", slotId: "mkyong_leaderboard_btf" });

Struts 教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/struts-tutorials/

struts tutorials

Struts 1.x 是最著名、最经典、最成熟的模型-视图-控制器(MVC)框架。很多时候,你会听到这样的话,学习 Struts 1.x 毫无意义,它是一个死框架。然而,尽管 Struts 1.x 在早期取得了巨大的成功,仍然有成千上万的公司在实施 Struts 1.x,并且从来没有考虑过升级,所以 Struts 1.x 仍然存在许多可维护性问题。

Struts 1.x 是一个完整的 web 框架,提供了完整的 web 表单组件、验证器、内部化、错误处理、tiles 布局,学习曲线低且易于实现。在本教程中,它提供了许多关于使用 Struts 1.x MVC 框架的分步示例和解释。

快乐学习 Struts。🙂

Struts 快速入门

让我们快速了解一下 Struts 1.x 框架。

  • Struts hello world 示例
    通过一个 hello world 示例来理解 Struts MVC 是如何工作的。

Struts 配置

所有关于 Struts 配置的东西。

Struts 动作和动作表单

Action 和 ActionForm 实现类。

Struts Web 表单组件

Struts 完全支持所有标准的 web 表单组件。

Struts 逻辑标记

Struts 附带了许多逻辑标记,以简化 bean 组件迭代或条件处理。

Struts 错误和日志记录

异常处理和错误记录。

Struts 本地化

Struts 在国际化或本地化方面有很好的支持。

Struts 验证程序框架

在 Struts 验证器框架中,它提供了许多泛型方法(required、maxlength、minlength..)来验证表单组件,这使您的验证代码更加标准化,也更容易维护。

  • Struts 验证器示例
    一个简单的用户注册表单,并用 Struts 验证器验证用户名、密码和电子邮件字段。

Struts Tiles 框架

Struts tiles 框架是一个强大的布局框架,用于维护所有网页的页眉、页脚或菜单细节的标准外观。

  • Struts Tiles 框架示例
    一个简单的 web 应用程序,演示了使用 Sturts tiles 框架来轻松更改页眉和页脚页面。

Struts 与其他框架集成

任何关于 Struts 与其他框架集成的信息。

Struts 杂项

其他 Struts 示例。

Struts 常见错误

一些 Struts 常见的错误消息。

Struts 参考

Struts 验证器框架示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-validator-framework-example/

Struts 验证器框架提供了许多通用的验证方法,使验证工作更加容易和可维护。使用 Struts validator,您需要将验证函数声明到一个 xml 文件中,而不是 ActionForm validate()方法,这可以使 Struts 验证更加标准化、可重用和减少重复代码。

Download this example – Struts-Validator-Example.zip

使用 Struts 验证器框架

下面是使用 Struts 验证器框架的快速指南。

1.验证程序插件

要使用 Struts 验证器插件,您需要将" ValidatorPlugIn "类包含到 struts-config.xml 文件中。

 ...
<plug-in className="org.apache.struts.validator.ValidatorPlugIn" >
	<set-property property="pathnames"
	value="/WEB-INF/validator-rules.xml, /WEB-INF/validator-user.xml"/>

</plug-in>
... 

" validator-rules.xml "文件包含了所有的通用验证器名称,你可以在 Struts 分发库中获得这个文件,(不要自己创建这个文件)。“validator-user.xml”包含所有表单域验证。

2.验证器表单

对于需要使用验证器框架的表单 bean,它必须扩展验证器表单,而不是动作表单

 import org.apache.struts.validator.ValidatorForm;

public class UserForm extends ValidatorForm{
.. 

3.validator-user.xml

用户表单 bean、电子邮件属性,并将“必需”和“电子邮件”验证器附加到电子邮件属性。“必需”验证器将确保该字段不为空,而“电子邮件”验证器用于检查电子邮件格式是否正确。“必需”和“电子邮件”验证器都在“validator-rules.xml”文件中声明。

 <form-validation>
   <formset>
      <form name="userForm">

		 <field property="email" depends="required,email">

		 	<msg name="required" key="err.user.email.required" />
		 	<msg name="email" key="err.user.email.invalid" />

		 </field>

     </form>
  </formset>
</form-validation> 

Struts 验证器框架示例

理解 Struts validator 框架的最佳方式是创建一个简单的应用程序并完成验证工作。这里有一个简单的用户注册表单,使用 Struts validator 框架来检查用户名、密码和电子邮件。

1.行动

动作类,只是转发一个成功请求。

user action . Java

 package com.mkyong.user.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

public class UserAction extends Action{

	public ActionForward execute(ActionMapping mapping, ActionForm form,
		HttpServletRequest request, HttpServletResponse response)
	throws Exception {

		return mapping.findForward("success");
	}
} 

2.用户表单

UserForm 扩展了 ValidatorForm 类。

UserForm.java

 package com.mkyong.user.form;

import org.apache.struts.validator.ValidatorForm;

public class UserForm extends ValidatorForm{

	String username;
	String pwd;
	String pwd2;
	String email;

	//getter and setter methods

} 

3.属性文件

属性文件包含所有标签和错误消息。

用户属性

 #user module label message
label.user.name = Name
label.user.username = UserName
label.user.pwd = Password
label.user.pwd2 = Confirm Password
label.user.email = Email

label.user.button.submit = Submit

#Error message
err.user.username.required = Username is required.<br/>
err.user.username.length = Username length should be between {0} and {1}.<br/>
err.user.username.invalid = 
Username is invalid , it should be a-z, A-Z, 0-9, dash "-" or underscore "_".<br/>

err.user.pwd.required = Password is required.<br/>
err.user.pwd.length = Password length should be between {0} and {1}.<br/>
err.user.pwd.invalid = Password is invalid , it should be a-z, A-Z, 0-9.<br/>

err.user.pwd2.notmatch = Confirm password is not match.<br/>

err.user.email.required = Email is required.<br/>
err.user.email.invalid =  Email address is invalid.<br/> 

4.查看页面

一个简单的 jsp 页面创建所有需要的文本字段,和一个简单的感谢页面

RegisterUser.jsp

<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>
<%@taglib uri="http://struts.apache.org/tags-logic" prefix="logic"%>
<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>

Struts -验证器示例

RegisterUser.jsp
User Registeration Form

: : : :

ThanksYou.jsp


Struts -验证器示例

Thanks you for the registration

5.Struts 配置

配置动作、表单映射并注册“ValidatorPlugIn”插件。

struts-connfig.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

   <form-beans>
	<form-bean name="userForm" type="com.mkyong.user.form.UserForm" />	
   </form-beans>

   <action-mappings>

	 	<action
			path="/Register"
			type="com.mkyong.user.action.UserAction"
			name="userForm"
			input="/pages/RegisterUser.jsp"
			>

			<forward name="success" path="/pages/ThanksYou.jsp"/>

		</action>

		<action
			path="/RegisterUserPage"
			type="org.apache.struts.actions.ForwardAction"
			parameter="/pages/RegisterUser.jsp"/>

   </action-mappings>

   <message-resources
		parameter="com.mkyong.user.properties.user" />

   <plug-in className="org.apache.struts.validator.ValidatorPlugIn" >
	<set-property property="pathnames"
	value="/WEB-INF/validator-rules.xml, /WEB-INF/validator-user.xml"/>

   </plug-in>

</struts-config> 

6.validator-user.xml

为用户表单的用户名、密码和电子邮件属性定义验证器。

validator-user.xml

 <!DOCTYPE form-validation PUBLIC
 "-//Apache Software Foundation
//DTD Commons Validator Rules Configuration 1.3.0//EN"
 "http://jakarta.apache.org/commons/dtds/validator_1_3_0.dtd">

<form-validation>
   <formset>
      <form name="userForm">
         <field property="username" depends="required,maxlength,minlength,mask">

         	<msg name="required" key="err.user.username.required" />
		<msg name="maxlength" key="err.user.username.length" />
		<msg name="minlength" key="err.user.username.length" />
		<msg name="mask" key="err.user.username.invalid" />

		<arg name="maxlength" key="${var:minlength}" position="0" resource="false"/>
                <arg name="maxlength" key="${var:maxlength}" position="1" resource="false"/>

	        <arg name="minlength" key="${var:minlength}" position="0" resource="false"/>
                <arg name="minlength" key="${var:maxlength}" position="1" resource="false"/>

                <var>
            	        <var-name>minlength</var-name>
		        <var-value>3</var-value>
		</var>		
		<var>
			<var-name>maxlength</var-name>
			<var-value>15</var-value>
		</var>
                <var>
			<var-name>mask</var-name>
			<var-value>^[a-zA-Z0-9-_]*$</var-value>
		</var>
         </field>

         <field property="pwd" depends="required,maxlength,minlength,mask">

         	<msg name="required" key="err.user.pwd.required" />
		<msg name="maxlength" key="err.user.pwd.length" />
		<msg name="minlength" key="err.user.pwd.length" />
		<msg name="mask" key="err.user.pwd.invalid" />

		<arg name="maxlength" key="${var:minlength}" position="0" resource="false"/>
                <arg name="maxlength" key="${var:maxlength}" position="1" resource="false"/>

		<arg name="minlength" key="${var:minlength}" position="0" resource="false"/>
                <arg name="minlength" key="${var:maxlength}" position="1" resource="false"/>

                <var>
            	        <var-name>minlength</var-name>
			<var-value>7</var-value>
		</var>		
		<var>
			<var-name>maxlength</var-name>
			<var-value>15</var-value>
		</var>
                <var>
			<var-name>mask</var-name>
			<var-value>^[a-zA-Z0-9]*$</var-value>
		</var>
         </field>

         <field property="pwd2" depends="validwhen">

         	<msg name="validwhen" key="err.user.pwd2.notmatch" />

		<var>
			<var-name>test</var-name>
			<var-value>
				(pwd == *this*)
			</var-value>
		</var>
	 </field>

	<field property="email" depends="required,email">	 
	 	<msg name="required" key="err.user.email.required" />
	 	<msg name="email" key="err.user.email.invalid" />
	 </field>

     </form>
  </formset>
</form-validation> 

7.演示

http://localhost:8080/struts example/register user page . do

Struts-Validator-Example-1

http://localhost:8080/struts example/register . do

Struts-Validator-Example-2

验证码是描述性的,足以知道它是如何工作的,如果你想知道细节,以及其他可用的验证器,请检查下面的参考网站。

参考

Struts 验证器文档—http://struts.apache.org/1.2.4/userGuide/dev_validator.html

struts validation

struts–通配符示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-wildcards-example/

Download this example – Struts-Wildcards-Example.zip

struts 通配符可以帮助减少 struts-config.xml 文件中的重复,只要您的 Struts 项目遵循一些常规的文件结构。例如,在用户模块中,为了实现 CRUD 函数,您的 struts-config.xml 可能如下所示

1.没有通配符

你需要为每个列表创建四个动作映射,添加、删除和更新函数,以及大量的重复。

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

	 	<action
			path="/ListUserAction"
			type="com.mkyong.common.action.UserAction"
			parameter="ListUser"
			>

			<forward name="success" path="/pages/ListUser.jsp"/>

		</action>

		<action
			path="/AddUserAction"
			type="com.mkyong.common.action.UserAction"
			parameter="AddUser"
			>

			<forward name="success" path="/pages/AddUser.jsp"/>

		</action>

		<action
			path="/EditUserAction"
			type="com.mkyong.common.action.UserAction"
			parameter="EditUser"
			>

			<forward name="success" path="/pages/EditUser.jsp"/>

		</action>

		<action
			path="/DeleteUserAction"
			type="com.mkyong.common.action.UserAction"
			parameter="DeleteUser"
			>

			<forward name="success" path="/pages/DeleteUser.jsp"/>

		</action>

	</action-mappings>

</struts-config> 

2.带通配符

使用 Struts 通配符特性,您的 struts-config.xml 可以缩减为一个操作映射。

struts-config.xml

 <?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts-config PUBLIC 
"-//Apache Software Foundation//DTD Struts Configuration 1.3//EN" 
"http://jakarta.apache.org/struts/dtds/struts-config_1_3.dtd">

<struts-config>

	<action-mappings>

	 	<action
			path="/*UserAction"
			type="com.mkyong.common.action.UserAction"
			parameter="{1}User"
			>

			<forward name="success" path="/pages/{1}User.jsp"/>

		</action>

	</action-mappings>

</struts-config> 

让我们来看一个用例,通过http://localhost:8080/struts example/edit user action . do尝试访问。“ EditUserAction.do ”将匹配“ /*UserAction ”模式, ***** 匹配字符串“ Edit ”用 {1} 表示,以备后用。

在上述情况下,通配符操作映射将从

 <action
		path="/*UserAction"
		type="com.mkyong.common.action.UserAction"
		parameter="{1}User"
	>

	<forward name="success" path="/pages/{1}User.jsp"/>

	</action> 

 <action
		path="/EditUserAction"
		type="com.mkyong.common.action.UserAction"
		parameter="EditUser"
	>

	<forward name="success" path="/pages/EditUser.jsp"/>

	</action> 

结论

两个 struts-config.xml 示例具有相同的功能,但是在通配符支持方面重复较少。然而,不要在你的项目中过度使用这个通配符特性,它比普通的声明更难管理。

struts

用 ExpressionParser 测试弹簧 el

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/spring3/test-spring-el-with-expressionparser/

Spring expression language (SpEL)支持许多功能,您可以使用这个特殊的“ ExpressionParser ”接口来测试那些表达式特性。

这里有两个代码片段,展示了使用 Spring EL 的基本用法。

SpEL 来计算文字字符串表达式。

 ExpressionParser parser = new SpelExpressionParser();
Expression exp = parser.parseExpression("'put spel expression here'");
String msg = exp.getValue(String.class); 

SpEL 来评估 bean 属性“item.name”。

 Item item = new Item("mkyong", 100);
StandardEvaluationContext itemContext = new StandardEvaluationContext(item);

//display the value of item.name property
Expression exp = parser.parseExpression("name");
String msg = exp.getValue(itemContext, String.class); 

测试 SpEL 的几个例子。代码和注释应该是自我探索的。

 import org.springframework.expression.Expression;
import org.springframework.expression.ExpressionParser;
import org.springframework.expression.spel.standard.SpelExpressionParser;
import org.springframework.expression.spel.support.StandardEvaluationContext;

public class App {
	public static void main(String[] args) {

		ExpressionParser parser = new SpelExpressionParser();

		//literal expressions 
		Expression exp = parser.parseExpression("'Hello World'");
		String msg1 = exp.getValue(String.class);
		System.out.println(msg1);

		//method invocation
		Expression exp2 = parser.parseExpression("'Hello World'.length()");  
		int msg2 = (Integer) exp2.getValue();
		System.out.println(msg2);

		//Mathematical operators
		Expression exp3 = parser.parseExpression("100 * 2");  
		int msg3 = (Integer) exp3.getValue();
		System.out.println(msg3);

		//create an item object
		Item item = new Item("mkyong", 100);
		//test EL with item object
		StandardEvaluationContext itemContext = new StandardEvaluationContext(item);

		//display the value of item.name property
		Expression exp4 = parser.parseExpression("name");
		String msg4 = exp4.getValue(itemContext, String.class);
		System.out.println(msg4);

		//test if item.name == 'mkyong'
		Expression exp5 = parser.parseExpression("name == 'mkyong'");
		boolean msg5 = exp5.getValue(itemContext, Boolean.class);
		System.out.println(msg5);

	}
} 
 public class Item {

	private String name;

	private int qty;

	public Item(String name, int qty) {
		super();
		this.name = name;
		this.qty = qty;
	}

	//...
} 

输出

 Hello World
11
200
mkyong
true 

Note
This article is demonstrates few basic usages of Spring expression parser, and you should visit this official Spring expression documentation for hundred of useful SpEL examples.

下载源代码

Download It – Spring3-EL-Parser-Example.zip (6 KB)spring el spring3 (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190225101849/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

TestNG–分组测试

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-groups-example/

在本教程中,我们将向您展示如何在 TestNG 中进行分组测试。

1.方法组

查看测试组示例。

  1. runSelenium()和 runSelenium1()属于组selenium-test
  2. testConnectOracle()和 testConnectMsSQL()属于组database
  3. 如果组selenium-testdatabase通过,将执行 runFinal()。

TestGroup.java

 package com.mkyong.testng.examples.group;

import org.testng.annotations.AfterGroups;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.Test;

public class TestGroup {

	@BeforeGroups("database")
	public void setupDB() {
		System.out.println("setupDB()");
	}

	@AfterGroups("database")
	public void cleanDB() {
		System.out.println("cleanDB()");
	}

	@Test(groups= "selenium-test")
	public void runSelenium() {
		System.out.println("runSelenium()");
	}

	@Test(groups= "selenium-test")
	public void runSelenium1() {
		System.out.println("runSelenium()1");
	}

	@Test(groups = "database")
	public void testConnectOracle() {
		System.out.println("testConnectOracle()");
	}

	@Test(groups = "database")
	public void testConnectMsSQL() {
		System.out.println("testConnectMsSQL");
	}

	@Test(dependsOnGroups = {"database","selenium-test"})
	public void runFinal() {
		System.out.println("runFinal");
	}

} 

输出

 //group = selenium-test
runSelenium()
runSelenium()1

//group = database
setupDB()
testConnectMsSQL
testConnectOracle()
cleanDB()

//dependsOnGroups = database, selenium-test
runFinal

PASSED: runSelenium
PASSED: runSelenium1
PASSED: testConnectMsSQL
PASSED: testConnectOracle
PASSED: runFinal 

2.课堂上的小组

“组”可以应用于类级别。在下面的例子中,这个类“TestSelenium”的每个公共方法都属于组selenium-test

TestSelenium.java

 package com.mkyong.testng.examples.group;

import org.testng.annotations.Test;

@Test(groups= "selenium-test")
public class TestSelenium {

	public void runSelenium() {
		System.out.println("runSelenium()");
	}

	public void runSelenium1() {
		System.out.println("runSelenium()1");
	}

} 

创建一个 XML 文件来运行 2 个测试类。

testng.xml

 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestAll">

	<test name="final">
		<classes>
			<class name="com.mkyong.testng.examples.group.TestSelenium" />
			<class name="com.mkyong.testng.examples.group.TestGroup" />
		</classes>
	</test>

	<!-- Run test method on group "selenium" only -->
	<test name="selenium">

		<groups>
			<run>
				<include name="selenium-test" />
			</run>
		</groups>

		<classes>
			<class name="com.mkyong.testng.examples.group.TestSelenium" />
			<class name="com.mkyong.testng.examples.group.TestGroup" />
		</classes>

	</test>

</suite> 

输出

 //test name = final
runSelenium()
runSelenium()1
setupDB()
testConnectMsSQL
testConnectOracle()
cleanDB()
runFinal

//test name = selenium
runSelenium()
runSelenium()1

===============================================
TestAll
Total tests run: 7, Failures: 0, Skips: 0
=============================================== 

3.杂项示例

3.1 一种试验方法可以属于多个组。

 @Test(groups = {"mysql","database"})
	public void testConnectMsSQL() {
		System.out.println("testConnectMsSQL");
	} 

3.2 以上结果是通过 Eclipse TestNG 插件执行的。

eclipse-testng

参考

  1. TestNG : @Test
  2. TestNG Eclipse 插件

group test testng

TestNG Hello World 示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-hello-world-example/

一个经典的例子,向你展示如何开始使用 TestNG 单元测试框架。

使用的工具:

  1. 测试 6.8.7
  2. maven3
  3. Eclipse IDE

1.测试依赖关系

pom.xml中添加 TestNG 库。

pom.xml

 <dependency>
		<groupId>org.testng</groupId>
		<artifactId>testng</artifactId>
		<version>6.8.7</version>
		<scope>test</scope>
	</dependency> 

2.测试示例

复习一个简单的类,有一个方法返回一个固定的邮箱“feedback@yoursite.com”。

RandomEmailGenerator.java

 package com.mkyong.testng.project.service.email;

import org.springframework.stereotype.Service;

public class RandomEmailGenerator {

	public String generate() {
		return "feedback@yoursite.com";
	}

} 

创建一个这样的测试用例:

TestHelloWorld.java

 package com.mkyong.testng.examples.helloworld;

import org.testng.Assert;
import org.testng.annotations.Test;
import com.mkyong.testng.project.service.email.RandomEmailGenerator;

public class TestHelloWorld {

	@Test()
	public void testEmailGenerator() {

		RandomEmailGenerator obj = new RandomEmailGenerator();
		String email = obj.generate();

		Assert.assertNotNull(email);
		Assert.assertEquals(email, "feedback@yoursite.com");

	}

} 

完成后,一个简单的 TestNG 测试用例就创建了,这个测试确保RandomEmailGenerator.generate()总是返回“feedback@yoursite.com”。

3.测试 Eclipse 插件

要在 Eclipse IDE 中运行上述测试,您需要安装 TestNG Eclipse 插件。按照这个官方测试 Eclipse 插件指南进行安装。

要运行 TestNG 测试,右键单击测试类并作为“TestNG test”运行。

testng-eclipse-plugin

结果

testng-hello-world

参考

  1. TestNG 官方文档

hello world testng

TestNG 参数测试示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-parameter-testing-example/

又一个 TestNG 参数测试例子,用@DataProvider

1.CharUtil 类

比方说,一个将字符转换为 ASCII 或相反的类,如何用 TestNG 对它进行单元测试?

CharUtils.java

 package com.mkyong.testng.examples.parameter;

/**
 * Character Utility class
 * 
 * @author mkyong
 * 
 */
public class CharUtils {
	/**
	 * Convert the characters to ASCII value
	 * 
	 * @param character character
	 * @return ASCII value
	 */
	public static int CharToASCII(final char character) {
		return (int) character;
	}

	/**
	 * Convert the ASCII value to character
	 * 
	 * @param ascii ascii value
	 * @return character value
	 */
	public static char ASCIIToChar(final int ascii) {
		return (char) ascii;
	}
} 

2.TestNG @DataProvider 示例

为了测试它,创建一个接受两个参数(字符和期望的 ASCII)的@Test方法,测试数据从数据提供者传递。

CharUtilsTest.java

 package com.mkyong.testng.examples.parameter;

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
/**
 * Character Utils Testing
 * @author mkyong
 *
 */
public class CharUtilsTest {

	@DataProvider
	public Object[][] ValidDataProvider() {
		return new Object[][]{
			{ 'A', 65 },{ 'a', 97 },
			{ 'B', 66 },{ 'b', 98 },
			{ 'C', 67 },{ 'c', 99 },
			{ 'D', 68 },{ 'd', 100 },
			{ 'Z', 90 },{ 'z', 122 },
			{ '1', 49 },{ '9', 57 }
		};
	}

	@Test(dataProvider = "ValidDataProvider")
	public void CharToASCIITest(final char character, final int ascii) {

		   int result = CharUtils.CharToASCII(character); 
		   Assert.assertEquals(result, ascii);

	}

	@Test(dataProvider = "ValidDataProvider")
	public void ASCIIToCharTest(final char character, final int ascii) {

		   char result = CharUtils.ASCIIToChar(ascii); 
		   Assert.assertEquals(result, character); 

	}
} 

结果

 PASSED: CharToASCIITest(A, 65)
PASSED: CharToASCIITest(a, 97)
PASSED: CharToASCIITest(B, 66)
PASSED: CharToASCIITest(b, 98)
PASSED: CharToASCIITest(C, 67)
PASSED: CharToASCIITest(c, 99)
PASSED: CharToASCIITest(D, 68)
PASSED: CharToASCIITest(d, 100)
PASSED: CharToASCIITest(Z, 90)
PASSED: CharToASCIITest(z, 122)
PASSED: CharToASCIITest(1, 49)
PASSED: CharToASCIITest(9, 57)
PASSED: ASCIIToCharTest(A, 65)
PASSED: ASCIIToCharTest(a, 97)
PASSED: ASCIIToCharTest(B, 66)
PASSED: ASCIIToCharTest(b, 98)
PASSED: ASCIIToCharTest(C, 67)
PASSED: ASCIIToCharTest(c, 99)
PASSED: ASCIIToCharTest(D, 68)
PASSED: ASCIIToCharTest(d, 100)
PASSED: ASCIIToCharTest(Z, 90)
PASSED: ASCIIToCharTest(z, 122)
PASSED: ASCIIToCharTest(1, 49)
PASSED: ASCIIToCharTest(9, 57)

===============================================
    com.mkyong.common.CharUtilsTest
    Tests run: 24, Failures: 0, Skips: 0
=============================================== 

More Parameter Examples.
For more examples, please refer to this TestNG parameter test with XML and DataProvider.parameter test testng (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190227120414/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

TestNG+Selenium–负载测试示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-selenium-load-testing-example/

testng-selenium-load-test

在本教程中,我们将向您展示如何使用@Test 属性invocationCountthreadPoolSize在网站上执行负载测试或压力测试。

使用的工具:

  1. 测试 6.8.7
  2. maven3

我们正在使用 Selenium 库来自动化浏览器访问网站。

1.项目依赖性

获取 TestNG 和 Selenium 库。

pom.xml

 <properties>
	<testng.version>6.8.7</testng.version>
	<selenium.version>2.39.0</selenium.version>
  </properties>

  <dependencies>
	<dependency>
		<groupId>org.testng</groupId>
		<artifactId>testng</artifactId>
		<version>${testng.version}</version>
		<scope>test</scope>
	</dependency>
	<dependency>
		<groupId>org.seleniumhq.selenium</groupId>
		<artifactId>selenium-java</artifactId>
		<version>${selenium.version}</version>
	</dependency>
   <dependencies> 

2.@Test(invocationCount=?)

这个invocationCount决定了 TestNG 应该运行这个测试方法多少次。

例 2.1

 @Test(invocationCount = 10)
  public void repeatThis() {
    //...
  } 

输出—repeatThis()方法将运行 10 次。

 PASSED: repeatThis
PASSED: repeatThis
PASSED: repeatThis
PASSED: repeatThis
PASSED: repeatThis
PASSED: repeatThis
PASSED: repeatThis
PASSED: repeatThis
PASSED: repeatThis
PASSED: repeatThis 

示例 2.2–使用 Selenium 打开 Firefox 浏览器并加载“Google.com”。这个测试是为了确保页面标题始终是“Google”。

 package com.mkyong.testng.examples.loadtest;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class TestMultipleThreads {

	@Test(invocationCount = 5)
	public void loadTestThisWebsite() {

		WebDriver driver = new FirefoxDriver();		
		driver.get("http://www.google.com");
		System.out.println("Page Title is " + driver.getTitle());
		Assert.assertEquals("Google", driver.getTitle());
		driver.quit();

	}
} 

输出–你会注意到 Firefox 浏览器会提示退出并关闭 5 次。

 Page Title is Google
Page Title is Google
Page Title is Google
Page Title is Google
Page Title is Google
PASSED: loadTestThisWebsite
PASSED: loadTestThisWebsite
PASSED: loadTestThisWebsite
PASSED: loadTestThisWebsite
PASSED: loadTestThisWebsite 

3.@Test(invocationCount =?,threadPoolSize =?)

threadPoolSize属性告诉 TestNG 创建一个线程池,通过多线程运行测试方法。有了线程池,将大大减少测试方法的运行时间。

例 3.1–启动一个线程池,包含 3 个线程,运行测试方法 3 次。

 @Test(invocationCount = 3, threadPoolSize = 3)
  public void testThreadPools() {

	System.out.printf("Thread Id : %s%n", Thread.currentThread().getId());

  } 

输出——测试方法运行 3 次,每次都接收到自己的线程。

 [ThreadUtil] Starting executor timeOut:0ms workers:3 threadPoolSize:3
Thread Id : 10
Thread Id : 12
Thread Id : 11
PASSED: testThreadPools
PASSED: testThreadPools
PASSED: testThreadPools 

例 3.2–启动一个线程池,包含 3 个线程,运行测试方法 10 次。

 @Test(invocationCount = 10, threadPoolSize = 3)
  public void testThreadPools() {

	System.out.printf("Thread Id : %s%n", Thread.currentThread().getId());

  } 

输出–测试方法运行 10 次,线程被重用。

 [ThreadUtil] Starting executor timeOut:0ms workers:10 threadPoolSize:3
Thread Id : 10
Thread Id : 11
Thread Id : 12
Thread Id : 10
Thread Id : 11
Thread Id : 12
Thread Id : 10
Thread Id : 11
Thread Id : 12
Thread Id : 10
PASSED: testThreadPools
PASSED: testThreadPools
PASSED: testThreadPools
PASSED: testThreadPools
PASSED: testThreadPools
PASSED: testThreadPools
PASSED: testThreadPools
PASSED: testThreadPools
PASSED: testThreadPools
PASSED: testThreadPools 

4.负载测试示例

通过结合 TestNG 多线程和 Selenium 强大的浏览器自动化。您可以创建一个简单而强大的负载测试,如下所示:

TestMultipleThreads.java

 package com.mkyong.testng.examples.loadtest;

import org.openqa.selenium.WebDriver;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.testng.Assert;
import org.testng.annotations.Test;

public class TestMultipleThreads {

  @Test(invocationCount = 100, threadPoolSize = 5)
  public void loadTest() {

	System.out.printf("%n[START] Thread Id : %s is started!", 
                                  Thread.currentThread().getId());

	WebDriver driver = new FirefoxDriver();
	driver.get("http://yourwebsite.com");

	//perform whatever actions, like login, submit form or navigation

	System.out.printf("%n[END] Thread Id : %s", 
                                  Thread.currentThread().getId());

	driver.quit();

  }
} 

输出–上面的测试将启动一个 5 线程池,并向一个指定的网站发送 100 个 URL 请求。

 [ThreadUtil] Starting executor timeOut:0ms workers:100 threadPoolSize:5

[START] Thread Id : 11 is started!
[START] Thread Id : 14 is started!
[START] Thread Id : 10 is started!
[START] Thread Id : 12 is started!
[START] Thread Id : 13 is started!
[END] Thread Id : 11
[START] Thread Id : 11 is started!
[END] Thread Id : 10
[START] Thread Id : 10 is started!
[END] Thread Id : 13
[START] Thread Id : 13 is started!
[END] Thread Id : 14
[START] Thread Id : 14 is started!
[END] Thread Id : 12
[START] Thread Id : 12 is started!
[END] Thread Id : 13
...... 

FAQs
Q : For load testing with Selenium and TestNG, why only one browser is prompts out at a time?
A : Your test method is completed too fast, try putting a Thread.sleep(5000) to delay the execution, now, you should notice multiple browsers prompt out simultaneously. (For demonstration purpose only).

下载源代码

Download – TestNG-LoadTest-Example.zip (15 kb)

参考

  1. 硒网站
  2. 维基百科:负载测试

load test selenium testng

TestNG + Spring 集成示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-spring-integration-example/

在本教程中,我们将向您展示如何用 TestNG 测试 Spring 的组件。

使用的工具:

  1. 测试 6.8.7
  2. 弹簧 3.2.2 释放
  3. maven3
  4. Eclipse IDE

1.项目相关性

要将 Spring 与 TestNG 集成,您需要spring-test.jar,添加以下内容:

pom.xml

 <properties>
		<spring.version>3.2.2.RELEASE</spring.version>	
		<testng.version>6.8.7</testng.version>
	</properties>

	<dependencies>
		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-core</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.springframework</groupId>
			<artifactId>spring-test</artifactId>
			<version>${spring.version}</version>
		</dependency>

		<dependency>
			<groupId>org.testng</groupId>
			<artifactId>testng</artifactId>
			<version>${testng.version}</version>
			<scope>test</scope>
		</dependency>
	</dependencies> 

2.弹簧组件

创建一个简单的 Spring 组件,稍后我们将使用 TestNG 测试这个组件。

EmailGenerator.java

 package com.mkyong.testng.project.service.email;

public interface EmailGenerator {

	String generate();

} 

RandomEmailGenerator.java

 package com.mkyong.testng.project.service.email;

import org.springframework.stereotype.Service;

@Service
public class RandomEmailGenerator implements EmailGenerator {

	@Override
	public String generate() {
		return "feedback@yoursite.com";
	}

} 

3.测试+弹簧

在测试文件夹中创建一个 Spring 配置文件,用于 Spring 组件扫描。

${project}/src/test/resources/spring-test-config.xml

 <beans 
	xmlns:context="http://www.springframework.org/schema/context"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="
		http://www.springframework.org/schema/beans 
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
    http://www.springframework.org/schema/context
	http://www.springframework.org/schema/context/spring-context-3.2.xsd
	">

	<context:component-scan base-package="com.mkyong.testng" />

</beans> 

要访问 TestNG 中的弹簧组件,请扩展AbstractTestNGSpringContextTests,参见以下示例:

${project}/src/test/java/com/mkyong/testng/examples/spring/TestSpring.java

 package com.mkyong.testng.examples.spring;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.testng.AbstractTestNGSpringContextTests;
import org.testng.Assert;
import org.testng.annotations.Test;
import com.mkyong.testng.project.service.email.EmailGenerator;

@Test
@ContextConfiguration(locations = { "classpath:spring-test-config.xml" })
public class TestSpring extends AbstractTestNGSpringContextTests {

	@Autowired
	EmailGenerator emailGenerator;

	@Test()
	void testEmailGenerator() {

		String email = emailGenerator.generate();
		System.out.println(email);

		Assert.assertNotNull(email);
		Assert.assertEquals(email, "feedback@yoursite.com");

	}

} 

输出

 feedback@yoursite.com
PASSED: testEmailGenerator

===============================================
    Default test
    Tests run: 1, Failures: 0, Skips: 0
=============================================== 

下载源代码

Download it – TestNG-Spring-Example.zip (35 KB)

参考

  1. Spring–TestNG 支持类
  2. Spring AbstractTestNGSpringContextTests JavaDoc

spring testng

TestNG–配置注释示例

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-tutorial-1-basic-usage/

testng-configuration

在 TestNG 中,我们可以使用以下注释来为您的测试类进行配置,比如设置/清理数据库、准备虚拟数据、部署/关闭服务器等。

 @BeforeSuite - For suite test, run before all tests in this suite have run. 
@AfterSuite -  For suite test, run after all tests in this suite have run.

@BeforeTest - For suite test, run before any test method belonging to the classes inside the <test> tag is run. 
@AfterTest - For suite test, run after all the test methods belonging to the classes inside the <test> tag have run. 

@BeforeGroups: Run before the first test method that belongs to the group is invoked. 
@AfterGroups: Run after the last test method that belongs to the groups is invoked. 

@BeforeClass - Run before the first test method in the current class is invoked. 
@AfterClass - Run after all the test methods in the current class have been run. 

@BeforeMethod - Run before each test method. 
@AfterMethod - Run after each test method. 

P.S Suite 测试–一起运行多个测试类。

回顾下面的例子,看看执行顺序——首先调用哪个方法,然后调用哪个方法。

1.单一测试类别

运行单个测试用例,展示之前/之后groupclassmethod的使用。

TestConfiguration.java

 package com.mkyong.testng.examples.configuration;

import org.testng.annotations.AfterClass;
import org.testng.annotations.AfterGroups;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeGroups;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;

public class TestConfiguration {

	@BeforeGroups("shopping")
	public void beforeGroups() {
		System.out.println("@BeforeGroups");
	}

	@AfterGroups("shopping")
	public void afterGroups() {
		System.out.println("@AfterGroups");
	}

	@BeforeClass
	public void beforeClass() {
		System.out.println("@BeforeClass");
	}

	@AfterClass
	public void afterClass() {
		System.out.println("@AfterClass");
	}

	@BeforeMethod
	public void beforeMethod() {
		System.out.println("@BeforeMethod");
	}

	@AfterMethod
	public void afterMethod() {
		System.out.println("@AfterMethod");
	}

	@Test(groups = "shopping")
	public void runTest1() {
		System.out.println("@Test - runTest1");
	}

	@Test
	public void runTest2() {
		System.out.println("@Test - runTest2");
	}
} 

输出

 @BeforeClass 

@BeforeGroups 
@BeforeMethod 
@Test - runTest1
@AfterMethod  
@AfterGroups  

@BeforeMethod
@Test - runTest2
@AfterMethod

@AfterClass

PASSED: runTest1
PASSED: runTest2

===============================================
    Default test
    Tests run: 2, Failures: 0, Skips: 0
=============================================== 

2.套件测试类

再创建 2 个测试类来展示 before/after suitetest的用法。

DBConfig.java

 package com.mkyong.testng.examples.configuration;

import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;

public class DBConfig {

	@BeforeSuite()
	public void beforeSuite() {
		System.out.println("@BeforeSuite");
	}

	@AfterSuite()
	public void afterSuite() {
		System.out.println("@AfterSuite");
	}

	@BeforeTest()
	public void beforeTest() {
		System.out.println("@BeforeTest");
	}

	@AfterTest()
	public void afterTest() {
		System.out.println("@AfterTest");
	}

} 

TestDBConnection.java

 package com.mkyong.testng.examples.configuration;

import org.testng.annotations.Test;

public class TestDBConnection {

	@Test
	public void runOtherTest1() {
		System.out.println("@Test - runOtherTest1");
	}

	@Test
	public void runOtherTest2() {
		System.out.println("@Test - runOtherTest2");
	}

} 

创建一个 XML 文件来一起运行多个测试用例。阅读 XML 注释,这是不言自明的。

testng.xml

 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<!-- @BeforeSuite -->
<suite name="TestAll">

	<!-- @BeforeTest -->
	<test name="case1">
	  <classes>
		<class name="com.mkyong.testng.examples.configuration.TestConfiguration" />
		<class name="com.mkyong.testng.examples.configuration.TestDBConnection" />
		<class name="com.mkyong.testng.examples.configuration.DBConfig" />
	  </classes>
	</test>
	<!-- @AfterTest -->

	<!-- @BeforeTest -->
	<test name="case2">
	  <classes>
		<class name="com.mkyong.testng.examples.configuration.TestDBConnection" />
		<class name="com.mkyong.testng.examples.configuration.DBConfig" />
	  </classes>
	</test>
	<!-- @AfterTest -->

</suite>
<!-- @AfterSuite --> 

输出

 @BeforeSuite

@BeforeTest		//Start {case1}
@BeforeClass
@BeforeGroups
@BeforeMethod
@Test - runTest1
@AfterMethod
@AfterGroups
@BeforeMethod
@Test - runTest2
@AfterMethod
@AfterClass
@Test - runOtherTest1
@Test - runOtherTest2
@AfterTest		//End {case1}

@BeforeTest		//Start {case2}
@Test - runOtherTest1
@Test - runOtherTest2
@AfterTest		//End {case2}

@AfterSuite

===============================================
TestAll
Total tests run: 6, Failures: 0, Skips: 0
=============================================== 

完成了。

参考

  1. 测试文档
  2. TestNG–运行多个测试类(套件测试)

suite test testng testng config

TestNG–预期异常测试

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-tutorial-2-expected-exception-test/

在本教程中,我们将向您展示如何使用 TestNG expectedExceptions来测试代码中预期的异常抛出。

1.运行时异常

这个例子向你展示了如何测试一个运行时异常。如果方法divisionWithException ()抛出一个运行时异常——ArithmeticException,它将被传递。

TestRuntime.java

 package com.mkyong.testng.examples.exception;

import org.testng.annotations.Test;

public class TestRuntime {

	@Test(expectedExceptions = ArithmeticException.class)
	public void divisionWithException() {
		int i = 1 / 0;
	}

} 

上述单元测试将通过。

2.检查异常

检查一个简单的业务对象,保存和更新方法,如果出错,抛出自定义的检查异常。

OrderBo.java

 package com.mkyong.testng.project.order;

public class OrderBo {

  public void save(Order order) throws OrderSaveException {

	if (order == null) {
	  throw new OrderSaveException("Order is empty!");
	}
	// persist it
  }

  public void update(Order order) throws OrderUpdateException, OrderNotFoundException {

	if (order == null) {
	  throw new OrderUpdateException("Order is empty!");
	}

	// If order is not available in the database
	throw new OrderNotFoundException("Order is not exists");

  }
} 

测试预期异常的示例。

TestCheckedException.java

 package com.mkyong.testng.examples.exception;

import org.testng.annotations.BeforeTest;
import org.testng.annotations.Test;

import com.mkyong.testng.project.order.Order;
import com.mkyong.testng.project.order.OrderBo;
import com.mkyong.testng.project.order.OrderNotFoundException;
import com.mkyong.testng.project.order.OrderSaveException;
import com.mkyong.testng.project.order.OrderUpdateException;

public class TestCheckedException {

  OrderBo orderBo;
  Order data;

  @BeforeTest
  void setup() {
	orderBo = new OrderBo();

	data = new Order();
	data.setId(1);
	data.setCreatedBy("mkyong");
  }

  @Test(expectedExceptions = OrderSaveException.class)
  public void throwIfOrderIsNull() throws OrderSaveException {
	orderBo.save(null);
  }

  /*
   * Example : Multiple expected exceptions
   * Test is success if either of the exception is thrown
   */
  @Test(expectedExceptions = { OrderUpdateException.class, OrderNotFoundException.class })
  public void throwIfOrderIsNotExists() throws OrderUpdateException, OrderNotFoundException {
	orderBo.update(data);
  }

} 

上述单元测试将通过。

下载源代码

Download it – TestNG-Example-Excepted-Exception.zip (11 kb)

参考

  1. TestNG 预期异常 JavaDoc

expected exception testng

TestNG–如何忽略一个测试方法

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-tutorial-3-ignore-test/

在本教程中,我们将向您展示如何用@Test(enabled = false)忽略一个测试方法。

TestIgnore.java

 package com.mkyong.testng.examples.ignore;

import org.testng.Assert;
import org.testng.annotations.Test;

public class TestIgnore {

	@Test //default enable=true
	public void test1() {
		Assert.assertEquals(true, true);
	}

	@Test(enabled = true)
	public void test2() {
		Assert.assertEquals(true, true);
	}

	@Test(enabled = false)
	public void test3() {
		Assert.assertEquals(true, true);
	}

} 

输出

 [TestNG] Running:

PASSED: test1
PASSED: test2

===============================================
    Default test
    Tests run: 2, Failures: 0, Skips: 0
=============================================== 

在上面的例子中,test3 ()测试方法被忽略。

ignore testng (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190227120518/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

TestNG–超时测试

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-tutorial-4-time-test/

在本教程中,我们将向您展示如何在 TestNG 中执行timeout测试。“超时”意味着如果一个单元测试花费的时间超过了指定的毫秒数,TestNG 将会中止它,并将其作为失败处理。

这个“超时”也可以用于性能测试,以确保方法在合理的时间内返回。

TestTimeout.java

 package com.mkyong.testng.examples.timeout;

import org.testng.annotations.Test;

public class TestTimeout {

	@Test(timeOut = 5000) // time in mulliseconds
	public void testThisShouldPass() throws InterruptedException {
		Thread.sleep(4000);
	}

	@Test(timeOut = 1000)
	public void testThisShouldFail() {
		while (true);
	}

} 

输出

 [TestNG] Running:

PASSED: testThisShouldPass
FAILED: testThisShouldFail
org.testng.internal.thread.ThreadTimeoutException: Method org.testng.internal.TestNGMethod.testThisShouldFail() didn't finish within the time-out 1000
	at com.mkyong.testng.examples.timeout.TestTimeout.testThisShouldFail(TestTimeout.java:14)
	at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
	at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
	at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
	at java.lang.reflect.Method.invoke(Unknown Source)
	at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:84)
	at org.testng.internal.InvokeMethodRunnable.runOne(InvokeMethodRunnable.java:46)
	at org.testng.internal.InvokeMethodRunnable.run(InvokeMethodRunnable.java:37)
	at java.util.concurrent.Executors$RunnableAdapter.call(Unknown Source)
	at java.util.concurrent.FutureTask.run(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor.runWorker(Unknown Source)
	at java.util.concurrent.ThreadPoolExecutor$Worker.run(Unknown Source)
	at java.lang.Thread.run(Unknown Source)

===============================================
    Default test
    Tests run: 2, Failures: 1, Skips: 0
=============================================== 

testng timeout (function (i,d,s,o,m,r,c,l,w,q,y,h,g) { var e=d.getElementById(r);if(e=null){ var t = d.createElement(o); t.src = g; t.id = r; t.setAttribute(m, s);t.async = 1;var n=d.getElementsByTagName(o)[0];n.parentNode.insertBefore(t, n); var dt=new Date().getTime(); try{i[l]w+y;}catch(er){i[h]=dt;} } else if(typeof i[c]!'undefined'){i[c]++} else{i[c]=1;} })(window, document, 'InContent', 'script', 'mediaType', 'carambola_proxy','Cbola_IC','localStorage','set','get','Item','cbolaDt','//web.archive.org/web/20190227120240/http://route.carambo.la/inimage/getlayer?pid=myky82&did=112239&wid=0')

TestNG–运行多个测试类(套件测试)

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-tutorial-5-suite-test/

testng-suite-test

在本教程中,我们将向您展示如何一起运行多个 TestNG 测试用例(类),也称为 suite test。

1.测试类

复习以下三个测试类。

TestConfig.java

 package com.mkyong.testng.examples.suite;

import org.testng.annotations.AfterSuite;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;

//show the use of @BeforeSuite and @BeforeTest
public class TestConfig {

	@BeforeSuite
	public void testBeforeSuite() {
		System.out.println("testBeforeSuite()");
	}

	@AfterSuite
	public void testAfterSuite() {
		System.out.println("testAfterSuite()");
	}

	@BeforeTest
	public void testBeforeTest() {
		System.out.println("testBeforeTest()");
	}

	@AfterTest
	public void testAfterTest() {
		System.out.println("testAfterTest()");
	}

} 

TestDatabase.java

 package com.mkyong.testng.examples.suite;

import org.testng.annotations.Test;

public class TestDatabase {

	@Test(groups = "db")
	public void testConnectOracle() {
		System.out.println("testConnectOracle()");
	}

	@Test(groups = "db")
	public void testConnectMsSQL() {
		System.out.println("testConnectMsSQL");
	}

	@Test(groups = "db-nosql")
	public void testConnectMongoDB() {
		System.out.println("testConnectMongoDB");
	}

	@Test(groups = { "db", "brokenTests" })
	public void testConnectMySQL() {
		System.out.println("testConnectMySQL");
	}

} 

TestOrder.java

 package com.mkyong.testng.examples.suite;

import org.testng.annotations.Test;

public class TestOrder {

	@Test(groups={"orderBo", "save"})
	public void testMakeOrder() {  
	  System.out.println("testMakeOrder");
	}  

	@Test(groups={"orderBo", "save"})
	public void testMakeEmptyOrder() {  
	  System.out.println("testMakeEmptyOrder");
	}  

	@Test(groups="orderBo")
	public void testUpdateOrder() {  
		System.out.println("testUpdateOrder");
	}  

	@Test(groups="orderBo")
	public void testFindOrder() {  
		System.out.println("testFindOrder");
	}  

} 

2.Testng.xml

要运行上面的测试类,创建一个 XML 文件-testng.xml(可以是任何文件名)文件,并如下定义细节:

testng.xml

 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestAll">

	<test name="order">
		<classes>
			<class name="com.mkyong.testng.examples.suite.TestConfig" />
			<class name="com.mkyong.testng.examples.suite.TestOrder" />
		</classes>
	</test>

	<test name="database">  
		<classes>
			<class name="com.mkyong.testng.examples.suite.TestConfig" />
			<class name="com.mkyong.testng.examples.suite.TestDatabase" />
		</classes>
	</test>

</suite> 

输出

 [TestNG] Running:
  C:\mkyong_projects\TestNG\src\test\resources\testng-all.xml

testBeforeSuite()

testBeforeTest()
testFindOrder
testMakeEmptyOrder
testMakeOrder
testUpdateOrder
testAfterTest()

testBeforeTest()
testConnectMongoDB
testConnectMsSQL
testConnectMySQL
testConnectOracle()
testAfterTest()

testAfterSuite() 

3.其他示例

下面是一些常用的例子。

3.1 指定包名而不是类名:

testng.xml

 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestAll">

	<test name="order">
		<packages>
			<package name="com.mkyong.testng.examples.suite.*" />
		</packages>
	</test>

</suite> 

3.2 指定包含或排除的方法:

testng.xml

 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestAll">

  <test name="order">
	<classes>
		<class name="com.mkyong.testng.examples.suite.TestConfig" />
		<class name="com.mkyong.testng.examples.suite.TestOrder">
			<methods>
				<include name="testMakeOrder" />
				<include name="testUpdateOrder" />
				<!-- 
					<exclude name="testMakeOrder" />
				 -->
			</methods>
		</class>
	</classes>
  </test>

</suite> 

输出

 [TestNG] Running:
  C:\mkyong_projects\TestNG\src\test\resources\testng.xml

testBeforeSuite()
testBeforeTest()
testMakeOrder
testUpdateOrder
testAfterTest()
testAfterSuite() 

3.3 指定要包括或排除的组:

testng.xml

 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestAll">

  <test name="database">
	<groups>
		<run>
			<exclude name="brokenTests" />
			<include name="db" />
		</run>
	</groups>

	<classes>
		<class name="com.mkyong.testng.examples.suite.TestDatabase" />
	</classes>
  </test>

</suite> 

输出

 [TestNG] Running:
  C:\mkyong_projects\TestNG\src\test\resources\testng.xml

testConnectMsSQL
testConnectOracle() 

参考

  1. TestNG–TestNG . XML 文件

suite test testng

TestNG–参数测试(XML 和@DataProvider)

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-tutorial-6-parameterized-test/

在本教程中,我们将向您展示如何通过 XML @Parameters@DataProvider将参数传递给@Test方法。

1.用 XML 传递参数

在这个例子中,属性 filename 从testng.xml传递,并通过@Parameters注入到方法中。

TestParameterXML.java

 package com.mkyong.testng.examples.parameter;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

import org.testng.annotations.Parameters;
import org.testng.annotations.Test;

public class TestParameterXML {

	Connection con;

	@Test
	@Parameters({ "dbconfig", "poolsize" })
	public void createConnection(String dbconfig, int poolsize) {

		System.out.println("dbconfig : " + dbconfig);
		System.out.println("poolsize : " + poolsize);

		Properties prop = new Properties();
		InputStream input = null;

		try {
		  //get properties file from project classpath
		  input = getClass().getClassLoader().getResourceAsStream(dbconfig);

		  prop.load(input);

		  String drivers = prop.getProperty("jdbc.driver");
		  String connectionURL = prop.getProperty("jdbc.url");
		  String username = prop.getProperty("jdbc.username");
		  String password = prop.getProperty("jdbc.password");

		  System.out.println("drivers : " + drivers);
		  System.out.println("connectionURL : " + connectionURL);
		  System.out.println("username : " + username);
		  System.out.println("password : " + password);

		  Class.forName(drivers);
		  con = DriverManager.getConnection(connectionURL, username, password);

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

	}

} 

db.properties

 jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mkyongserver
jdbc.username=mkyong
jdbc.password=password 

testng.xml

 <!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="test-parameter">

    <test name="example1">

	<parameter name="dbconfig" value="db.properties" />
	<parameter name="poolsize" value="10" />

	<classes>
	  <class name="com.mkyong.testng.examples.parameter.TestParameterXML" />
	</classes>

    </test>

</suite> 

输出

 dbconfig : db.properties
poolsize : 10
drivers : com.mysql.jdbc.Driver
connectionURL : jdbc:mysql://localhost:3306/mkyongserver
username : mkyong
password : password 

2.用@DataProvider 传递参数

2.1 回顾一个简单的@DataProvider例子,传递一个int参数。

TestParameterDataProvider.java

package com.mkyong.testng.examples.parameter;

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TestParameterDataProvider {

	@Test(dataProvider = "provideNumbers")
	public void test(int number, int expected) {
		Assert.assertEquals(number + 10, expected);
	}

	@DataProvider(name = "provideNumbers")
	public Object[][] provideData() {

		return new Object[][] { 
			{ 10, 20 }, 
			{ 100, 110 }, 
			{ 200, 210 } 
		};
	}

}

输出

 PASSED: test(10, 20)
PASSED: test(100, 110)
PASSED: test(200, 210) 

2.2@DataProvider是传递一个object参数的支持。下面的例子展示了如何传递一个Map对象作为参数。

TestParameterDataProvider.java

 package com.mkyong.testng.examples.parameter;

import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Properties;

import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TestParameterDataProvider {

	@Test(dataProvider = "dbconfig")
	public void testConnection(Map<String, String> map) {

		for (Map.Entry<String, String> entry : map.entrySet()) {
		  System.out.println("[Key] : " + entry.getKey() 
                              + " [Value] : " + entry.getValue());
		}

	}

	@DataProvider(name = "dbconfig")
	public Object[][] provideDbConfig() {
		Map<String, String> map = readDbConfig();
		return new Object[][] { { map } };
	}

	public Map<String, String> readDbConfig() {

		Properties prop = new Properties();
		InputStream input = null;
		Map<String, String> map = new HashMap<String, String>();

		try {
		  input = getClass().getClassLoader().getResourceAsStream("db.properties");

		  prop.load(input);

		  map.put("jdbc.driver", prop.getProperty("jdbc.driver"));
		  map.put("jdbc.url", prop.getProperty("jdbc.url"));
		  map.put("jdbc.username", prop.getProperty("jdbc.username"));
		  map.put("jdbc.password", prop.getProperty("jdbc.password"));

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (input != null) {
				try {
					input.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}

		return map;

	}

} 

输出

 [Key] : jdbc.url [Value] : jdbc:mysql://localhost:3306/mkyongserver
[Key] : jdbc.username [Value] : mkyong
[Key] : jdbc.driver [Value] : com.mysql.jdbc.Driver
[Key] : jdbc.password [Value] : password
PASSED: testConnection({jdbc.url=jdbc:mysql://localhost:3306/mkyongserver, 
jdbc.username=mkyong, jdbc.driver=com.mysql.jdbc.Driver, jdbc.password=password}) 

3.@DataProvider +方法

这个例子向您展示了如何根据测试方法的名称来传递不同的参数。

TestParameterDataProvider.java

 package com.mkyong.testng.examples.parameter;

import java.lang.reflect.Method;
import org.testng.Assert;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TestParameterDataProvider {

	@Test(dataProvider = "dataProvider")
	public void test1(int number, int expected) {
		Assert.assertEquals(number, expected);
	}

	@Test(dataProvider = "dataProvider")
	public void test2(String email, String expected) {
		Assert.assertEquals(email, expected);
	}

	@DataProvider(name = "dataProvider")
	public Object[][] provideData(Method method) {

		Object[][] result = null;

		if (method.getName().equals("test1")) {
			result = new Object[][] {
				{ 1, 1 }, { 200, 200 } 
			};
		} else if (method.getName().equals("test2")) {
			result = new Object[][] { 
				{ "test@gmail.com", "test@gmail.com" }, 
				{ "test@yahoo.com", "test@yahoo.com" } 
			};
		}

		return result;

	}

} 

输出

 PASSED: test1(1, 1)
PASSED: test1(200, 200)
PASSED: test2("test@gmail.com", "test@gmail.com")
PASSED: test2("test@yahoo.com", "test@yahoo.com") 

4. @DataProvider + ITestContext

在 TestNG 中,我们可以使用org.testng.ITestContext来确定调用当前测试方法的运行时参数。在最后一个例子中,我们将向您展示如何根据包含的组名来传递参数。

TestParameterDataProvider.java

 package com.mkyong.testng.examples.parameter;

import org.testng.Assert;
import org.testng.ITestContext;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;

public class TestParameterDataProvider {

	@Test(dataProvider = "dataProvider", groups = {"groupA"})
	public void test1(int number) {
		Assert.assertEquals(number, 1);
	}

	@Test(dataProvider = "dataProvider", groups = "groupB")
	public void test2(int number) {
		Assert.assertEquals(number, 2);
	}

	@DataProvider(name = "dataProvider")
	public Object[][] provideData(ITestContext context) {

		Object[][] result = null;

		//get test name
		//System.out.println(context.getName());

		for (String group : context.getIncludedGroups()) {

			System.out.println("group : " + group);

			if ("groupA".equals(group)) {
				result = new Object[][] { { 1 } };
				break;
			}

		}

		if (result == null) {
			result = new Object[][] { { 2 } };
		}
		return result;

	}

} 

testng.xml

 <!DOCTYPE suite SYSTEM "http://beust.com/testng/testng-1.0.dtd" >
<suite name="test-parameter">

  <test name="example1">

	<groups>
		<run>
			<include name="groupA" />
		</run>
	</groups>

	<classes>
	   <class
	    name="com.mkyong.testng.examples.parameter.TestParameterDataProvider" />
	</classes>

  </test>

</suite> 

输出

 group : groupA 

完成了。

参考

  1. TestNG @DataProvider
  2. TestNG ITestContext JavaDoc
  3. 使用 JDBC 驱动程序连接 MySQL】

parameter test testng

TestNG–依赖性测试

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/unittest/testng-tutorial-7-dependency-test/

在 TestNG 中,我们使用dependOnMethodsdependsOnGroups来实现依赖测试。如果一个从属方法失败,所有后续的测试方法将被跳过,而不是失败。

1.dependOnMethods 示例

一个简单的例子,“方法 2()”依赖于“方法 1()”。

1.1 如果method1()通过,将执行method2()

App.java

 package com.mkyong.testng.examples.dependency;

import org.testng.annotations.Test;

public class App {

	@Test
	public void method1() {
		System.out.println("This is method 1");
	}

	@Test(dependsOnMethods = { "method1" })
	public void method2() {
		System.out.println("This is method 2");
	}

} 

输出

 This is method 1
This is method 2
PASSED: method1
PASSED: method2

===============================================
    Default test
    Tests run: 2, Failures: 0, Skips: 0
=============================================== 

1.2 如果method1()失败,method2()将被跳过。

App.java

 package com.mkyong.testng.examples.dependency;

import org.testng.annotations.Test;

public class App {

	//This test will be failed.
	@Test
	public void method1() {
		System.out.println("This is method 1");
		throw new RuntimeException();
	}

	@Test(dependsOnMethods = { "method1" })
	public void method2() {
		System.out.println("This is method 2");
	}

} 

输出

 This is method 1
FAILED: method1
java.lang.RuntimeException
	at com.mkyong.testng.examples.dependency.App.method1(App.java:10)
	//...

SKIPPED: method2

===============================================
    Default test
    Tests run: 2, Failures: 1, Skips: 1
=============================================== 

2.dependsOnGroups 示例

让我们创建几个测试用例来演示dependsOnMethodsdependsOnGroups的混合使用。不言自明的见注释。

TestServer.java

 package com.mkyong.testng.examples.dependency;

import org.testng.annotations.Test;

//all methods of this class are belong to "deploy" group.
@Test(groups="deploy")
public class TestServer {

	@Test
	public void deployServer() {
		System.out.println("Deploying Server...");
	}

	//Run this if deployServer() is passed.
	@Test(dependsOnMethods="deployServer")
	public void deployBackUpServer() {
		System.out.println("Deploying Backup Server...");
	}

} 

TestDatabase.java

 package com.mkyong.testng.examples.dependency;

import org.testng.annotations.Test;

public class TestDatabase {

	//belong to "db" group, 
	//Run if all methods from "deploy" group are passed.
	@Test(groups="db", dependsOnGroups="deploy")
	public void initDB() {
		System.out.println("This is initDB()");
	}

	//belong to "db" group,
	//Run if "initDB" method is passed.
	@Test(dependsOnMethods = { "initDB" }, groups="db")
	public void testConnection() {
		System.out.println("This is testConnection()");
	}

} 

TestApp.java

 package com.mkyong.testng.examples.dependency;

import org.testng.annotations.Test;

public class TestApp {

	//Run if all methods from "deploy" and "db" groups are passed.
	@Test(dependsOnGroups={"deploy","db"})
	public void method1() {
		System.out.println("This is method 1");
		//throw new RuntimeException();
	}

	//Run if method1() is passed.
	@Test(dependsOnMethods = { "method1" })
	public void method2() {
		System.out.println("This is method 2");
	}

} 

创建一个 XML 文件并一起测试它们。

testng.xml

 <!DOCTYPE suite SYSTEM "http://testng.org/testng-1.0.dtd" >

<suite name="TestDependency">

  <test name="TestCase1">

	<classes>
	  <class 
		name="com.mkyong.testng.examples.dependency.TestApp">
	  </class>
	  <class 
		name="com.mkyong.testng.examples.dependency.TestDatabase">
	  </class>
	  <class 
		name="com.mkyong.testng.examples.dependency.TestServer">
	  </class>
	</classes>

  </test>

</suite> 

输出

 Deploying Server...
Deploying Backup Server...
This is initDB()
This is testConnection()
This is method 1
This is method 2

===============================================
TestDependency
Total tests run: 6, Failures: 0, Skips: 0
=============================================== 

testng-dependency-test ## 参考

  1. 测试依赖方法

dependency test testng

TestNG 教程

原文:http://web.archive.org/web/20230101150211/https://mkyong.com/tutorials/testng-tutorials/

testng tutorials

TestNG(下一代)是一个测试框架,受 JUnitNUnit 的启发,但引入了许多新的创新功能,如依赖测试、分组概念,使测试更强大、更容易。它旨在涵盖所有类别的测试:单元、功能、端到端、集成等…

1.测试教程

  • TestNG–Hello World 示例
    开始使用 TestNG,创建一个简单的测试用例以及如何执行它。
  • 这个例子向您展示了 TestNG 中支持的配置注释列表。
  • TestNG–预期异常测试
    这个例子展示了如何进行异常测试–@Test(expectedExceptions = ?)
  • 这个例子向你展示了如何启用和禁用一个测试方法-@Test(enabled = true)
  • TestNG–超时测试
    确保测试方法必须在规定的时间内完成-@Test(timeOut = 5000)
  • TestNG–分组测试
    这个例子向你展示了如何进行分组测试——@Test(groups= ?)@Test(dependsOnGroups - ?)
  • 这个例子向你展示了如何使用testng.xml运行多个测试类。
  • 这个例子向你展示了如何使用dependOnMethodsdependsOnGroups来实现依赖测试。
  • TestNG–参数测试(XML 和 DataProvider)
    这个例子展示了如何用XML@DataProvider将参数传递给测试方法。
  • TestNG–参数测试(DataProvider)
    又一个@DataProvider的例子。
  • 这个例子向你展示了如何使用 Selenium 在一个网站上执行负载测试。
  • 这个例子向你展示了如何用 TestNG 测试 Spring 组件。
  • JUnit 4 与 TestNG 的对比
    JUnit 4 与 TestNG 的详细特性对比。

参考

  1. TestNG 官网

Struts

原文:http://web.archive.org/web/20230101150211/http://www.mkyong.com/struts/struts-htmltextarea-textarea-example/

Download this Struts text area example – Struts-TextArea-Example.zip

在这个 Struts 示例中,您将学习如何使用 Struts

1.文件夹结构

这是 Maven 创建的最终项目结构。请创建相应的文件夹。

Struts-textarea-folder

2.动作类

创建一个 Action 类,除了转发请求什么也不做。

html text reaction . Java

 package com.mkyong.common.action;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;

import com.mkyong.common.form.HtmlTextAreaForm;

public class HtmlTextAreaAction extends Action{

	public ActionForward execute(ActionMapping mapping,ActionForm form,
			HttpServletRequest request,HttpServletResponse response) 
        throws Exception {

	   HtmlTextAreaForm htmlTextAreaForm = (HtmlTextAreaForm)form;

	   return mapping.findForward("success");
	}

} 

3.属性文件

创建一个属性文件,并声明错误和标签消息。

公共属性

 #error message
error.common.html.textarea.required = "Address" field is required.

#label message
label.common.html.textarea.address = Address 
label.common.html.textarea.button.submit = Submit
label.common.html.textarea.button.reset = Reset 

4.动作形式

创建一个 ActionForm,包含一个地址变量来保存文本区域的输入值。

HtmlTextAreaForm.java

 package com.mkyong.common.form;

import javax.servlet.http.HttpServletRequest;

import org.apache.struts.action.ActionErrors;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionMapping;
import org.apache.struts.action.ActionMessage;

public class HtmlTextAreaForm extends ActionForm{

	String address;

	public String getAddress() {
		return address;
	}

	public void setAddress(String address) {
		this.address = address;
	}

	@Override
	public ActionErrors validate(ActionMapping mapping,
		HttpServletRequest request) {

	    ActionErrors errors = new ActionErrors();

	    if( getAddress() == null || ("".equals(getAddress())))
	    {
	       errors.add("common.textarea.err",
	    	new ActionMessage("error.common.html.textarea.required"));
	    }

	    return errors;
	}

	@Override
	public void reset(ActionMapping mapping, HttpServletRequest request) {
		// reset properties
		address = "";
	}

} 

5.JSP 页面

使用 Struts HTML 标签

textarea.jsp

<%@taglib uri="http://struts.apache.org/tags-html" prefix="html"%>
<%@taglib uri="http://struts.apache.org/tags-bean" prefix="bean"%>

Struts html:textarea 示例

:
posted @ 2024-11-01 16:32  绝不原创的飞龙  阅读(3)  评论(0编辑  收藏  举报