先在myeclipse中创建WebProject(web工程)
首先需要导入的struts2的jar包,我的是struts2.3的,从struts2官网下载的。
一个也别少,少了控制台立马报错!
然后去web.xml中添加以下内容
<!-- Struts2配置 -->
<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>
然后在src下创建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>
<package name="struts2" extends="struts-default">
<action name="HelloWorld" class="com.boco.HelloWorld" method="execute">
<result name="HelloWorld">/HelloWorld.jsp</result>
</action>
<action name="HelloChina" class="com.boco.HelloWorld" method="execute1">
<result name="HelloChina">/HelloChina.jsp</result>
</action>
</package>
</struts>
然后去写java类,也就是struts2中的action,HelloWorld.java
package com.boco;
public class HelloWorld {
public final static String MESSAGE = "世界你好,Struts2你好";
public final static String MESSAGE2 = "中国你好,Struts2你好";
private String message;
/**
* @return the message
*/
public String getMessage() {
return message;
}
/**
* @param message
* the message to set
*/
public void setMessage(String message) {
this.message = message;
}
/**
* 世界你好
*
* @return
* @throws Exception
*/
public String execute() throws Exception {
setMessage(MESSAGE);
return "helloWorld";
}
/**
* @return 中国你好
* @throws Exception
*/
public String execute1() throws Exception {
setMessage(MESSAGE2);
return "HelloChina";
}
}
最后在WebRoot下创建两个页面
HelloChina.jsp页面
内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Hello China!</title>
</head>
<body>
<h2>
<s:property value="message" />
</h2>
</body>
</html>
HelloWorld.jsp页面
内容如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<%@ taglib prefix="s" uri="/struts-tags"%>
<html>
<head>
<title>Hello World!</title>
</head>
<body>
<h2>
<s:property value="message" />
</h2>
</body>
</html>
这样就可以了。
部署到tomcat上,分别在浏览器地址栏输入以下两个地址
http://localhost:8080/Struts2Sample/HelloChina
http://localhost:8080/Struts2Sample/HelloWorld
可以看到页面有值。其中Struts2Sample为项目名称