1. 程式人生 > >struts2框架學習筆記1:搭建測試

struts2框架學習筆記1:搭建測試

method lang app org char 示例 重要 type img

Servlet是線程不安全的,Struts1是基於Servlet的框架

而Struts2是基於Filter的框架,解決了線程安全問題

因此Struts1和Struts2基本沒有關系,只是創造者取名問題

接下來搭建並測試

下載Struts2:https://struts.apache.org/

解壓後目錄如下:

技術分享圖片

apps中的是示例、docs是文檔、lib是類庫、src是源碼

導包不需要導入lib中全部的包,導入這些即可

技術分享圖片

簡單寫一個Action類:

package hello;

public class HelloAction {
    
    public String hello(){
        System.out.println(
"hello world!"); return "success"; } }

導入dtd約束,這裏可以省略,只是在編寫配置文件的時候沒有提示,全憑手打易出錯

配置文件: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="hello" namespace="/hello" extends="struts-default" > <action name="HelloAction" class="hello.HelloAction" method="hello" > <result name="success">/hello.jsp</result> </action> </package> </struts>

下一步至關重要,配置web.xml:

由於Struts2是基於Filter的框架,所以必須配置web.xml:

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

一個jsp文件hello.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>hello world!</h1>
</body>
</html>

到這裏框架搭建完成!

部署到Tomcat服務器,本地測試:

技術分享圖片

並且在控制臺打印hello world!

測試成功!!

流程分析:

1.瀏覽器中訪問....../hello/HelloAction

2.請求交到web.xml的Struts2過濾器,匹配hello和HelloAction

3.過濾器去尋找核心配置文件,/hello匹配namespace屬性成功,於是尋找HelloAction類

4.找到HelloAction類,創建出Action對象,調用類的hello方法,打印hello world,返回"success"

5.返回值找到result標簽的name屬性,匹配成功,轉發到hello.jsp

6.最終前端頁面顯示如圖

struts2框架學習筆記1:搭建測試