Struts2 语法--action
xml的注释:
<!--叨叨叨叨-->
web.xml注释格式":
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<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>
- namespace:
 
1. package:区分不同的action,
2. namespace为空, 随便找到index action处理,可以囊括其他package处理不了的.
输入/front/index 就会显示 Namespace.jsp
<package name="front" extends="struts-default" namespace="/front">
<action name="index">
<result name="success">/Namespace.jsp</result>
</action>
</package> <package name="main" extends="struts-default" namespace="">
<action name="index">
<result>/Namespace.jsp</result>
</action>
</package>
- action:具体视图的返回可以由用户自己定义的action来决定.
 
/index 会访问 IndexAction1.class,通过返回的success,跳转到 ActionIntroduction.jsp
上面的例子,没有配置class则会执行ActionSurport, 自动返回一个success, 所以直接执行result里的jsp
<constant name="struts.devMode" value="true" />
<package name="front" extends="struts-default" namespace="/">
<action name="index" class="com.bjsxt.struts2.front.action.IndexAction1">
<result name="success">/ActionIntroduction.jsp</result>
</action>
</package>
action的标准模式:
public class IndexAction3 extends ActionSupport {
	@Override
	public String execute() {
		return "success";
	}
}
- path:
 
jsp文件中有这个样的连接:
<a href="path/path.action">路径问题说明</a>
要去struts.xml去找namespace为path, action为path的, 再去看class里找到pathaction.class,返回值为path跳转到path.jsp
<constant name="struts.devMode" value="true" />
<package name="path" extends="struts-default" namespace="/path">
<action name="path" class="com.bjsxt.struts2.path.action.PathAction">
<result name="path">/path.jsp</result>
</action>
</package>
path.jsp:
<a href="index.jsp">index.jsp</a>
这样是不可以的,虽然path.jsp和index.jsp在同一目录. 去找的是 /path/index.jsp,如何解决:
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<base href="<%=basePath%>" />
所以,Struts2的路径问题是根据action的路径而不是jsp的路径来决定的. 所以尽量不要使用相对路径.要使用绝对路径.
jsp中使用request.getContextRoot获取webapp的路径. myeclipse指定basepath
- 动态调用DMI Dynamic Method Invoking:
 
action执行不一定要执行execute方法, 看下面的例子:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts>
<constant name="struts.devMode" value="true" />
<package name="user" extends="struts-default" namespace="/user">
<action name="userAdd" class="com.bjsxt.struts2.user.action.UserAction" method="add">
<result>/user_add_success.jsp</result>
</action> <action name="user" class="com.bjsxt.struts2.user.action.UserAction">
<result>/user_add_success.jsp</result>
</action>
</package>
</struts>
jsp调用方法:
第2种方法比较好, 动态调用, 找namespace为user, action为user, 方法由jsp里调用时的add选择.
<a href="<%=context %>/user/userAdd">添加用户</a>
<br />
<a href="<%=context %>/user/user!add">添加用户</a>
<br />
- 通配符配置:
 
struts.xml文件:
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts>
<constant name="struts.devMode" value="true" />
<package name="actions" extends="struts-default" namespace="/actions">
<action name="Student*" class="com.bjsxt.struts2.action.StudentAction" method="{1}">
<result>/Student{1}_success.jsp</result>
</action> <action name="*_*" class="com.bjsxt.struts2.action.{1}Action" method="{2}">
<result>/{1}_{2}_success.jsp</result>
<!-- {0}_success.jsp -->
</action>
</package>
</struts>
调用jsp:
<% String context = request.getContextPath(); %> <a href="<%=context %>/actions/Studentadd">添加学生</a>
<a href="<%=context %>/actions/Studentdelete">删除学生</a>
<br />
不过,一定要遵守"约定优于配置"的原则
<br />
<a href="<%=context %>/actions/Teacher_add">添加老师</a>
<a href="<%=context %>/actions/Teacher_delete">删除老师</a>
<a href="<%=context %>/actions/Course_add">添加课程</a>
<a href="<%=context %>/actions/Course_delete">删除课程</a>
- 用action属性接收参数:
 
jsp文件:
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030" />
<base href="<%=basePath %>"/>
<title>Insert title here</title>
</head>
<body>
使用action属性接收参数<a href="user/user!add?name=a&age=8">添加用户</a> </body>
</html>
struts.xml:
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts>
<constant name="struts.devMode" value="true" />
<package name="user" extends="struts-default" namespace="/user"> <action name="user" class="com.bjsxt.struts2.user.action.UserAction">
<result>/user_add_success.jsp</result>
</action>
</package>
</struts>
user.java:
package com.bjsxt.struts2.user.action;
import com.opensymphony.xwork2.ActionSupport;
public class UserAction extends ActionSupport {
private String name;
	private int age;
public String add() {
		System.out.println("name=" + name);
		System.out.println("age=" + age);
		return SUCCESS;
	}
public String getName() {
		return name;
	}
public void setName(String name) {
		this.name = name;
	}
public int getAge() {
		return age;
	}
public void setAge(int age) {
		this.age = age;
	}
}
1. 由user/user!add?name=a&age=8 找xml里的namespace为user,action为user的add方法,同时传入两个值给action
2. 需要在action里设置同名属性name和age,此处同名指的是getName,和getAge.
- 用DomainModel接收参数:
 
调用jsp:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030" />
<base href="<%=basePath %>"/>
<title>Insert title here</title>
</head>
<body>
使用Domain Model接收参数<a href="user/user!add?user.name=a&user.age=8">添加用户</a> </body>
</html>
useraction.java文件:
相当于调用了setUser().setName()
public class UserAction extends ActionSupport {
	private User user;  //自己new
	//private UserDTO userDTO;
	public String add() {
		System.out.println("name=" + user.getName());
		System.out.println("age=" + user.getAge());
		return SUCCESS;
	}
	public User getUser() {
		return user;
	}
	public void setUser(User user) {
		this.user = user;
	}
}
vo: user.java:
public class User {
	private String name;
	private int age;
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getAge() {
		return age;
	}
	public void setAge(int age) {
		this.age = age;
	}
}
DTO: userdto.java: data transfer object
package com.bjsxt.struts2.user.dto;
public class UserDTO {
	private String name;
	private String password;
	private String confirmingPassword;
}
- modeldriven接收参数: 面向对象思想: V: jsp M: Model类, C:各种action , action来负责M, V沟通,并解耦和
 
useraction.java: C
package com.bjsxt.struts2.user.action; import com.bjsxt.struts2.user.model.User;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven; public class UserAction extends ActionSupport implements ModelDriven<User>{ private User user = new User(); //必须自己new public String add() {
System.out.println("name=" + user.getName());
System.out.println("age=" + user.getAge());
return SUCCESS;
} @Override
public User getModel() {
return user;
}
}
jsp:
<?xml version="1.0" encoding="GB18030" ?>
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%> <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030" />
<base href="<%=basePath %>"/>
<title>Insert title here</title>
</head>
<body>
使用ModelDriven接收参数<a href="user/user!add?name=a&age=8">添加用户</a> </body>
</html>
总结:接收参数用第二种 DomainModel.
- 接收参数的中文问题:
 
jsp:
<?xml version="1.0" encoding="GB18030" ?>
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%> <%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030" />
<base href="<%=basePath %>"/>
<title>Insert title here</title>
</head>
<body>
使用action属性接收参数,测试中文问题
<form action="user/user!add" method="post">
姓名:<input type="text" name="name"></input>
<input type="submit" value="submit"/>
</form> </body>
</html>
提交中文后乱码,如何解决?
struts里已经设置,还是不行 :
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE struts PUBLIC
"-//Apache Software Foundation//DTD Struts Configuration 2.0//EN"
"http://struts.apache.org/dtds/struts-2.0.dtd"> <struts>
<constant name="struts.devMode" value="true" />
<constant name="struts.i18n.encoding" value="GBK" /> <!-- internationalization -->
<package name="user" extends="struts-default" namespace="/user">
<action name="userAdd" class="com.bjsxt.struts2.user.action.UserAction" method="add">
<result>/user_add_success.jsp</result>
</action> <action name="user" class="com.bjsxt.struts2.user.action.UserAction">
<result>/user_add_success.jsp</result>
</action>
</package>
</struts>
答案,配置web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<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-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter> <filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
- 简单数据验证:
 
jsp文件:
使用addFieldError方法和s:fieldError标签简单处理数据校验
<a href="user/user!add?name=a" >添加用户</a>
struts.xml:
<struts>
<constant name="struts.devMode" value="true" />
<package name="user" extends="struts-default" namespace="/user">
<action name="user" class="com.bjsxt.struts2.user.action.UserAction">
<result>/user_add_success.jsp</result>
<result name="error">/user_add_error.jsp</result>
</action>
</package>
</struts>
useraction.java:
想往前台传信息,可以用response或者request.setparameters, 但是action访问不到request,response
public class UserAction extends ActionSupport {
	private String name;
	public String add() {
		if(name == null || !name.equals("admin")) {
			this.addFieldError("name", "name is error");
			this.addFieldError("name", "name is too long");
			return ERROR;
		}
		return SUCCESS;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
}
登录不成功的时候user_add_error.jsp:
<body>
User Add Error!
<s:fielderror fieldName="name" theme="simple"/>
<br />
<s:property value="errors.name[0]"/>
<s:debug></s:debug>
</body>
</html>
- Action获取前台数据:request,session,application
 
后台的action是拿不到前台的request, response等,
如果前台输入用户名和密码什么的,放入session里,如果action获取不到session怎么办呢?
如何让action获取 request,session, application等外部元素?
index.jsp:
<body>
取得Map类型request,session,application,真实类型 HttpServletRequest, HttpSession, ServletContext的引用:
<ol>
<li>前三者:依赖于容器</li>
<li>前三者:IOC</li> (只用这种)
<li>后三者:依赖于容器</li>
<li>后三者:IOC</li>
</ol>
<br />
<form name="f" action="" method="post">
用户名:<input type="text" name="name"/>
密码:<input type="text" name="password"/>
<br />
<input type="button" value="submit1" onclick="javascript:document.f.action='login/login1';document.f.submit();" />
<input type="button" value="submit2" onclick="javascript:document.f.action='login/login2';document.f.submit();" />
<input type="button" value="submit3" onclick="javascript:document.f.action='login/login3';document.f.submit();" />
<input type="button" value="submit4" onclick="javascript:document.f.action='login/login4';document.f.submit();" />
</form> </body>
struts.xml:
<struts>
<constant name="struts.devMode" value="true" />
<package name="login" extends="struts-default" namespace="/login">
<action name="login*" class="com.bjsxt.struts2.user.action.LoginAction{1}">
<result>/user_login_success.jsp</result>
</action>
</package>
</struts>
最重要的处理action:
package com.bjsxt.struts2.user.action; import java.util.Map; import org.apache.struts2.interceptor.ApplicationAware;
import org.apache.struts2.interceptor.RequestAware;
import org.apache.struts2.interceptor.SessionAware; import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport; public class LoginAction2 extends ActionSupport implements RequestAware,SessionAware, ApplicationAware { private Map<String, Object> request;
private Map<String, Object> session;
private Map<String, Object> application; //DI dependency injection
//IoC inverse of control
public String execute() {
request.put("r1", "r1");
session.put("s1", "s1");
application.put("a1", "a1");
return SUCCESS;
} @Override
public void setRequest(Map<String, Object> request) {
this.request = request;
} @Override
public void setSession(Map<String, Object> session) {
this.session = session;
} @Override
public void setApplication(Map<String, Object> application) {
this.application = application;
}
}
返回成功的jsp:
<?xml version="1.0" encoding="GB18030" ?>
<%@ page language="java" contentType="text/html; charset=GB18030"
pageEncoding="GB18030"%>
<%@taglib uri="/struts-tags" prefix="s" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030" />
<title>Insert title here</title>
</head>
<body>
User Login Success!
<br />
<s:property value="#request.r1"/> | <%=request.getAttribute("r1") %> <br />
<s:property value="#session.s1"/> | <%=session.getAttribute("s1") %> <br />
<s:property value="#application.a1"/> | <%=application.getAttribute("a1") %> <br />
<s:property value="#attr.a1"/><br />
<s:property value="#attr.s1"/><br />
<s:property value="#attr.r1"/><br />
<s:debug></s:debug>
<br />
</body>
</html>
- 模块包含:
 
<include file="login.xml"/>
意义:多人平台开发的时候, 大家写各自的xml,
- 默认action:
 
使用目的:当访问当前的namespace下的action,找不到actoin的时候, 就可以自动选择index这个action
<default-action-ref name="index"></default-action-ref>
<action name="index">
<result>/default.jsp</result>
<action>
Struts2 语法--action的更多相关文章
- Struts2 In Action笔记_页面到动作的数据流入和流出
		
因为回答百度知道的一个问题,仔细查看了<Struts2 In Action>,深入细致的看了 “数据转移OGNL 和 构建视图-标签”,很多东西才恍然大悟. 一直觉得国外写的书很浮,不具有 ...
 - 转载  Struts2之------Action类中的get,set方法和execute方法的使用规范和使用流程(规范是没有理由的,必须遵守!!!)
		
1,Action中get,set方法的使用流程? 前台form中有一个<input type="text" name="username"/> 如果 ...
 - struts2的action是多例,servlet是单例
		
struts2中action是多例的,即一个session产生一个action如果是单例的话,若出现两个用户都修改一个对象的属性值,则会因为用户修改时间不同,两个用户访问得到的 属性不一样,操作得出的 ...
 - Struts2中Action接收参数的四种形式
		
1.Struts2的Action接收参数的三种形式. a. 使用Action的属性接收(直接在action中利用get方法来接收参数): login.js ...
 - Struts2中Action取得表单数据的几种方法
		
Struts2中Action取得表单数据的几种方法 Struts2中Action获得表单数据的几种方法struts2 Action获取表单传值 1.通过属性驱动式JSP: <form act ...
 - Struts2的Action(二)
		
Struts2的Action可以是一个POJO(即简单的javaBean),也实现Action接口,或者继承ActionSupport类. 1.Action接口: public interface A ...
 - Struts2之Action
		
Struts2之Action MVC模式中需要有一个控制器来负责浏览器与服务器之间的通信,实现用户与服务器的交互.在Struts2框架中实现这一功能的是Action,它是整个框架最核心的部分.Acti ...
 - 浅析Struts1和Struts2的Action线程安全问题  转
		
浅析Struts1和Struts2的Action线程安全问题 转 http://blog.csdn.net/virgoboy2004/article/details/5876133 [问题描述]最近 ...
 - struts1 和 struts2中Action什么时候实例化
		
精帖1:http://blog.csdn.net/lfsf802/article/details/7277013 精帖1:http://blog.csdn.net/wmj2003/article/de ...
 
随机推荐
- Linux openvswitch性能调优
			
Increasing the flow-eviction threshold The threshold is a type of limit on the number of flows that ...
 - jquety选择器
			
基本选择器 1.#id 根据id的属性值来获取元素 2.TagName 根据标签名来获取元素 3.selector1,selector2 匹配列表中的选择器(就是可以匹配多 ...
 - HDU 5777 domino
			
贪心一下.有k次机会,也就是那些数字中,最大的k-1可以不选择.答案为:sum{a[i]}-sum{最大的k-1个a[i]}+n.注意:k>=n的时候直接输出n. #pragma comment ...
 - MySQL查看索引、表信息、触发器
			
查看索引: select * FROM information_schema.TABLE_CONSTRAINTS ; select * FROM information_schema.TABLE_CO ...
 - openwrt之snmpd
			
OpenWRT uses UCI (/etc/config/snmpd) to generate the /etc/snmp/snmpd.conf , so you cannot simply edi ...
 - OS X快捷键最最齐全版(官方版)
			
看大家不时的都在将系统发快捷键最新版,在官网上其实就有这个最详细的信息,为了方便大家.另外系统快捷键不会更新那么快,也就不存在最新版了.小弟现将原文转发过来,希望对新入门或需要的小伙伴有帮助.OS X ...
 - Java 学习路线
			
java 入门到精通 转自:http://forum.hibernate.org.cn作者:robbinJava Learning Path (一).工具篇 一. JDK (Java Develop ...
 - Hadoop 中关于 map,reduce 数量设置
			
map和reduce是hadoop的核心功能,hadoop正是通过多个map和reduce的并行运行来实现任务的分布式并行计算,从这个观点来看,如果将map和reduce的数量设置为1,那么用户的任务 ...
 - MySQL数据库分区修改【原创】
			
之前有个表分区添加时s201607添加成s201617,所以在查询7月份数据时报错 错误的 alter table statistics_ticket add partition (partition ...
 - PHP实现队列的原理
			
关于的队列的介绍,我这里就不多讲了,随便百度一下都很多 用过laravel框架的童鞋都知道其自带队列功能,之前我很费解,PHP只是一个脚本,有超时机制 为什么能不停的去执行队列呢? 带着这个问题,在网 ...