Strtus2框架笔记

2018-02-28 11:27:36 浏览数 (1)

Struts2以WebWork优秀的设计思想为核心,吸收了 Struts框架的部分优点,提供了一个更加整洁的MVC设计模式实现的Web 应用程序框架。 Struts2引入了几个新的框架特性:从逻辑中分离出横切关注点的拦截器、减少或者消除配置文件、贯穿整个框架的强大表达式语言、支持可变更和可重用的基于MVC模式的标签API, Struts2充分利用了从其它MVC框架学到的经验和教训,使得 Struts2框架更加清晰灵活。

Struts2的详细交教程可以看:http://www.yiibai.com/struts_2/

为什么要用Struts2:

struts2其实就是为我们封装了servlet,简化了jsp跳转的复杂操作,并且提供了易于编写的标签,可以快速开发view层的代码。  过去,我们用jsp和servlet搭配,实现展现时,大体的过程是:   1 jsp触发action   2 servlet接受action,交给后台class处理   3 后台class跳转到其他的jsp,实现数据展现  现在有了struts2,实现过程变为   1 jsp触发action   2 struts2拦截请求,调用后台action   3 action返回结果,由不同的jsp展现数据

Struts2的优势:

    Struts2有两方面的技术优势,一是所有的Struts2应用程序都是基于client/server HTTP交换协议,The Java Servlet API揭示了Java Servlet只是Java API的一个很小子集,这样我们可以在业务逻辑部分使用功能强大的Java语言进行程序设计。     二是提供了对MVC的一个清晰的实现,这一实现包含了很多参与对所以请求进行处理的关键组件,如:拦截器、OGNL表达式语言、堆栈。     因为struts2有这样目标,并且有这样的优势,所以,这是我们学习struts2的理由,下面,我们在深入剖析一下struts的工作原理。

Struts2工作原理:

Struts2简单实例:

web.xml

代码语言:javascript复制
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <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">
 3   <display-name>1101Strtus2</display-name>
 4 
 5     <filter>
 6         <filter-name>struts2</filter-name>
 7         <filter-class>org.apache.struts2.dispatcher.ng.filter.StrutsPrepareAndExecuteFilter</filter-class>
 8     </filter>
 9 
10     <filter-mapping>
11         <filter-name>struts2</filter-name>
12         <url-pattern>/*</url-pattern>
13     </filter-mapping>
14     
15 </web-app>

struts2配置文件:

代码语言:javascript复制
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 
 6 <struts>
 7     <!-- 开启方法时调用 -->
 8     <constant name="struts.enable.DynamicMethodInvocation" value="false" />
 9     <!-- 打开开发模式 -->
10     <constant name="struts.devMode" value="true" />
11     
12     <package name="helloworld" namespace="/helloworld" extends="struts-default">
13         <action name="test" class="com.hanqi.action.HelloWorldAction">
14             <result>
15                   /page/success.jsp
16             </result>
17         </action>
18     </package>
19 </struts>
代码语言:javascript复制
<result>标签可以在同一个action中设置多个,根据他的name属性来区分。

java类:

代码语言:javascript复制
 1 package com.hanqi.action;
 2 
 3 import com.opensymphony.xwork2.ActionSupport;
 4 
 5 public class HelloWorldAction extends ActionSupport{
 6     
 7     @Override
 8     public String execute(){
 9         System.out.println("执行execute方法!!!");
10         return "fail";
11     }
12 }

主页:

代码语言:javascript复制
 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 <a href="helloworld/test">跳转</a>
11 </body>
12 </html>

点击链接,就会跳到根据相应的方法找到相应的页面。

Struts2传参数:

代码语言:javascript复制
 1 package com.hanqi.action;
 2 
 3 import java.util.Date;
 4 
 5 import com.alibaba.fastjson.JSONObject;
 6 import com.hanqi.model.AppUser;
 7 
 8 public class TestAction2 extends BaseAction {
 9 
10     private static final long serialVersionUID = 1L;
11 
12     private Date dateStr;
13     
14     private AppUser appUser;
15     
16     private JSONObject jo;
17     
18     public String test1() {
19         System.out.println(dateStr);
20         
21         return SUCCESS;
22     }
23     
24     public String test2() {
25         System.out.println(appUser);
26         
27         return SUCCESS;
28     }
29     
30     public String doJson() {
31         AppUser user = new AppUser();
32         user.setId(123);
33         user.setUsername("admin");
34         user.setPassword("321");
35         
36         JSONObject _jo = new JSONObject();
37         _jo.put("success", true);
38         _jo.put("result", user);
39         this.setJo(_jo);
40         
41         return SUCCESS;
42     }
43 
44     public Date getDateStr() {
45         return dateStr;
46     }
47 
48     public void setDateStr(Date dateStr) {
49         this.dateStr = dateStr;
50     }
51 
52     public AppUser getAppUser() {
53         return appUser;
54     }
55 
56     public void setAppUser(AppUser appUser) {
57         this.appUser = appUser;
58     }
59 
60     public JSONObject getJo() {
61         return jo;
62     }
63 
64     public void setJo(JSONObject jo) {
65         this.jo = jo;
66     }
67     
68     
69 }
代码语言:javascript复制
 1 package com.hanqi.action;
 2 
 3 import com.hanqi.model.AppUser;
 4 import com.opensymphony.xwork2.ModelDriven;
 5 
 6 public class TestAction extends BaseAction implements ModelDriven<AppUser> {
 7 
 8     private static final long serialVersionUID = 1L;
 9 
10     private String username;
11 
12     private AppUser appUser;
13 
14     public String testMethod() {
15         System.out.println(username);
16         getRequest().setAttribute("param1", username);
17 
18         return SUCCESS;
19     }
20 
21     public String testMethod2() {
22         System.out.println(appUser);
23         return SUCCESS;
24     }
25 
26     public String getUsername() {
27         return username;
28     }
29 
30     public void setUsername(String username) {
31         this.username = username;
32     }
33 
34     public AppUser getAppUser() {
35         return appUser;
36     }
37 
38     public void setAppUser(AppUser appUser) {
39         this.appUser = appUser;
40     }
41 
42     @Override
43     public AppUser getModel() {
44         if (appUser == null) {
45             appUser = new AppUser();
46         }
47         return appUser;
48     }
49 }
代码语言:javascript复制
 1 package com.hanqi.model;
 2 
 3 import java.util.Date;
 4 
 5 public class AppUser {
 6     
 7     private Integer id;
 8     private String username;
 9     private String password;
10     private Date birthday;
11 
12     public AppUser() {
13         super();
14     }
15 
16     public AppUser(Integer id, String username, String password) {
17         super();
18         this.id = id;
19         this.username = username;
20         this.password = password;
21     }
22 
23     public Integer getId() {
24         return id;
25     }
26 
27     public void setId(Integer id) {
28         this.id = id;
29     }
30 
31     public String getUsername() {
32         return username;
33     }
34 
35     public void setUsername(String username) {
36         this.username = username;
37     }
38 
39     public String getPassword() {
40         return password;
41     }
42 
43     public void setPassword(String password) {
44         this.password = password;
45     }
46 
47     @Override
48     public String toString() {
49         return "AppUser [id="   id   ", username="   username   ", password="   password   ", birthday="   birthday
50                   "]";
51     }
52 
53     public Date getBirthday() {
54         return birthday;
55     }
56 
57     public void setBirthday(Date birthday) {
58         this.birthday = birthday;
59     }
60 
61 }
代码语言:javascript复制
 1 package com.hanqi.util;
 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 import com.opensymphony.xwork2.conversion.TypeConversionException;
11 /*
12  * 日期转换类
13  */
14 public class MyDateConvertor extends StrutsTypeConverter {
15     
16     private static final SimpleDateFormat[] sdf = {
17             new SimpleDateFormat("yyyyMMdd"),
18             new SimpleDateFormat("yyyy-MM-dd"),
19             new SimpleDateFormat("yyyy年MM月dd日"),
20             new SimpleDateFormat("yyyy/MM/dd")
21     };
22 
23     @Override
24     public Object convertFromString(Map arg0, String[] values, Class arg2) {
25         
26         String dateString = values[0];
27         Date date = null;
28         for(int i=0;i<sdf.length;i  ) {
29             try {
30                 date = sdf[i].parse(dateString);
31                 return date;
32             } catch (ParseException e) {
33                 // e.printStackTrace();
34                 continue;
35             }
36         }
37         throw new TypeConversionException("没有记录的日期类型..");
38     }
39 
40     @Override
41     public String convertToString(Map arg0, Object arg1) {
42         // TODO Auto-generated method stub
43         return null;
44     }
45 
46 }

log4j2.xml

代码语言:javascript复制
 1 <?xml version="1.0" encoding="UTF-8"?>
 2 <Configuration>
 3     <Appenders>
 4         <Console name="STDOUT" target="SYSTEM_OUT">
 5             <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/>
 6         </Console>
 7     </Appenders>
 8     <Loggers>
 9         <Logger name="com.opensymphony.xwork2" level="debug"/>
10         <Logger name="org.apache.struts2" level="debug"/>
11         <Root level="warn">
12             <AppenderRef ref="STDOUT"/>
13         </Root>
14     </Loggers>
15 </Configuration>

struts2.xml

代码语言:javascript复制
 1 <?xml version="1.0" encoding="UTF-8" ?>
 2 <!DOCTYPE struts PUBLIC
 3     "-//Apache Software Foundation//DTD Struts Configuration 2.3//EN"
 4     "http://struts.apache.org/dtds/struts-2.3.dtd">
 5 
 6 <struts>
 7     <!-- 开启动态方法调用 -->
 8     <constant name="struts.enable.DynamicMethodInvocation" value="false" />
 9     <!-- 打开开发模式 -->
10     <constant name="struts.devMode" value="true" />
11 
12     <package name="helloworld" namespace="/helloworld" extends="json-default">
13         <action name="helloworld" class="com.hanqi.action.HelloWorldAction">
14             <result name="success">/page/success.jsp</result>
15             <result name="fail">/page/fail.jsp</result>
16         </action>
17         
18         <action name="test1" class="com.hanqi.action.TestAction" method="testMethod">
19             <result>/page/result.jsp</result>
20         </action>
21         
22         <action name="test2" class="com.hanqi.action.TestAction" method="testMethod2">
23             <result>/page/result.jsp</result>
24         </action>
25         
26         <action name="test3" class="com.hanqi.action.TestAction2" method="test1">
27             <result>/page/result.jsp</result>
28         </action>
29         
30         <action name="test4" class="com.hanqi.action.TestAction2" method="test2">
31             <result>/page/result.jsp</result>
32         </action>
33         
34         <action name="*_*" class="com.hanqi.action.{1}Action">
35             <result>
36                 /page/{2}.jsp
37             </result>
38         </action>
39         
40         <action name="testjson" class="com.hanqi.action.TestAction2" method="doJson">
41             <result type="json">
42                 <param name="root">jo</param>
43             </result>
44         </action>
45         
46     </package>
47 
48 </struts>

xwork日期转换

代码语言:javascript复制
1 java.util.Date=com.hanqi.util.MyDateConvertor

index.xml

代码语言:javascript复制
 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 <script type="text/javascript" src="js/jquery-1.12.3.min.js"></script>
 9 <script type="text/javascript">
10 $(function() {
11     $("#btn").click(function() {
12         $.ajax({
13             url:"helloworld/testjson.action",
14             type:"post",
15             dataType:"json",
16             success:function(data) {
17                 console.log(data);
18             },
19             error:function() {
20                 alert("ERROR !");
21             }
22         });
23     });
24 });
25 </script>
26 </head>
27 <body>
28 <a href="helloworld/test.action">测试链接</a><br>
29 <a href="helloworld/test1.action?username=admin">测试链接_传递参数</a><br>
30 <form action="helloworld/test1.action" method="post">
31     <input name="username" /><input type="submit" value="提交" />
32 </form>
33 <hr>
34 <form action="helloworld/test2.action" method="post">
35     <input name="username" /><input name="password" /><input type="submit" value="提交" />
36 </form>
37 <hr>
38 <form action="helloworld/test3.action" method="post">
39     <input name="dateStr" /><input type="submit" value="提交" />
40 </form>
41 <hr>
42 <h1>不实现ModelDriven接口传递实体类</h1>
43 <form action="helloworld/test4.action" method="post">
44     <input name="appUser.id" />
45     <input name="appUser.username" />
46     <input name="appUser.password" />
47     <input name="appUser.birthday" />
48     <input type="submit" value="提交" />
49 </form>
50 <a href="helloworld/Login_success">测试链接2</a><button id="btn">测试json</button>
51 </body>
52 </html>

0 人点赞