第一步
第二步
第三步
进入项目目录后,在web/WEB-INF下新建lib文件夹,同时将在上一节整理的struts2开发包拷入lib文件,之后,右键lib目录,选择Add as library选项,将开发包配置好。如下:
jar包下载连接:https://pan.baidu.com/s/1w6NZRVr6LIMpQusVvpw64w
提取码:5034
第四步
打开web/WEB-INF中的web.xml,配置filter,这个就是之前提到过的前端控制器。如下:
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
这里注意:struts2每个版本不同org.apache.struts2.dispatcher.filter.StrutsPrepareAndExecuteFilter
路径地址不一样,具体请根据版本的不同书写正确的拦截器路径地址
第五步
在项目目录src下新建包com.happy.demo,新建HelloAction.java,代码如下:
public class HelloAction {
public String sayHi() {
System.out.println("hello world");
return "success";
}
}
第六步
打开项目目录下的struts.xml,将刚编写的HelloAction进行配置,如下:
<struts>
<package name="hello" namespace="/hello" extends="struts-default">
<action name="sayHi" class="com.happy.demo.HelloAction" method="sayHi">
<result name="success">sayHi.jsp</result>
</action>
</package>
</struts>
如struts-default报红请参考:https://blog.youkuaiyun.com/weixin_41060905/article/details/82872737
里面有解决方法
第七步
在上面xml配置中,通过result标签配置了当success时跳转的页面sayHi.jsp,下面我们就来新建这个页面。
又因为在上面配置的namespace=hello,页面跳转时寻找规则为web/namespace/xxx.jsp,所以,在web目录下,新建hello文件夹,并新建sayHi.jsp文件。详细如下:
sayHi.jsp内容如下:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>SayHi</h1>
</body>
</html>
通过浏览器访问http://localhost:8080/hello/sayHi,可控制台会打印HelloAction中的hello world,同时页面会跳转到struts.xml中配置的sayHi.jsp页面,页面显示之前写的SayHi文字。