Struts2入门--环境搭建(IDEA版)
1、搭建 struts2 项目步骤
- 新建Java项目—输入项目名称/项目路径
- 目录结构如下:将lib文件夹复制到web-inf下(否则发布不到Tomcat)
- 配置web.xml(filter-class中需与导入的Struts2的jar包中的一致,此处删除了.ng)
- 配置Struts.xml(IDEA创建Struts2项目会自动生成)
- 修改index.jsp
- 运行成功
2、添加页面
编写 Action 类—HelloAction(在src下创建cn.ht.action.HelloAction类)
package cn.ht.action;
/**
- @Classname HelloAction
- @Description TODO
- @Date 2019-8-12 16:12
- @Created by Administrator
- Struts2的第一个案例
*/
public class HelloAction {
// 在Struts2中,所有的业务方法都是public
// 返回值都为string类型,所有业务方法都没有参数
// 方法名可以自定义,默认为execute
public String execute(){
}System.out.println("hello struts2");
return "success";
}
注:在 servlet 中,默认执行 service 方法。在 struts2 中,默认执行 execute 方法。
在 servlet 中,service 方法参数时 HttpServletRequest 和 HttpServletResponse,无返回
值。在 struts2 中,方法都是 public 的,并且返回值都是 String 类型,而且方法都是没
有参数的。
配置 action 类—在 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">
<package name="default" namespace="/" extends="struts-default">
<!--配置action
配置url和处理类的方法进行映射
-->
<action name="hello" class="cn.ht.action.HelloAction">
<result>/hello.jsp</result>
</action>
</package>
</struts>
- 配置 struts2 的核心控制器 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">
<!--配置Struts2的前端控制器-->
<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>*.action</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
- 访问:http://localhost:8080/StrutsTest\_war\_exploded/hello.action
结果:
转载于//www.cnblogs.com/Anemia-BOY/p/11341163.html
还没有评论,来说两句吧...