struts2:web层框架
struts基本执行过程:
一、发送请求
二、过滤器
1、获取请求路径,获取对外访问路径值A
2、到src下面找struts.xml,dom4j解析得到xml文件中的内容
通过A到xml文件找action标签,匹配name属性值是否一致
3、匹配name属性值一致(A),通过action标签的class属性得到类的全路径:
反射原理:
Class class = Class.forName("action全路径");
//得到名称是execute的方法
Method m = clazz.getMethod("execute");
//方法执行
Object obj = m.invoke();
4、得到action方法返回值,通过struts.xml的action标签里面的result标签
匹配name属性值,跳转到指定页面
官网下载struts2:struts-2-all.zip
普通解压软件解压,根目录:
用于导入的依赖包apps/struts2-blank/WEB-INF/lib:
导入eclipse项目的lib
简单示例:
创建web项目,apps/struts2-blank/WEB-INF/web.xml得到过滤器配置:
<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>
appsstruts2-blankWEB-INFsrcjava中得到struts.xml,拷贝到项目根目录下的src:
<?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>
<constant name="struts.devMode" value="true" />
<package name="default" namespace="/" extends="struts-default">
<action name="hello" class="com.ants.action.LoginAction">
<result name="success">/success.jsp</result>
<result name="error">/error.jsp</result>
</action>
</package>
</struts>
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>
<form action="hello" method="get">
name:<input type="text" name="userName"/>
<input type="submit" value="go"/>
</form>
</body>
</html>
LoginAction.java:
package com.ants.action;
import com.opensymphony.xwork2.ActionSupport;
/**
* 登录验证
* @author Administrator
*
*/
public class LoginAction extends ActionSupport{
private static final long serialVersionUID = 65689983137490423L;
private String userName;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String execute(){
System.out.println(this.getUserName());
if("你好".equals(this.getUserName())){
return "success";
}else{
return "error";
}
}
}
至此,完成了struts的登录验证!