Web层框架做两件事情:接收请求参数、返回响应。
Web层框架的特点
*都是一个特点,前端控制器模式
*记住:前端控制器(核心的控制器)
*Struts2框架前端的控制器就是过滤器
浏览器端发送的任何请求都会先经过前端控制器。
前端控制器会完成一些功能,然后再把请求交给Action。Action再去处理请求。
Struts2的核心就是过滤器
项目结构
一、导包
在Struts-apps-struts2-blank的项目中导入lib包
二、编写demo.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>
<h3>快速入门</h3>
<a href="${pageContext.request.contextPath }/hello.action">快速入门</a>
</body>
</html>
三、编写HelloAction
package com.ken.action;
public class HelloAction {
/**
* Action类中的方法签名有要求:
* public
* 必须有返回值,必须String类型
* 方法名可以是任意的,但是不能有参数列表
* 页面的跳转:
* 1.return "字符串"
* 2.需要在struts.xml配置文件中,配置跳转的页面
*
*/
public String sayHello() {
System.out.println("Hello Struts2");
return "ok";
}
}
四、编写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="default" namespace="/" extends="struts-default">
<!-- 配置Action -->
<action name="hello" class="com.ken.action.HelloAction" method="sayHello">
<!-- 配置跳转的页面,路径的写法:在struts2框架中,不管是转发还是重定向都不用写项目名 -->
<!-- name中的ok叫做逻辑视图名称 -->
<result name="ok">/demo1/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_3_0.xsd"
id="WebApp_ID" version="3.0">
<display-name>strutsDemo</display-name>
<welcome-file-list>
<welcome-file>index.jsp</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>
六、运行项目
点击超链接