您的位置:首页 > 编程语言 > Java开发

struts2学习记录

2018-03-22 22:39 274 查看
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>
<!-- i18n:国际化. 解决post提交乱码 -->
<constant name="struts.i18n.encoding" value="UTF-8"></constant>
<!-- 指定反问action时的后缀名 http://localhost:8080/struts2_day01/hello/HelloAction.do -->
<constant name="struts.action.extension" value="action,,do"></constant>
<!-- 指定struts2是否以开发模式运行
1.热加载主配置.(不需要重启即可生效)
2.提供更多错误信息输出,方便开发时的调试
-->
<constant name="struts.devMode" value="true"></constant>

<!-- package:将Action配置封装.就是可以在Package中配置很多action.
name属性: 给包起个名字,起到标识作用.随便起.不能其他包名重复.
namespace属性:给action的访问路径中定义一个命名空间
extends属性: 继承一个 指定包
abstract属性:包是否为抽象的; 标识性属性.标识该包不能独立运行.专门被继承
-->
<package name="hello" namespace="/hello" extends="struts-default" >
<!-- action元素:配置action类
name属性: 决定了Action访问资源名.
class属性: action的完整类名
method属性: 指定调用Action中的哪个方法来处理请求
-->
<action name="HelloAction" class="cn.example.a_hello.HelloAction" method="hello" >
<!-- result元素:结果配置
name属性: 标识结果处理的名称.与action方法的返回值对应.
type属性: 指定调用哪一个result类来处理结果,默认使用转发.

4000
标签体:填写页面的相对路径
-->
<result name="success" type="dispatcher" >/hello.jsp</result>
</action>
</package>
<!-- 引入其他struts配置文件 -->
<include file="cn/example/b_dynamic/struts.xml"></include>
(<!-- 配置动态方法调用是否开启常量
默认是关闭的,需要开启 (了解 action名加!方法名)
-->
<constant name="struts.enable.DynamicMethodInvocation" value="false"></constant>

<package name="dynamic" namespace="/dynamic" extends="struts-default" >
<!-- 动态方法调用方式2:通配符方式
使用{1} 取出第一个星号通配的内容
-->
<action name="Demo1Action_*" class="cn.example.b_dynamic.Demo1Action" method="{1}" >
<result name="success" >/hello.jsp</result>
</action>)
<include file="cn/example/c_default/struts.xml"></include>
(<package name="default" namespace="/default" extends="struts-default" >
<!-- 找不到包下的action,会使用Demo2Action作为默认action处理请求 -->
<default-action-ref name="Demo2Action"></default-action-ref>
<!-- method属性:execute  -->
<!-- result的name属性:success  -->
<!-- result的type属性:dispatcher 转发  -->
<!-- class属性:com.opensymphony.xwork2.ActionSupport -->
<action name="Demo2Action"   >
<result  >/hello.jsp</result>
</action>
</package>)
</struts>


<!--  转发 -->
<action name="Demo1Action" class="cn.example.a_result.Demo1Action" method="execute" >
<result name="success" type="dispatcher" >/hello.jsp</result>
</action>
<!-- 重定向 -->
<action name="Demo2Action" class="cn.example.a_result.Demo2Action" method="execute" >
<result name="success" type="redirect" >/hello.jsp</result>
</action>
<!-- 转发到Action -->
<action name="Demo3Action" class="cn.example.a_result.Demo3Action" method="execute" >
<result name="success" type="chain">
<!-- action的名字 -->
<param name="actionName">Demo1Action</param>
<!-- action所在的命名空间 -->
<param name="namespace">/</param>
</result>
</action>
<!-- 重定向到Action -->
<action name="Demo4Action" class="cn.example.a_result.Demo4Action" method="execute" >
<result  name="success"  type="redirectAction">
<!-- action的名字 -->
<param name="actionName">Demo1Action</param>
<!-- action所在的命名空间 -->
<param name="namespace">/</param>
</result>
</action>
<action name="Demo3Action" class="cn.example.d_config.Demo3Action" method="execute" >
<result name="success" type="redirectAction" >
<param name="actionName">Demo1Action</param>
<param name="namespace">/</param>
<!-- 如果添加的参数struts"看不懂".就会作为参数附加重定向的路径之后.
如果参数是动态的.可以使用${}包裹ognl表达式.动态取值
-->
<param name="name">${name}</param>
</result>
</action>


拦截器,生命周期:随项目的启动而创建,随项目关闭而销毁

implements Interceptor(了解);AbstractInterceptor(了解)
//继承:MethodFilterInterceptor 方法过滤拦截器
//功能: 定制拦截器拦截的方法.
//  定制哪些方法需要拦截.
//  定制哪些方法不需要拦截
public class MyInterceptor3 extends MethodFilterInterceptor{

@Override
protected String doIntercept(ActionInvocation invocation) throws Exception {
if
//前处理
System.out.println("MyInterceptor3 的前处理!");
//放行
String result = invocation.invoke();
//后处理
System.out.println("MyInterceptor3 的后处理!");
else
return result;
}

}

<package name="inter" namespace="/" extends="struts-default" >
<interceptors>
<!-- 1.注册拦截器 -->
<interceptor name="myInter3" class="cn.itcast.a_interceptor.MyInterceptor3"></interceptor>
<!-- 2.注册拦截器栈 -->
<interceptor-stack name="myStack">
<!-- 自定义拦截器引入(建议放在20个拦截器之前) -->
<interceptor-ref name="myInter3">
<!-- 指定哪些方法不拦截
<param name="excludeMethods">add,delete</param> -->
<!-- 指定哪些方法需要拦截 -->
<param name="includeMethods">add,delete</param>
</interceptor-ref>
<!-- 引用默认的拦截器栈(20个) -->
<interceptor-ref name="defaultStack"></interceptor-ref>
</interceptor-stack>
</interceptors>
<!-- 3.指定包中的默认拦截器栈 -->
<default-interceptor-ref name="myStack"></default-interceptor-ref>
<action name="Demo1Action_*" class="cn.itcast.a_interceptor.Demo1Action" method="{1}" >
<!-- 为Action单独指定走哪个拦截器(栈)
<interceptor-ref name="myStack"></interceptor-ref>-->
<result name="success" type="dispatcher" >/index.jsp</result>
</action>
</package>


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>


ActionContext数据中心

含有:原生request,原生response,原生servletContext,request 域,session域,application域,param参数,attr域,valueStack值栈

//request域=> map (struts2并不推荐使用原生request域)
//不推荐
Map<String, Object> requestScope = (Map<String, Object>) ActionContext.getContext().get("request");
//推荐
ActionContext.getContext().put("name", "requestTom");
//session域 => map
Map<String, Object> sessionScope =ActionContext.getContext().getSession();
sessionScope.put("name", "sessionTom");
//application域=>map
Map<String, Object> applicationScope = ActionContext.getContext().getApplication();
applicationScope.put("name", "applicationTom");
//原生request
HttpServletRequest request = ServletActionContext.getRequest();
//原生session
HttpSession session = request.getSession();
//原生response
HttpServletResponse response = ServletActionContext.getResponse();
//原生servletContext
ServletContext servletContext=ServletActionContext.getServletContext();

//-接口方式 *Aware
//如何在action中获得原生ServletAPI
public class Demo7Action extends ActionSupport implements ServletRequestAware {


1属性驱动获得参数

action与jsp里名字对应<input type=”text” name=”name” />

public class Action extends ActionSupport {
//准备与参数键名称相同的属性
private String name;
//自动类型转换 只能转换8大基本数据类型以及对应包装类
private Integer age;
//支持特定类型字符串转换为Date ,例如 yyyy-MM-dd
private Date   birthday;


2对象驱动<input type=”text” ame=”user.name”/>

public class Action extends ActionSupport
//准备user对象
private User user;


3模型驱动

public class Action extends ActionSupport implements ModelDriven<User> {
//准备user 成员变量
private User user =new User();


封装集合类型参数
public class Demo11Action extends ActionSupport  {
//list
private List<String> list;
//Map
private Map<String,String> map;
jsp:
list:<input type="text" name="list" /><br>
list:<input type="text" name="list[3]" /><br>(索引跳跃,中间为NULL)
map:<input type="text" name="map['haha']" /><br>


.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>Insert title here</title>
</head>
<body>
<form action="${pageContext.request.contextPath}/Demo2Action">
用户名:<input type="text" name="name" /><br>
<input type="submit" value="提交" />
</form>
<!-- 调试标签 -->
<s:debug></s:debug>
(
Root默认情况下,栈中放置当前访问的Action对象
Context部分就是ActionContext数据中心
)
</body>
</html>


Struts标签

<%@ 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>Insert title here</title>
</head>
<body>
<!-- 遍历标签 iterator -->
<!-- ------------------------------------- -->
<s:iterator value="#list" >
<s:property /><br>  输出:1\n 2\n 3\n
</s:iterator>
<!-- ------------------------------------- --><hr>
<s:iterator value="#list" var="name" >   第二种遍历方式,名name然后取出
<s:property value="#name" /><br>
</s:iterator>
<!-- ------------------------------------- --><hr>
<s:iterator begin="1" end="100" step="1"  >
<s:property />|  输出:1-100 步进为1
</s:iterator>
<!-- ------------------if else elseif------------------- --><hr>

<s:if test="#list.size()==4">
list长度为4!
</s:if>
<s:elseif test="#list.size()==3">
list长度为3!
</s:elseif>
<s:else>
list不3不4!
</s:else>

<!-- ------------------property 配合ognl表达式页面取值 ------------------- --><hr>

<s:property value="#list.size()" />
<s:property value="#session.user.name" />

<!-- struts2表单标签 ****一般不用****-->
<!-- 好处1: 内置了一套样式.  -->
<!-- 好处2: 自动回显,根据栈中的属性  -->
<!-- theme:指定表单的主题
xhtml:默认
simple:没有主题
-->
<s:form action="Demo3Action" namespace="/" theme="xhtml" >
<s:textfield name="name" label="用户名"  ></s:textfield>
<s:password name="password" label="密码" ></s:password>
<s:radio list="{'男','女'}" name="gender" label="性别" ></s:radio>
<s:radio list="#{1:'男',0:'女'}" name="gender" label="性别" ></s:radio>
<s:checkboxlist list="#{2:'抽烟',1:'喝酒',0:'烫头'}" name="habits" label="爱好" ></s:checkboxlist>
<s:select list="#{2:'大专',1:'本科',0:'硕士'}" headerKey="" headerValue="---请选择---" name="edu" label="学历" >
</s:select>
<s:file name="photo" label="近照" ></s:file>
<s:textarea name="desc" label="个人简介" ></s:textarea>
<s:submit value="提交" ></s:submit>
</s:form>

<s:actionerror/>
</body>
</html>


html el
request: ${requestScope.name}<br>
session:${sessionScope.name}<br>
application:${applicationScope.name}<br>


OGNL:对象视图导航语言.  ${user.addr.name} 这种写法就叫对象视图导航.
OGNL不仅仅可以视图导航.支持比EL表达式更加丰富的功能.
//准备ONGLContext
//准备Root
User rootUser = new User("tom",18);
//准备Context
Map<String,User> context = new HashMap<String,User>();
context.put("user1", new User("jack",18));
context.put("user2", new User("rose",22));
OgnlContext oc = new OgnlContext();
//将rootUser作为root部分
oc.setRoot(rootUser);
//将context这个Map作为Context部分
oc.setValues(context);
//取出root中的属性值
//取出root中user对象的name属性
String name = (String) Ognl.getValue("name", oc, oc.getRoot());
//对root中的user对象的name属性赋值
Ognl.getValue("name='jerry'", oc, oc.getRoot());
//取出context中的属性值
//取出context中键为user1对象的name属性
String name = (String) Ognl.getValue("#user1.name", oc, oc.getRoot());
//对context中的user1对象的name属性赋值
String name2 = (String) Ognl.getValue("#user1.name='勇',#user1.name", oc, oc.getRoot());
//调用root中user对象的setName,getName方法
Ognl.getValue("setName('lilei')", oc, oc.getRoot());
String name = (String) Ognl.getValue("getName()", oc, oc.getRoot());
//调用context中user对象的setName,getName方法
String name2 = (String) Ognl.getValue("#user1.setName('lucy'),#user1.getName()", oc, oc.getRoot());
//调用静态方法@类全名@方法名
String name = (String) Ognl.getValue("@cn.itheima.a_ognl.HahaUtils@echo('hello !')", oc, oc.getRoot());
@变量名
//Double pi = (Double) Ognl.getValue("@java.lang.Math@PI", oc, oc.getRoot());
Double pi = (Double) Ognl.getValue("@@PI", oc, oc.getRoot());
//创建list对象
Integer size = (Integer) Ognl.getValue("{'tom','jerry','jack','rose'}.size()", oc, oc.getRoot());
String name = (String) Ognl.getValue("{'tom','jerry','jack','rose'}[0]", oc, oc.getRoot());
String name2 = (String) Ognl.getValue("{'tom','jerry','jack','rose'}.get(1)", oc, oc.getRoot());

//创建Map对象
Integer size2 = (Integer) Ognl.getValue("#{'name':'tom','age':18}.size()", oc, oc.getRoot());
String name3  = (String) Ognl.getValue("#{'name':'tom','age':18}['name']", oc, oc.getRoot());
Integer age  = (Integer) Ognl.getValue("#{'name':'tom','age':18}.get('age')", oc, oc.getRoot());


prepare,ModelDriven接口里
//1获得值栈
ValueStack vs = ActionContext.getContext().getValueStack();
//2将u压入栈顶
vs.push(u);


JAVA 四大域对象总结(ServletContext,HttpSession ,ServletRequest,PageContext):https://www.cnblogs.com/skjsg/p/4707032.html

Action生命周期

- 1.每次请求到来时,都会创建一个新的Action实例

- 2.Action是线程安全的.可以使用成员变量接收参数

struts2使用优势

- 自动封装参数

- 参数校验

- 结果的处理(转发|重定向)

- 国际化

- 显示等待页面

- 表单的防止重复提交

- struts2具有更加先进的架构以及思想
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: