index.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%--设置浏览器的页面编码 --%>
<%--设置JSP编译成Servlet时使用的编码,可以只写这一句 --%>
<!DOCTYPE html>
<html>
<head>
<%--规定 HTML 文档的字符编码 --%>
<meta charset="UTF-8">
<title>Struct2的入门案例</title>
</head>
<body>
<a href="${pageContext.request.contextPath }/hello">访问第一个struts2应用</a>
</body>
</html>
success.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%--设置浏览器的页面编码 --%>
<%--设置JSP编译成Servlet时使用的编码,可以只写这一句 --%>
<!DOCTYPE html>
<html>
<head>
<%--规定 HTML 文档的字符编码 --%>
<meta charset="UTF-8">
<title>执行结果</title>
</head>
<body>
执行成功
</body>
</html>
HelloAction.java
package com.itheima.web.action;
/*
* 我们的第一个动作类
*
* 动作类:就是一个概念,它就是struts2框架中用于处理请求的类
* 我们处理请求都用动作类
* */
public class HelloAction {
/*
* 我们第一个动作方法
* 动作类中用于处理动作请求的方法
*
* 编写规范
* 1.访问修饰符都是public
* 2.方法的返回值一般都是String,可以是void,return null就可以替代void
* 3.方法没有参数
* */
public String sayHello() {
System.out.println("sayhello已执行");
return "success";
}
}
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="p1" extends="struts-default">
<action name="hello" class="com.itheima.web.action.HelloAction" method="sayHello">
<result name="success" type="dispatcher">/success.jsp</result>
</action>
</package>
</struts>
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID" version="2.5">
<display-name>day59_01struts</display-name>
<!-- 配置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>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
注意struts.xml中映射文件的路径是.
赋值的路径是/
导致白忙一小时
执行流程
starUML时序图
- struts的核心控制器默认会处理以.action为后缀的url,或者是没有后缀的url
<a href="${pageContext.request.contextPath }/hello.action">访问第一个struts2应用</a>
<a href="${pageContext.request.contextPath }/hello">访问第一个struts2应用</a>
每个线程任何实例都会重新初始化,不会有线程安全,但是servlet是单例,不可以这么定义
执行时序
执行流程