参考这个博客搭建:
Struts2快速入门与使用IntelliJ IDEA创建第一个web项目
需要注意几点:
1)可能会遇到struts-default高亮变红的情况,其实是没有把struts-default.xml加入到Default File Set
解决办法:
2)注意struts的版本,2.3有ng,2.5没有
3)注意要进行部署操作
4)加载TOMCAT的时候要记得配置Deployment
5)注意各个文件的路径,库文件的加载
在这个实例中,我把namespace="/hello",也就是当执行HelloAction的sayHi这个ACTION方法之后,如果返回success状态,那么又因为在上面配置的namespace=hello
,页面跳转时寻找规则为web/namespace/xxx.jsp,也即是:
web/hello/sayHi.jsp
因此我们在浏览器输入http://localhost:8080/hello/sayHi
访问项目
通过浏览器访问http://localhost:8080/hello/sayHi
,控制台会打印HelloAction
中的hello world
,同时页面会跳转到struts.xml
中配置的sayHi.jsp
页面,页面显示之前写的SayHi
文字。
struts.xml
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd">
<struts>
<package name="hello" namespace="/hello" extends="struts-default">
<action name="sayHi" class="com.southstar.demo.HelloAction" method="sayHi">
<result name="success">sayHi.jsp</result>
</action>
</package>
</struts>
web.xml
<?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_4_0.xsd"
version="4.0">
<display-name>Struts Blank</display-name>
<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>
Action
package com.southstar.demo;
public class HelloAction {
public String sayHi() {
System.out.println("hello world");
return "success";
}
}
sayHi.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
没鱼,SB
</body>
</html>
至此,一个完整的简单struts实例,创建完成!