一.知识点:
—Strust2的核心控制器: FilterDispatcher
在web.xml配置,负责拦截所有用户请求,当用户请求到达,会过滤用户请求
—Strust2的业务控制器:Action
Action类中包含了对用户请求的的处理逻辑
1.Action接口和ActionSupport类
Action接口中定义的字符串常量作用是作为业务控制器中execute()方法的返回值
ActionSupport类提供了许多默认的方法(获取国际化信息、数据验证、默认处理用户请求……),如果在编写业务控制器时继承了ActionSupport类会大大简化开发。
2.Action实现类
为了简化可以实现ActionSupport类,通常包含一个execute()方法
二、Action访问ActionContext
在Action中可以通过该类获取Servlet中的参数
创建ActionContext实例的方法:
ActionContext ac = ActionContext.getContext();
Action访问ActionContext实例:
登录界面login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!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><s:text name="演示Struts2中Action通过ActionContext访问Servlet API"></s:text></title>
</head>
<body>
<s:form action="login1" method="post">
<s:textfield name="userName" label="用户名称" /><br>
<s:textfield name="password" label="用户密码" /><br>
<s:submit value="登录" />
</s:form>
登录成功success.jsp:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="s" uri="/struts-tags" %>
<!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>登录成功界面</title>
</head>
<body>
通过application:欢迎
<s:property value="#application.userName"/>进入系统<br><hr>
通过session:欢迎
<s:property value="#session.userName"/>进入系统
</body>
</html>
业务控制器Action:
package com.struts.demo;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
public class LoginAction extends ActionSupport{
private static final long serialVersionUID = 1L;
private String userName;
private String password;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String execute() throws Exception {
if(getUserName().equals("qq")&&getPassword().equals("123")){
//获取ActionContext对象
ActionContext ac= ActionContext.getContext();
//通过Application()得到用户名
ac.getApplication().put("userName", getUserName());
//通过Session()得到用户名
ac.getSession().put("userName", getUserName());
return SUCCESS;
} else {
return INPUT;
}
}
}
配置文件同上一篇
struts环境配置
运行结果:
用户名qq
密码:123