Struts2的流程配置
该应用是用户输入用户名,然后action跳转到其他的页面将其显示,如果输入的为空或者没输入用户名,action将其定位到原页面。开发环境为MyEclipse
- 新建Web Project.
- 将Struts2所需的jar包拷贝到WebRoot——>WEB-INF——>lib文件夹中。
- 打开WEB-INF文件下的web.xml,添加filter,filter的代码如下:<filter>
<filter-name>struts2</filter-name> <filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class> </filter> <filter-mapping> <filter-name>struts2</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
- 在src目录下,新建struts.xml。其最原始的内容为:<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> </struts>
- 在src目录下,新建action,其存放位置为com.action.HelloAction。其代码如下:package com.action;
import com.opensymphony.xwork2.ActionSupport; public class HelloAction extends ActionSupport { public String username; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } @Override public String execute() throws Exception { if(username == null || username.equals("")){ return INPUT; }else{ return SUCCESS; } } }
- 在struts.xml中注册action。其代码如下:<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <package name="default"> <action name="HelloAction" class="com.action.HelloAction"> <result name="success">result.jsp</result> <result name="input">index.jsp</result> </action> </package> </struts>
- 新建jsp页面,本应用所需的jsp页面如下:
- index.jsp:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> </head> <body> <s:form theme="simple"> username:<s:textfield></s:textfield> <s:submit value="submit"></s:submit> </s:form> </body> </html>
- result.jsp:<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ taglib prefix="s" uri="/struts-tags"%> <html> <head> <title>My JSP 'result.jsp' starting page</title> </head> <body> Welcome to Struts2 world!!! </body> </html>
- 配置后的struts.xml的代码如下:<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1.7//EN" "http://struts.apache.org/dtds/struts-2.1.7.dtd"> <struts> <package name="default" extends="struts-default"> <action name="HelloAction" class="com.action.HelloAction"> <result name="success">result.jsp</result> <result name="input">index.jsp</result> </action> </package> </struts>