Struts2 语法--action

时间:2022-01-09 15:10:38

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>