Struts2(二)

以下内容是基于导入struts2-2.3.32.jar包来讲的

1.关于StrutsPrepareAndExecuteFilter

启动StrutsPrepareAndExecuteFilter时加载配置文件的流程
init方法依次执行加载以下文件
1.org/apache/struts2/default.properties

  默认的基本配置信息

  如:struts.action.extension=action,,

  此时默认为可以在路径末尾添加.action访问,可自行修改。

2.struts2-core-2.3.32.jar/struts-default.xml

3.src/struts.xml

可通过<constant name="" value=""></constant>更改以上基本的默认配置信息

配置web.xml文件:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>struts</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.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>

 

 1 package com.ronng.web.action;
 2 
 3 import com.opensymphony.xwork2.ActionSupport;
 4 
 5 public class OneAction extends ActionSupport {
 6 
 7     private static final long serialVersionUID = -1827866244363310821L;
 8     @Override
 9     public String execute() throws Exception {
10         //三种方式创建Action:普通类、实现Action接口、继承ActionSupport类
11         //SUCCESS常量是在Action接口已经定义好的,代表字符串"success"
12         return SUCCESS;
13     }
14 }
<?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>
    <!-- 
    package 
        包的概念,是可以继承的
        name:唯一标识。以后继承的时候可以使用
        namespace:命名空间,作为网络请求连接的一部分
        extends 这个是继承的意思,这个包继承了struts-default包  struts-default包定义在struts-default.xml文件中
        abstract 这个包是否是抽象包,true为抽象包,false不是抽象。抽象包下的所有的action都不会被创建对象使用
     action
         是动作类,是控制器
         name 控制器名字,也是访问url的一部分 http://localhost:8080/struts/one
         class 是控制器的完整路径
         method 是要执行的方法,默认是execute
     result
         是结果集。指定要返回的方式和内容
         默认是dispatcher转发
         redirect是重定向
         
     include 
         导入其他的struts配置文件 
         默认是src目录
     -->
    
    <package name="com.rong.web.action" namespace="/" extends="struts-default">
        <action name="one" class="com.ronng.web.action.OneAction">
            <result>/one.jsp</result>
        </action>
    </package>
   <!--  <include file="struts-goods.xml"></include> -->
    
</struts>

2.通配符的使用

<?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>
    <!--  http://localhost:8080/struts/one_add -->
    <!--  http://localhost:8080/struts/one_add_view -->
    <!--  http://localhost:8080/struts/one_execute_one-->
   <!-- http://localhost:8080/struts/one -->
<!-- 通用配置*号 one_*_* 例如:one_add_view {1} 获得 add {2} 获得view 一般用一个就可以了 one_add --> <package name="com.rong.web.action" namespace="/" extends="struts-default"> <action name="one_*_*" class="com.ronng.web.action.OneAction" method="{1}"> <result>/{2}.jsp</result> </action> <action name="*" class="com.ronng.web.action.OneAction" method="{1}"> <!-- result标签的name属性不写时,方法必须返回"success";否则两者的值必须相同 --> <result>/{1}.jsp</result> </action> </package> <!-- <include file="struts-goods.xml"></include> --> </struts>
 1 package com.ronng.web.action;
 2 
 3 import com.opensymphony.xwork2.ActionSupport;
 4 
 5 public class OneAction extends ActionSupport {
 6 
 7     private static final long serialVersionUID = -1827866244363310821L;
 8     @Override
 9     public String execute() throws Exception {
10         //三种方式创建Action:普通类、实现Action接口、继承ActionSupport类
11         //SUCCESS常量是在Action接口已经定义好的,代表字符串"success"
12         return SUCCESS;
13     }
14     
15     public String add() throws Exception {
16         //SUCCESS常量是在Action接口已经定义好的,代表字符串"success"
17         return SUCCESS;
18     }
19     public String one() throws Exception {
20         //SUCCESS常量是在Action接口已经定义好的,代表字符串"success"
21         //如果在xml配置文件中result标签没有写返回的name属性,此处必须返回小写的"success"字符串
22         //此处常量SUCCESS等于"success"
23         return SUCCESS;
24     }
25 }

 3.数据由前台传到后台

A.通过普通属性传递

index.jsp

除了通过表单提交方式外,还可以通过a标签URL链接的方式以及AJAX请求方式提交数据(这部分略。)

 1 <%@ page language="java" contentType="text/html; charset=UTF-8"
 2     pageEncoding="UTF-8"%>
 3 <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
 4 <html>
 5 <head>
 6 <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
 7 <title>Insert title here</title>
 8 </head>
 9 <body>
10     <form action="${pageContext.request.contextPath }/one" method="get">
11         <input type="text" name="username"/>
12         <input type="submit" value="提交"/>
13     </form>
14 </body>
15 </html>

one.jsp略

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>
    <package name="com.rong.web.action" namespace="/" extends="struts-default">
        <action name="one" class="com.ronng.web.action.OneAction">
            <result>/one.jsp</result>
        </action>
    </package>
    
</struts>

OneAction.java

 1 package com.ronng.web.action;
 2 
 3 import com.opensymphony.xwork2.ActionSupport;
 4 
 5 public class OneAction extends ActionSupport {
 6 
 7     private static final long serialVersionUID = -1827866244363310821L;
 8     //成员变量名必须与前台的name属性值相同
 9     private String username;
10     //必须提供set方法,可以不写get方法
11     public String getUsername() {
12         return username;
13     }
14     public void setUsername(String username) {
15         this.username = username;
16     }
17     @Override
18     public String execute() throws Exception {
19         System.out.println("username的值为:"+username);
20         return SUCCESS;
21     }
22 }

B.通过对象属性传递

inde.jsp

name 属性的值为user对象的属性,即对象名.属性名

<body>
    <form action="${pageContext.request.contextPath }/one" method="get">
        <input type="text" name="user.username"/>
        <input type="submit" value="提交"/>
    </form>
</body>

OneAction.java

提供get和set方法

 1 package com.ronng.web.action;
 2 
 3 import com.opensymphony.xwork2.ActionSupport;
 4 import com.ronng.web.entity.User;
 5 
 6 public class OneAction extends ActionSupport {
 7 
 8     private static final long serialVersionUID = -1827866244363310821L;
 9     private User user;
10     public User getUser() {
11         return user;
12     }
13     public void setUser(User user) {
14         this.user = user;
15     }
16     @Override
17     public String execute() throws Exception {
18         System.out.println("user对象的username属性值为:"+user.getUsername());
19         return SUCCESS;
20     }
21 }

User.java实体类

package com.ronng.web.entity;

public class User {
    private String username;

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }
}

C.通过模型驱动传递(实现ModelDriven接口)

index.jsp

<body>
    <form action="${pageContext.request.contextPath }/one" method="get">
        <input type="text" name="username"/>
        <input type="submit" value="提交"/>
    </form>
</body>
 1 package com.ronng.web.action;
 2 
 3 import com.opensymphony.xwork2.ActionSupport;
 4 import com.opensymphony.xwork2.ModelDriven;
 5 import com.ronng.web.entity.User;
 6 
 7 public class OneAction extends ActionSupport implements ModelDriven<User> {
 8 
 9     private static final long serialVersionUID = -1827866244363310821L;
10     //使用模型驱动ModelDriven(拦截器)必须创建对象
11     private User user=new User();
12     @Override
13     public String execute() throws Exception {
14         System.out.println("user对象的username属性值为:"+user.getUsername());
15         return SUCCESS;
16     }
17     //实现ModelDriven的getModel方法,为封装数据提供对象
18     @Override
19     public User getModel() {
20         System.out.println("getModel方法!");
21         return user;
22     }
23 }

先调用getModel方法,返回一个可以提供封装数据的对象

4.中文乱码问题

A.GET提交方式

在tomcat服务器的server.xml更改配置文件2017-12-31

<Connector connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443" URIEncoding="UTF-8"/>

B.POST提交方式

在struts2-core包中/org/apache/struts2/default.properties属性配置文件中默认编码为:

struts.i18n.encoding=UTF-8

因此,只要前后端的编码统一为UTF-8即可解决该问题,同时,也可根据实际自己去修改

在src/struts.xml中设置常量<constant name="struts.i18n.encoding" value="GBK"></constant>

5.时间格式问题

struts2支持的格式:

2017-12-31 20:20:20

2017年10月01日

如需要yyyy/MM/dd HH:mm:ss格式需要自定义日期格式

2017/08/08 11:22:33

A.局部方式解决

index.jsp

 

<body>
    <form action="${pageContext.request.contextPath }/one" method="get">
        <input type="text" name="date"/>
        <input type="submit" value="提交"/>
    </form>
</body>

 

OneAction.java

 1 package com.ronng.web.action;
 2 
 3 import java.util.Date;
 4 
 5 import com.opensymphony.xwork2.ActionSupport;
 6 
 7 public class OneAction extends ActionSupport{
 8 
 9     private static final long serialVersionUID = -1827866244363310821L;
10     private Date date;
11     public Date getDate() {
12         return date;
13     }
14     public void setDate(Date date) {
15         this.date = date;
16     }
17     @Override
18     public String execute() throws Exception {
19         System.out.println("date对象的值为:"+date);
20         return SUCCESS;
21     }
22 }

自定义转换器(继承StrutsTypeConverter 抽象类)

 1 package com.ronng.web.convert;
 2 
 3 import java.text.ParseException;
 4 import java.text.SimpleDateFormat;
 5 import java.util.Date;
 6 import java.util.Map;
 7 
 8 import org.apache.struts2.util.StrutsTypeConverter;
 9 
10 public class DateConvert extends StrutsTypeConverter {
11 
12     @Override
13     public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
14         SimpleDateFormat simpleDateFormat=new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");
15         System.out.println(arg2);
16         try {
17             Date date = simpleDateFormat.parse(arg1[0]);
18             return date;
19         } catch (ParseException e) {
20             e.printStackTrace();
21         }
22         return null;
23     }
24 
25     @Override
26     public String convertToString(Map arg0, Object arg1) {
27         return null;
28     }
29 }

新建properties文件,文件名为该Action类类名-conversion.properties

放在与该Action类同一包下,内容为date=com.ronng.web.convert.DateConvert

properties文件内容一般为Action类需要转换的成员变量.属性,现在该示例中时间是date成员变量,并不是对象中的属性,所以不用点号

 

使用以上方式后,会使原来固有的传递时间的方式失效,如需要原来的生效,则需要添加原来的处理格式

 1 package com.ronng.web.convert;
 2 
 3 import java.text.DateFormat;
 4 import java.text.ParseException;
 5 import java.text.SimpleDateFormat;
 6 import java.util.Date;
 7 import java.util.Map;
 8 
 9 import org.apache.struts2.util.StrutsTypeConverter;
10 
11 public class DateConvert extends StrutsTypeConverter {
12     //如果需要添加不同格式的时间,可以继续添加
13     //可以写成配置文件properties或xml形式,读取配置文件创建对象
14     //注意空格位置格式,以及中英文字符的区别
15     DateFormat[] df={
16             new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"),    
17             new SimpleDateFormat("yyyy/MM/dd HH:mm:ss"),    
18             new SimpleDateFormat("yyyyMMddHHmmss"),    
19             new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss")
20     };
21     @Override
22     public Object convertFromString(Map arg0, String[] arg1, Class arg2) {
23         for (DateFormat format : df) {
24             //出现异常则捕捉,然后继续下一个匹配。找到则返回,否则继续。
25             //实在没有则返回null
26             try {
27                 Date date = format.parse(arg1[0]);
28                 return date;
29             } catch (ParseException e) {
30                 //不应输出到控制台或日志,若输出则会影响调试或者判断
31                 //e.printStackTrace();
32                 System.out.println("测试!");
33             }
34         }
35         return null;
36     }
37 
38     @Override
39     public String convertToString(Map arg0, Object arg1) {
40         return null;
41     }
42 }

 

B.全局方式解决

 保留以上方式原有的东西,然后删除局部方式的properties文件

在src根目录下新建xwork-conversion.properties文件

文件内容添加:

6.数据由后台传到前台

方式一:EL表达式

index.jsp

<body>
    <form action="${pageContext.request.contextPath }/one" method="get">
        <input type="text" name="name"/>
        <input type="submit" value="提交"/>
    </form>
</body>

one.jsp

<body>
    通用的域: ${name }<br/>
    request域:${requestScope.name }<br/>
    session域:${sessionScope.name }<br/>
    application域:${applicationScope.name }<br/>
</body>

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>
    <package name="com.rong.web.action" namespace="/" extends="struts-default">
        <action name="one" class="com.ronng.web.action.OneAction">
            <result>/one.jsp</result>
        </action>
    </package>
    
</struts>

OneAction.java

 1 package com.ronng.web.action;
 2 
 3 import java.util.Date;
 4 
 5 import com.opensymphony.xwork2.ActionSupport;
 6 
 7 public class OneAction extends ActionSupport{
 8 
 9     private static final long serialVersionUID = -1827866244363310821L;
10     //默认是request域的传递
11     private String name;
12     //后台向前台传递数据时(展示数据)get方法是必须的
13     public String getName() {
14         return name;
15     }
16     //前台向后台传递数据时,set方法是必须的
17     public void setName(String name) {
18         this.name = name;
19     }
20     @Override
21     public String execute() throws Exception {
22         System.out.println("前台传过来的name的值为:"+name);
23         name+=" By EL";
24         return SUCCESS;
25     }
26 }

 7.棒符(!)(感叹号、叹号)的使用

实际开发中很少用

TwoAction.java 普通类实现Action

 1 package com.ronng.web.action;
 2 
 3 public class TwoAction {
 4     public String show(){
 5         System.out.println("show");
 6         return "success";
 7     }
 8     
 9     public String look(){
10         System.out.println("look");
11         return "success";
12     }
13 }

struts.xml

default.properties文件默认配置为:关闭动态调用方法

要开启才能使用叹号!

<?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.enable.DynamicMethodInvocation" value="true"></constant>
    <package name="com.rong.web.action" namespace="/" extends="struts-default">
        <action name="two" class="com.ronng.web.action.TwoAction">
            <result>/two.jsp</result>
        </action>
    </package>
    
</struts>

 浏览器路径为:http://localhost:8080/struts/two!show

浏览器路径为:http://localhost:8080/struts/two!look

 

posted @ 2017-12-31 23:40  57容杰龙  阅读(179)  评论(0编辑  收藏  举报