一、创建JavaWeb项目
1.加入搭建Struts2 FrameWork开发环境的必需Jar包[可以在网上下载Struts,地址:http://down7.pc6.com/xy3/struts2.zip,解压找到下面的包]
2.在【src】目录下的“struts.xml”文件
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.5//EN" "http://struts.apache.org/dtds/struts-2.5.dtd"> <struts> <constant name="struts.devMode" value="true" /> <package name="Hello_World_Struts2" extends="struts-default"> <action name="index"> <result>/index.jsp</result> </action> </package> </struts>
3.在【web.xml】文件中配置Struts2的核心过滤器(红色部分)
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" version="3.1"> <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>
三、创建Model类MessageStore
在项目的src文件夹下添加一个“MessageStore.java”文件,放到“org.benTigerKin.model”这个包中
public class MessageStore { private String message; public MessageStore(String msg){ this.setMessage(msg); } public String getMessage() { return message; } public void setMessage(String message) { this.message = message; } }
四、创建Action类HelloWorldAction,充当Controller
在项目的src文件夹下添加一个“HelloWorldAction.java”文件,到“org.benTigerKin.action”这个包中
public class HelloWorldAction extends ActionSupport { private MessageStore msgStore; @Override public String execute() throws Exception { msgStore = new MessageStore("HelloWorld!"); return SUCCESS; } public MessageStore getMsgStore() { return msgStore; } public void setMsgStore(MessageStore msgStore) { this.msgStore = msgStore; } }
五、创建View(视图)HelloWorld.jsp
在【WebRoot】文件夹下创建“HelloWorld.jsp”文件
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>欢迎welcom for you </title> </head> <body> <h2>欢迎进入helloWorld页面<s:property value="msgStore.message" /></h2> </body> </html>
六、配置struts.xml
在struts.xml中加入红色部分的配置信息
<struts> <constant name="struts.devMode" value="true" /> <package name="Hello_World_Struts2" extends="struts-default"> <action name="index"> <result>/index.jsp</result> </action> <action name="hello" class="com.benTigerKin.action.HelloWordAction" method="execute"> <result name="success">/helloWorld.jsp</result> </action> </package> </struts>
七、创建Action的URL链接
在index.jsp中添加Action的URL链接
<%@ page contentType="text/html;charset=UTF-8" language="java" %> <%@ taglib prefix="s" uri="/struts-tags" %> <html> <head> <title>index 页面</title> </head> <body>你好!!<a href="<s:url action='hello'/>">Hello World</a> </body> </html>
八、部署运行
将项目发布到Idea的Tomcat服务器中,如下图所示:
九、预览
打开浏览器,在浏览器中输入http://localhost:8080/Hello_World_Struts2/index.action
补充:整个目录结构如下: