Struts2 入门实例

Struts2 入门实例

更多请看  (www.omob.cc)

导包

web.xml

在web.xml中添加struts2监听器,使struts可以拦截Request

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xmlns="http://java.sun.com/xml/ns/javaee"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
	id="WebApp_ID" version="2.5">
	<display-name>day46_Struts2_01_hello</display-name>
	<welcome-file-list>
		<welcome-file>hello.jsp</welcome-file>
		<welcome-file>index.htm</welcome-file>
		<welcome-file>index.jsp</welcome-file>
		<welcome-file>default.html</welcome-file>
		<welcome-file>default.htm</welcome-file>
		<welcome-file>default.jsp</welcome-file>
	</welcome-file-list>

	<!-- 过滤器,拦截请求,将请求交给struts来处理 -->
	<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>
</web-app>

struts.xml

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

<struts>
	<!-- 打开开发模式,当修改了这个文件,不需要重启就有效果 -->
    <constant name="struts.devMode" value="true" />
    <!-- 默认继承自struts-default -->
    <package name="default" namespace="/" extends="struts-default">
    	<!-- 配置请求url和处理类的映射关系,默认调用execute方法-->
        <action name="hello" class="com.qianfeng.action.HelloAction">
        	<result name="success">/ok.jsp</result>
        </action>
    </package>

</struts>

写Action

第一种

package com.qianfeng.action;

/**
 * 第一种实现方式:普通的java类--解耦
 * @author ASUS
 *
 */
public class HelloAction {
	public HelloAction(){
		System.out.println("创建了一个HelloAction对象....");
	}
	
	//规则
	public String execute(){
		System.out.println("execute");
		return "success";
	} 
	
	//规则
	public String other(){
		System.out.println("other");
		return "success";
	} 
}

第二种

package com.qianfeng.action;

import com.opensymphony.xwork2.Action;

/**
 * 第二种实现方式:实现一个接口
 * @author ASUS
 *
 */
public class HelloAction2 implements Action{
	public HelloAction2(){
		System.out.println("创建了一个HelloAction2对象....");
	}
	
	//规则
	public String execute(){
		System.out.println("execute");
		return Action.SUCCESS;
	} 
	
	//规则
	public String other(){
		System.out.println("other");
		return Action.SUCCESS;
	} 
}

第三种

package com.qianfeng.action;

import com.opensymphony.xwork2.ActionSupport;

/**
 * 第三种实现方式:继承一个类
 * ActionSupport 校验,国际化
 * @author ASUS
 *
 */
public class HelloAction3 extends ActionSupport{
	public HelloAction3(){
		System.out.println("创建了一个HelloAction3对象....");
	}
	
	//规则
	public String execute(){
		System.out.println("execute");
		return SUCCESS;
	} 
	
	//规则
	public String other(){
		System.out.println("other");
		return SUCCESS;
	} 
}

猜你喜欢

转载自blog.csdn.net/thinktik/article/details/80946426