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
<?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>1101Strtus2</display-name> <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>
struts2配置文件:
<?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="false" /> <!-- 打开开发模式 --> <constant name="struts.devMode" value="true" /> <package name="helloworld" namespace="/helloworld" extends="struts-default"> <action name="test" class="com.hanqi.action.HelloWorldAction"> <result> /page/success.jsp </result> </action> </package> </struts>
<result>标签可以在同一个action中设置多个,根据他的name属性来区分。
java类:
package com.hanqi.action; import com.opensymphony.xwork2.ActionSupport; public class HelloWorldAction extends ActionSupport{ @Override public String execute(){ System.out.println("执行execute方法!!!"); return "fail"; } }
主页:
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8"%> <!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> <a href="helloworld/test">跳转</a> </body> </html>
点击链接,就会跳到根据相应的方法找到相应的页面。
Struts2传参数:
package com.hanqi.action; import java.util.Date; import com.alibaba.fastjson.JSONObject; import com.hanqi.model.AppUser; public class TestAction2 extends BaseAction { private static final long serialVersionUID = 1L; private Date dateStr; private AppUser appUser; private JSONObject jo; public String test1() { System.out.println(dateStr); return SUCCESS; } public String test2() { System.out.println(appUser); return SUCCESS; } public String doJson() { AppUser user = new AppUser(); user.setId(123); user.setUsername("admin"); user.setPassword("321"); JSONObject _jo = new JSONObject(); _jo.put("success", true); _jo.put("result", user); this.setJo(_jo); return SUCCESS; } public Date getDateStr() { return dateStr; } public void setDateStr(Date dateStr) { this.dateStr = dateStr; } public AppUser getAppUser() { return appUser; } public void setAppUser(AppUser appUser) { this.appUser = appUser; } public JSONObject getJo() { return jo; } public void setJo(JSONObject jo) { this.jo = jo; } }
package com.hanqi.action; import com.hanqi.model.AppUser; import com.opensymphony.xwork2.ModelDriven; public class TestAction extends BaseAction implements ModelDriven<AppUser> { private static final long serialVersionUID = 1L; private String username; private AppUser appUser; public String testMethod() { System.out.println(username); getRequest().setAttribute("param1", username); return SUCCESS; } public String testMethod2() { System.out.println(appUser); return SUCCESS; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public AppUser getAppUser() { return appUser; } public void setAppUser(AppUser appUser) { this.appUser = appUser; } @Override public AppUser getModel() { if (appUser == null) { appUser = new AppUser(); } return appUser; } }
package com.hanqi.model; import java.util.Date; public class AppUser { private Integer id; private String username; private String password; private Date birthday; public AppUser() { super(); } public AppUser(Integer id, String username, String password) { super(); this.id = id; this.username = username; this.password = password; } public Integer getId() { return id; } public void setId(Integer id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } @Override public String toString() { return "AppUser [id=" + id + ", username=" + username + ", password=" + password + ", birthday=" + birthday + "]"; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } }
package com.hanqi.util; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Date; import java.util.Map; import org.apache.struts2.util.StrutsTypeConverter; import com.opensymphony.xwork2.conversion.TypeConversionException; /* * 日期转换类 */ public class MyDateConvertor extends StrutsTypeConverter { private static final SimpleDateFormat[] sdf = { new SimpleDateFormat("yyyyMMdd"), new SimpleDateFormat("yyyy-MM-dd"), new SimpleDateFormat("yyyy年MM月dd日"), new SimpleDateFormat("yyyy/MM/dd") }; @Override public Object convertFromString(Map arg0, String[] values, Class arg2) { String dateString = values[0]; Date date = null; for(int i=0;i<sdf.length;i++) { try { date = sdf[i].parse(dateString); return date; } catch (ParseException e) { // e.printStackTrace(); continue; } } throw new TypeConversionException("没有记录的日期类型.."); } @Override public String convertToString(Map arg0, Object arg1) { // TODO Auto-generated method stub return null; } }
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> <Configuration> <Appenders> <Console name="STDOUT" target="SYSTEM_OUT"> <PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n"/> </Console> </Appenders> <Loggers> <Logger name="com.opensymphony.xwork2" level="debug"/> <Logger name="org.apache.struts2" level="debug"/> <Root level="warn"> <AppenderRef ref="STDOUT"/> </Root> </Loggers> </Configuration>
struts2.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> <!-- 开启动态方法调用 --> <constant name="struts.enable.DynamicMethodInvocation" value="false" /> <!-- 打开开发模式 --> <constant name="struts.devMode" value="true" /> <package name="helloworld" namespace="/helloworld" extends="json-default"> <action name="helloworld" class="com.hanqi.action.HelloWorldAction"> <result name="success">/page/success.jsp</result> <result name="fail">/page/fail.jsp</result> </action> <action name="test1" class="com.hanqi.action.TestAction" method="testMethod"> <result>/page/result.jsp</result> </action> <action name="test2" class="com.hanqi.action.TestAction" method="testMethod2"> <result>/page/result.jsp</result> </action> <action name="test3" class="com.hanqi.action.TestAction2" method="test1"> <result>/page/result.jsp</result> </action> <action name="test4" class="com.hanqi.action.TestAction2" method="test2"> <result>/page/result.jsp</result> </action> <action name="*_*" class="com.hanqi.action.{1}Action"> <result> /page/{2}.jsp </result> </action> <action name="testjson" class="com.hanqi.action.TestAction2" method="doJson"> <result type="json"> <param name="root">jo</param> </result> </action> </package> </struts>
xwork日期转换
java.util.Date=com.hanqi.util.MyDateConvertor
index.xml
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%> <!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> <script type="text/javascript" src="js/jquery-1.12.3.min.js"></script> <script type="text/javascript"> $(function() { $("#btn").click(function() { $.ajax({ url:"helloworld/testjson.action", type:"post", dataType:"json", success:function(data) { console.log(data); }, error:function() { alert("ERROR !"); } }); }); }); </script> </head> <body> <a href="helloworld/test.action">测试链接</a><br> <a href="helloworld/test1.action?username=admin">测试链接_传递参数</a><br> <form action="helloworld/test1.action" method="post"> <input name="username" /><input type="submit" value="提交" /> </form> <hr> <form action="helloworld/test2.action" method="post"> <input name="username" /><input name="password" /><input type="submit" value="提交" /> </form> <hr> <form action="helloworld/test3.action" method="post"> <input name="dateStr" /><input type="submit" value="提交" /> </form> <hr> <h1>不实现ModelDriven接口传递实体类</h1> <form action="helloworld/test4.action" method="post"> <input name="appUser.id" /> <input name="appUser.username" /> <input name="appUser.password" /> <input name="appUser.birthday" /> <input type="submit" value="提交" /> </form> <a href="helloworld/Login_success">测试链接2</a><button id="btn">测试json</button> </body> </html>