struts2-byblank案例练习(一)

前言:本文为一个最简单的struts2案例,意在熟悉struts2主干线流程,后续练习会逐步拓展案例功能

一,创建项目

  1 新建动态web工程,目录如下:

 

   2 配置web.xml,找到struts2-core-2.3.34.jar中,StrutsPrepareAndExecuteFilter.class,拷贝全路径,配置成过滤器。   

<?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>struts2-byblank</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
  </welcome-file-list>
  
  <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>
</web-app>

  3 新建index.html

<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8" http-equiv="refresh" content="2;url=HelloWorld.action">
<title>index</title>
</head>
<body>
    <h1>欢迎进入首页,2秒后自动进入HelloWord界面!</h1>
</body>
</html>

  

  4 配置struts.xml,位于工程src下。解压struts2-core-2.3.34.jar,找到struts2-default.xml,拷贝头引用,创建struts.xml,配置一个package,继承struts-default。

<?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="default" namespace="/" extends="struts-default">
        <action name="HelloWorld">
            <result>HelloWorld.jsp</result>
        </action>
    </package>
</struts>

 

  5 新建 HelloWorld.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>HelloWord</title>
</head>
<body>
    <h1>hello,world! i am struts2</h1>
</body>
</html>

    

 

二,运行结果

 

 

 

 

 

 

三,过程分析

1,访问http://localhost:8080/struts2-byblank/,web.xml配置了<welcome-file>为index.html,页面跳转到index.html

2,index.html <heal>配置的2秒后自动刷新到HelloWorld.action,所以实际会跳转到http://localhost:8080/struts2-byblank/HelloWorld.action

3,web.xml配置了StrutsPrepareAndExecuteFilter过滤器,所以action请求被struts2核心包中的struts-default.xml的配置处理。

而自定义的struts.xml继承struts-default.xml, 定义了名为HelloWorld的action,返回结果为HelloWorld.jsp,所以页面跳转到http://localhost:8080/struts2-byblank/HelloWorld.jsp

 

 

 

 

 

参考资料:官方struts-2.3.34-all.zip文件中,struts2-blank案例

posted @ 2018-04-03 10:49  萧嘉  阅读(238)  评论(0编辑  收藏  举报