Strut2简单使用

来源:互联网 发布:2017淘宝流量突然暴跌 编辑:程序博客网 时间:2024/06/07 05:10

一、Strut1和Strut2的主要区别

在Action的实现方面
Struts1要求必须统一扩展自Action类,而Struts2中可以是一个POJO。
线程模型方面
Struts1的Action是单实例的,一个Action的实例处理所有的请求。Struts 2的Action是一个请求对应一个实例(每次请求时都新new出一个对象),没有线程安全方面的问题。
Servlet依赖方面
Struts1的Action依赖于Servlet API,比如Action的execute方法的参数就包括request和response对象。这使程序难于测试。Struts2中的Action不再依赖于Servlet API,有利于测试,并且实现TDD。
封装请求参数
Struts1中强制使用ActionForm对象封装请求的参数。Struts2可以选择使用POJO类来封装请求的参数,或者直接使用Action的属性。
表达式语言方面
Struts1中整合了EL,但是EL对集合和索引的支持不强,Struts2整合了OGNL(Object Graph NavigationLanguage)。
绑定值到视图技术
Struts1使用标准的JSP,Struts2使用“ValueStack”技术。
类型转换
Struts1中的ActionForm基本使用String类型的属性。Struts2中使用OGNL进行转换,可以更方便的使用。
Struts1中支持覆盖validate方法或者使用Validator框架。Struts2支持重写validate方法或者使用XWork的验证框架。
Action执行控制的对比
Struts1支持每一个模块对应一个请求处理,但是模块中的所有Action必须共享相同的生命周期。Struts2支持通过拦截器堆栈为每一个Action创建不同的生命周期。
拦截器的应用
拦截器,在AOP(Aspect-Oriented Programming)中用于在某个方法或字段被访问之前,进行拦截然后在之前或之后加入某些操作。拦截是AOP的一种实现策略。
在Webwork的中文文档的解释为——拦截器是动态拦截Action调用的对象。它提供了一种机制可以使开发者可以定义在一个action执行的前后执行的代码,也可以在一个action执行前阻止其执行。同时也是提供了一种可以提取action中可重用的部分的方式。

二、简单实例

  • web.xml(这里有一个小细节,对于struts.xml文件我们是要放在src目录下的,要不然会出现500
<?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>
  • struts.xml(注意配置namespace之后,对于<s:form ><s:a>这些的url怎么写,都会自动加上.action
<?xml version="1.0" encoding="UTF-8" ?><!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd"><struts><!-- 在struts.xml中开启该常量。 --><constant name="struts.devModel" value="true"/><package name="my" extends="struts-default" namespace="/www"><interceptors>            <interceptor name="islogin" class="com.struts2.intercept.IsLoginInterceptor"/>            <interceptor-stack name="teamwareStack">                <interceptor-ref name="islogin"/>                <interceptor-ref name="defaultStack"/>            </interceptor-stack></interceptors><default-interceptor-ref name="teamwareStack"/><default-action-ref name="index" /><global-results><result name="NoLogin" type="redirect">/index.jsp</result><result name="error" type="redirect">/error.jsp</result></global-results>    <!-- 定义处理请求URL为login.action的Action -->       <action name="index" class="com.struts2.action.LoginAction" method="doIndex">        <!-- 定义处理结果字符串和资源之间的映射关系 -->            <result name="non">/index.jsp</result>        </action>            <action name="login" class="com.struts2.action.LoginAction" method="doLogin">        <result>/index.jsp</result>        <!-- 定义处理结果字符串和资源之间的映射关系 -->            <result name="success">/success.jsp</result>        </action>                <action name="show" class="com.struts2.action.LoginAction" method="doShow">        <!-- 定义处理结果字符串和资源之间的映射关系 -->            <result name="success">/show.jsp</result>        </action>            </package>    </struts>
  • index.jsp
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>登陆</title><meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>    <s:form action="login" method="post" namespace="/www">    <table align="center" bgcolor="pink">    <tr align="center">    <td colspan="2">欢迎登陆</td>    </tr>    <tr>    <td>用户名</td>    <td><input type="text" name="u.username"/></td>    </tr>    <tr>    <td>密码:</td>    <td><input type="text" name="u.password"/></td>    </tr>    <tr align="cnter">    <td colspan="2"><input type="submit" value="登陆"/></td>    </tr>    </table>    </s:form>  </body></html>
  • success.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%><%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><%@ taglib prefix="s" uri="/struts-tags" %><!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"><html>  <head>    <base href="<%=basePath%>">        <title>登陆成功</title>    <meta http-equiv="pragma" content="no-cache"><meta http-equiv="cache-control" content="no-cache"><meta http-equiv="expires" content="0">    <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"><meta http-equiv="description" content="This is my page"><!--<link rel="stylesheet" type="text/css" href="styles.css">-->  </head>    <body>    <h1>登录成功后显示此页面</h1>    <s:a href="www/show">开始访问</s:a>   </body></html>

  • show.jsp和error.jsp一样,里面加了一个<s:a>标签返回到index.jsp

  • User.java
package com.struts2.model;public class User {private String username;private String password;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;}}
  • LoginAction.java
package com.struts2.action;import com.opensymphony.xwork2.ActionSupport;import com.struts2.model.User;public class LoginAction extends ActionSupport{private User u = new User();public User getU() {return u;}public void setU(User u) {this.u = u;}public String doLogin(){return "success";}public String doShow(){return "success";}public String doIndex(){return "non";}@Overridepublic void validate() {super.validate();}}

  • IsLoginInterceptor.java(定义一个拦截器,在所有action执行之前都判断是否用户登陆了,没有的话就跳到登陆页面
package com.struts2.intercept;import com.opensymphony.xwork2.ActionContext;import com.opensymphony.xwork2.ActionInvocation;import com.opensymphony.xwork2.interceptor.AbstractInterceptor;public class IsLoginInterceptor extends AbstractInterceptor{@Overridepublic String intercept(ActionInvocation invocation) throws Exception {ActionContext ctx = invocation.getInvocationContext();Object username= ctx.getParameters().get("u.username");        /*if (username != null) {     return invocation.invoke();          }          return "NoLogin";  */                return invocation.invoke();  }

}
  • 【注】因为我发现username并不是理想中的文本框的值,不知道为什么得到的是String类对象,ctx.getParameters()里面得到的是[u.username=Java.Lang.String,u.password=Java.Land.String]可能是因为我在Action里面使用的是User这个对象吧。
  • 其次,不知道怎么保持登陆信息,是每次method的时候保存在session里面比较好呢还是用一个隐藏文本框?或者再加一个拦截器。


0 0
原创粉丝点击