最近跟着struts2文档学习了一下,英文实在是很折磨人,不过感觉上面的代码还可以,自己留着用,也可以大家看看。
简单的建立struts2的环境,首先下载struts2的一个版本,不是最新版也可以,然后解压找到apps目录,里面放着的是struts2的一些示例应用,随便打开一个,把里面的jar文件复制到你建立的web项目中的/WEB-INF/lib目录下。
下面是配置web.xml文件,增加struts2的核心Filterp配置,代码段如下,当然不用记住,直接在前面解压找到的例子中复制一个即可。
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
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">
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<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>
下面我们在Web应用的类加载路径下即src目录下建立一个struts.xml文件,配置如下,
Struts2提供了UI标签,使用它建立一个简单的index.jsp页面,当然要使用标签必须使用taglib指令导入标签库支持。
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>hello world</title>
</head>
<body>
<h2>This is my first struts application</h2>
<s:form action="helloWorld" method="post">
<s:textfield name="userName" label="User Name:" />
<s:submit value="Submit" />
</s:form>
</body>
</html>
然后我们来写HelloWorld类,这里我们只需要实现execute方法即可,并设置一些简单的信息。
package com.zcl.struts.helloworld;
public class HelloWorld {
private String userName ;
private String message ;
public String execute(){
this.setMessage("Hello " + this.getUserName()) ;
return "success" ;
}
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
下面是成功显示页面,页面接收message的值并显示出来
<%@ page language="java" import="java.util.*" pageEncoding="GB18030"%>
<%@ taglib prefix="s" uri="/struts-tags" %>
<html>
<head>
<title>hello world</title>
</head>
<body>
<h2>The success page</h2>
<h3>message:<s:property value="message"/></h3>
</body>
</html>
下面我们开始配置struts.xml文件,我们可以根据模版进行配置
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
<struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.i18n.encoding" value="GBK" />
<package name="hello" extends="struts-default">
<action name="helloWorld" class="com.zcl.struts.helloworld.HelloWorld" method="execute">
<result name="success">/success.jsp</result>
</action>
</package>
</struts>
上面其实配置很简单,慢慢的就熟悉了。
ok这样加载到tomcat即可运行了效果如下:
提交后:
对了我的myeclipse目录结构:
如果大家不想手动建立开发环境的画,直接在myeclipse下自动添加struts2支持即可。
选择项目单击右键--》找到myeclipse--》添加struts支持,选择struts2即可。