Struts2入门

1-1 Struts2入门概述

课程目标

01 Struts2的概念

02 MVC

03 Struts的发展历史

04 第一个Struts2例子

05 Struts2的工作原理及文件结构

06 深入讲解Struts2的用法

一、Struts2的概念

  • Struts2是Java程序员所必须学习的一门课程。
  • Struts的英文单词是什么意思?

          翻译:支柱、枝干,来源于建筑和旧式飞机使用的金属支架

  • Struts在软件开发中,是一个非常优秀的框架。
  • Struts是什么?

  Struts是流行和成熟的基于MVC设计模式的Web应用程序框架。

  • 使用Struts的目的:

  为了帮助我们减少在运用MVC设计模型来开发Web应用的时间。

二、MVC模式

  • MVC模式是什么?
  • MVC模式的发展过程

  JSP+JavaBean=Model1 这种模式使用于小型网站的开发

  JSP+Servlet+JavaBean=Model2 最典型的MVC

  • MVC的定义是什么?

  MVC是模型视图控制器(Model View Controller),一种软件设计典范,用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面,在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑。

  • MVC的流程:

在Sturts中Controller就是Action。

三、Struts2的发展历史

2001年发布Sturts1

2007年发布Sturts2(在WebWork框架上进行升级的)

Sturts2不是一个全新的框架,因此稳定性、性能等各方面都有很好的保证,同时吸收了Sturts1和WebWork两者的优势。

四、第一个Sturts2例子

  • Apache Sturts2的环境需求如下:

Servlet API 2.4

JSP API 2.0

Java 5

  • 需要提醒的是,在Sturts2中会用到Annotation,所以请将JDK版本升级到1.5.
  • 搭建Sturts2环境步骤

  下载相关jar包(下载地址(Apache Sturts官方网站): http://Sturts.apache.org/   和 http://people.apache.org/builds/Sturts/)

  创建Web项目

  创建并完善相关配置文件

  创建Action并测试启动

1.导入相关jar包:

2.配置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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>HelloWorld</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>  
  
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>

3.创建并完善相关配置文件 

创建Struts的核心文件 XML File

核心文件: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">

<struts>
	<!-- 默认的包名、命名空间/、扩展选择默认 -->
	<package name="default" namespace="/" extends="struts-default">
		<action name="helloworld" class="com.imooc.action.HelloWorldAction">
			<!-- return SUCCESS -->
			<result>/result.jsp</result>
		</action>
	</package>

</struts>

4.创建Action并测试启动HelloWorldAction.java

package com.imooc.action;

import com.opensymphony.xwork2.ActionSupport;

@SuppressWarnings("serial")
public class HelloWorldAction extends ActionSupport {

	@Override
	public String execute() throws Exception {
		System.out.println("执行Action");
		return SUCCESS;
	}
}

 测试结果:

原文地址:https://www.cnblogs.com/songsongblue/p/9526851.html