Struts2篇

一、Struts2概述

Struts2是Apache发行的MVC开源框架。它只是表现层web(MVC)框架。

二、Struts2环境搭建

  • 导jar包

将Struts2开发包下常用jar包复制到web项目的lib文件夹下

  • 添加配置文件

在src文件夹下新建struts.xml文件,内容如下,<struts>标签中的内容我们后面再进行编写。

<?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>

</struts>
  • 配置struts过滤器

web.xml中,配置Filter,配置的目的是用于拦截请求,由Struts的规则去处理请求,而不是用以前的servlet去处理。

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>Struts2Demo</display-name>
  
  <!-- 配置struts的过滤器 【拦截所有请求】-->
  <filter>
     <filter-name>struts2</filter-name>
     <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
  </filter>
  
  <!-- struts过滤器拦截请求的规则 -->
  <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>
  • Tomcat运行web工程

运行Tomcat,若无报错,则代表struts环境配置无误。

三、Struts的Action配置讲解

下面将在struts环境配置好后的基础上实例一个demo。

1、新建包和类,并写一个sayHello()方法

2、在struts.xml中配置package和action,写如下代码

<?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:包名,在struts.xml文件不能有相同的包名,包名是惟一
		    extends:继承,固定struts-default
	action:动作
			name:相当于Servlet的映射路径(@WebServlet)
			class:处理请求的类,相当一个Servlet类
			method:处理请求的方法
	
	result:结果,写返回的jsp页面
	 -->
	<package name="p1" extends="struts-default">
		<action name="hello" class="com.hedong.helloStruts.helloAction" method="sayHello">
			<result name="success">/success.jsp</result>
		</action>
	</package>
</struts>

3、在WebContent下新建success.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
hello! Struts2.
</body>
</html>

4、在浏览器地址栏中输入http://localhost:8080/Struts2Demo/hello,即可正常打开success.jsp页面。

四、流程分析

  1. tomcat启动,加载web.xml
  2. 实例化并初始化过滤器
  3. 加载struts.xml配置文件
  4. 客户端发送请求:hello
  5. 请求到达过滤器
  6. 截取请求的动作名称name,并在struts.xml中找到对应动作
  7. 找到动作后实例化动作类
  8. 调用对应的动作方法method,方法有返回值
  9. 根据返回值找到name取值对应的结果视图,即对应的success.jsp页面
  10. 响应浏览器,展示结果

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章