当前位置:  编程技术>软件工程/软件设计
本页文章导读:
    ▪ActionContext和ServletActionContext小结       1. ActionContext 在Struts2开发中,除了将请求参数自动设置到Action的字段中,我们往往也需要在Action里直接获取请求(Request)或会话(Session)的一些信息,甚至需要直接对JavaServlet Http的请求(HttpServletRequ.........
    ▪组合模式(Composite Pattern)                像一个树形结构一样使用基本的对象和自己本身构建一个复杂的对象,称为组合模式。 这种模式很容易学习以及应用到某个系统中。组合模式属于结构设计.........
    ▪action里边的登录方法      public class AdminAction extends BaseAction { // 当前Action涉及到业务对象 private AdminService adminService; private Admin admin; public void setAdminService(AdminService adminService) { this.adminService = adminService; } public Admin .........

[1]ActionContext和ServletActionContext小结
    来源: 互联网  发布时间: 2013-11-19


1. ActionContext


在Struts2开发中,除了将请求参数自动设置到Action的字段中,我们往往也需要在Action里直接获取请求(Request)或会话(Session)的一些信息,甚至需要直接对JavaServlet Http的请求(HttpServletRequest),响应(HttpServletResponse)操作. 我们需要在Action中取得request请求参数"username"的值:


ActionContext context = ActionContext.getContext(); 
Map params = context.getParameters(); 
String username = (String) params.get("username");
ActionContext(com.opensymphony.xwork.ActionContext)是Action执行时的上下文,上下文可以看作是一个容器(其实我们这里的容器就是一个Map而已),它存放的是Action在执行时需要用到的对象. 一般情况, 我们的ActionContext都是通过: ActionContext context = (ActionContext) actionContext.get();来获取的.我们再来看看这里的actionContext对象的创建:


static ThreadLocal actionContext = new ActionContextThreadLocal();


ActionContextThreadLocal是实现ThreadLocal的一个内部类.ThreadLocal可以命名为"线程局部变量",它为每一个使用该变量的线程都提供一个变量值的副本,使每一个线程都可以独立地改变自己的副本,而不会和其它线程的副本冲突.这样,我们ActionContext里的属性只会在对应的当前请求线程中可见,从而保证它是线程安全的.


通过ActionContext取得HttpSession: Map session = ActionContext.getContext().getSession();


  2. ServletActionContext


ServletActionContext(com.opensymphony.webwork. ServletActionContext),这个类直接继承了我们上面介绍的ActionContext,它提供了直接与Servlet相关对象访问的功能,它可以取得的对象有:


(1)javax.servlet.http.HttpServletRequest : HTTPservlet请求对象


(2)javax.servlet.http.HttpServletResponse : HTTPservlet相应对象


(3)javax.servlet.ServletContext : Servlet上下文信息


(4)javax.servlet.ServletConfig : Servlet配置对象


(5)javax.servlet.jsp.PageContext : Http页面上下文


如何从ServletActionContext里取得Servlet的相关对象:


<1>取得HttpServletRequest对象: HttpServletRequest request = ServletActionContext. getRequest();


<2>取得HttpSession对象: HttpSession session = ServletActionContext. getRequest().getSession();


  3. ServletActionContext和ActionContext联系


ServletActionContext和ActionContext有着一些重复的功能,在我们的Action中,该如何去抉择呢?我们遵循的原则是:如果ActionContext能够实现我们的功能,那最好就不要使用ServletActionContext,让我们的Action尽量不要直接去访问Servlet的相关对象.


注意:在使用ActionContext时有一点要注意: 不要在Action的构造函数里使用ActionContext.getContext(),因为这个时候ActionContext里的一些值也许没有设置,这时通过ActionContext取得的值也许是null;同样,HttpServletRequest req = ServletActionContext.getRequest()也不要放在构造函数中,也不要直接将req作为类变量给其赋值。至于原因,我想是因为前面讲到的static ThreadLocal actionContext = new ActionContextThreadLocal(),从这里我们可以看出ActionContext是线程安全的,而ServletActionContext继承自ActionContext,所以ServletActionContext也线程安全,线程安全要求每个线程都独立进行,所以req的创建也要求独立进行,所以ServletActionContext.getRequest()这句话不要放在构造函数中,也不要直接放在类中,而应该放在每个具体的方法体中(eg:login()、queryAll()、insert()等),这样才能保证每次产生对象时独立的建立了一个req。


  4. struts2中获得request、response和session


(1)非IoC方式


方法一:使用org.apache.struts2.ActionContext类,通过它的静态方法getContext()获取当前Action的上下文对象。


ActionContext ctx = ActionContext.getContext();


ctx.put("liuwei", "andy"); //request.setAttribute("liuwei", "andy"); 
Map session = ctx.getSession(); //session


HttpServletRequest request = ctx.get(org.apache.struts2.StrutsStatics.HTTP_REQUEST); 
HttpServletResponse response = ctx.get(org.apache.struts2.StrutsStatics.HTTP_RESPONSE);
细心的朋友可以发现这里的session是个Map对象, 在Struts2中底层的session都被封装成了Map类型. 我们可以直接操作这个Map对象进行对session的写入和读取操作, 而不用去直接操作HttpSession对象.


方法二:使用org.apache.struts2.ServletActionContext类


public class UserAction extends ActionSupport { 
     
    //其他代码片段 
     
    private HttpServletRequest req; 
// private HttpServletRequest req = ServletActionContext.getRequest(); 这条语句放在这个位置是错误的,同样把这条语句放在构造方法中也是错误的。


    public String login() { 
        req = ServletActionContext.getRequest(); //req的获得必须在具体的方法中实现 
        user = new User(); 
        user.setUid(uid); 
        user.setPassword(password); 
        if (userDAO.isLogin(user)) { 
            req.getSession().setAttribute("user", user); 
            return SUCCESS; 
        } 
        return LOGIN; 
    } 
    public String queryAll() { 
        req = ServletActionContext.getRequest(); //req的获得必须在具体的方法中实现 
        uList = userDAO.queryAll(); 
        req.getSession().setAttribute("uList", uList); 
        return SUCCESS; 
    } 
     
    //其他代码片段 
}


(2)IoC方式(即使用Struts2 Aware拦截器)


要使用IoC方式,我们首先要告诉IoC容器(Container)想取得某个对象的意愿,通过实现相应的接口做到这点。


public class UserAction extends ActionSupport implements SessionAware, ServletRequestAware, ServletResponseAware {


    private HttpServletRequest request; 
    private HttpServletResponse response;


    public void setServletRequest(HttpServletRequest request) { 
        this.request = request; 
    }


    public void setServletResponse(HttpServletResponse response) { 
        this.response = response; 
    }


    public String execute() { 
        HttpSession session = request.getSession(); 
        return SUCCESS; 
    } 
}
作者:chuyuqing 发表于2013-5-15 15:36:26 原文链接
阅读:67 评论:0 查看评论

    
[2]组合模式(Composite Pattern)
    来源: 互联网  发布时间: 2013-11-19

   

      像一个树形结构一样使用基本的对象和自己本身构建一个复杂的对象,称为组合模式。 这种模式很容易学习以及应用到某个系统中。组合模式属于结构设计模式之一,比较常用。经典的UML图如下:


       一个简单的实例程序来说明组合模式是如何实现的。定义一个Employee类,充当组合模式中的表演者,CompositePatternDemo作为测试类。

public class Employee {
    private String name;
    private String dept;
    private int salary;
    private List<Employee> subordinates;

    // constructor
    public Employee(String name,String dept, int sal) {
        this.name = name;
        this.dept = dept;
        this.salary = salary;
        subordinates = new ArrayList<Employee>();
    }

    public void add(Employee e) {
        subordinates.add(e);
    }

    public void remove(Employee e) {
        subordinates.remove(e);
    }

    public List<Employee> getSubordinates(){
        return subordinates;
    }

    public String toString(){
        return ("Employee :[ Name : "+ name
                +", dept : "+ dept + ", salary :"
                + salary+" ]");
    }

}

    测试代码:

public class CompositePatternDemo {
    public static void main(String[] args) {
        Employee CEO = new Employee("John","CEO", 30000);

        Employee headSales = new Employee("Robert","Head Sales", 20000);

        Employee headMarketing = new Employee("Michel","Head Marketing", 20000);

        Employee clerk1 = new Employee("Laura","Marketing", 10000);
        Employee clerk2 = new Employee("Bob","Marketing", 10000);

        Employee salesExecutive1 = new Employee("Richard","Sales", 10000);
        Employee salesExecutive2 = new Employee("Rob","Sales", 10000);

        CEO.add(headSales);
        CEO.add(headMarketing);

        headSales.add(salesExecutive1);
        headSales.add(salesExecutive2);

        headMarketing.add(clerk1);
        headMarketing.add(clerk2);

        //print all employees of the organization
        System.out.println(CEO);
        for (Employee headEmployee : CEO.getSubordinates()) {
            System.out.println(headEmployee);
            for (Employee employee : headEmployee.getSubordinates()) {
                System.out.println(employee);
            }
        }
    }
}

      测试结果:


Employee :[ Name : John, dept : CEO, salary :0 ]
Employee :[ Name : Robert, dept : Head Sales, salary :0 ]
Employee :[ Name : Richard, dept : Sales, salary :0 ]
Employee :[ Name : Rob, dept : Sales, salary :0 ]
Employee :[ Name : Michel, dept : Head Marketing, salary :0 ]
Employee :[ Name : Laura, dept : Marketing, salary :0 ]
Employee :[ Name : Bob, dept : Marketing, salary :0 ]

        

作者:GreatElite 发表于2013-5-15 15:29:12 原文链接
阅读:57 评论:0 查看评论

    
[3]action里边的登录方法
    来源: 互联网  发布时间: 2013-11-19
public class AdminAction extends BaseAction {


// 当前Action涉及到业务对象
private AdminService adminService;

private Admin admin;


public void setAdminService(AdminService adminService) {
this.adminService = adminService;
}


public Admin getAdmin() {
return admin;
}


public void setAdmin(Admin admin) {
this.admin = admin;
}


public String login() {
System.out.println("login………………" + admin.getName() + "---"
+ admin.getPass());
if (ServletActionContext.getRequest().getSession()
.getAttribute("logadmin") != null) {
return "loginIn";
}
if (admin == null) {
return "loginOut";
}
admin = adminService.login(admin.getName(), admin.getPass());
System.out.println(admin);
// System.out.println(admin + "======");
ServletActionContext.getRequest().getSession()
.setAttribute("logadmin", admin);
return "loginIn";


}


public String logout() {


if (ServletActionContext.getRequest().getSession()
.getAttribute("logadmin") != null) {
ServletActionContext.getRequest().getSession()
.removeAttribute("logadmin");
}


return "loginOut";
}
作者:chuyuqing 发表于2013-5-15 15:23:42 原文链接
阅读:73 评论:0 查看评论

    
最新技术文章:
▪主-主数据库系统架构    ▪java.lang.UnsupportedClassVersionError: Bad version number i...    ▪eclipse项目出现红色叉叉解决方案
▪Play!framework 项目部署到Tomcat    ▪dedecms如何做中英文网站?    ▪Spring Batch Framework– introduction chapter(上)
▪第三章 AOP 基于@AspectJ的AOP    ▪基于插件的服务集成方式    ▪Online Coding开发模式 (通过在线配置实现一个表...
▪观察者模式(Observer)    ▪工厂模式 - 程序实现(java)    ▪几种web并行化编程实现
▪机器学习理论与实战(二)决策树    ▪Hibernate(四)——全面解析一对多关联映射    ▪我所理解的设计模式(C++实现)——解释器模...
▪利用规则引擎打造轻量级的面向服务编程模式...    ▪google blink的设计计划: Out-of-Progress iframes    ▪FS SIP呼叫的消息线程和状态机线程
▪XML FREESWITCH APPLICATION 实现    ▪Drupal 实战    ▪Blink: Chromium的新渲染引擎
▪(十四)桥接模式详解(都市异能版)    ▪你不知道的Eclipse用法:使用Allocation tracker跟...    ▪Linux内核-进程
▪你不知道的Eclipse用法:使用Metrics 测量复杂度    ▪IT行业为什么没有进度    ▪Exchange Server 2010/2013三种不同的故障转移
▪第二章 IoC Spring自动扫描和管理Bean    ▪CMMI简介    ▪目标检测(Object Detection)原理与实现(六)
▪值班总结(1)——探讨sql语句的执行机制    ▪第二章 IoC Annotation注入    ▪CentOS 6.4下安装Vagrant
▪Java NIO框架Netty1简单发送接受    ▪漫画研发之八:会吃的孩子有奶吃    ▪比较ASP和ASP.NET
▪SPRING中的CONTEXTLOADERLISTENER    ▪在Nginx下对网站进行密码保护    ▪Hibernate从入门到精通(五)一对一单向关联映...
▪.NET领域驱动设计—初尝(三:穿过迷雾走向光...    ▪linux下的块设备驱动(一)    ▪Modem项目工作总结
▪工作流--JBPM简介及开发环境搭建    ▪工作流--JBPM核心服务及表结构    ▪Eclipse:使用JDepend 进行依赖项检查
▪windows下用putty上传文件到远程Linux方法    ▪iBatis和Hibernate的5点区别    ▪基于学习的Indexing算法
▪设计模式11---设计模式之中介者模式(Mediator...    ▪带你走进EJB--JMS编程模型    ▪从抽象谈起(二):观察者模式与回调
▪设计模式09---设计模式之生成器模式(Builder)也...    ▪svn_resin_持续优化中    ▪Bitmap recycle方法与制作Bitmap的内存缓存
▪Hibernate从入门到精通(四)基本映射    ▪设计模式10---设计模式之原型模式(Prototype)    ▪Dreamer 3.0 支持json、xml、文件上传
▪Eclipse:使用PMD预先检测错误    ▪Jspx.net Framework 5.1 发布    ▪从抽象谈起(一):工厂模式与策略模式
▪Eclipse:使用CheckStyle实施编码标准    ▪【论文阅读】《Chain Replication for Supporting High T...    ▪Struts2 Path_路径问题
▪spring 配置文件详解    ▪Struts2第一个工程helloStruts极其基本配置    ▪Python学习入门基础教程(learning Python)--2 Python简...
▪maven springmvc环境配置    ▪基于SCRUM的金融软件开发项目    ▪software quality assurance 常见问题收录
▪Redis集群明细文档    ▪Dreamer 框架 比Struts2 更加灵活    ▪Maven POM入门
▪git 分支篇-----不断更新中    ▪Oracle非主键自增长    ▪php设计模式——UML类图
▪Matlab,Visio等生成的图片的字体嵌入问题解决...    ▪用Darwin和live555实现的直播框架    ▪学习ORM框架—hibernate(二):由hibernate接口谈...
▪(十)装饰器模式详解(与IO不解的情缘)    ▪无锁编程:最简单例子    ▪【虚拟化实战】网络设计之四Teaming
▪OSGi:生命周期层    ▪Javascript/Jquery——简单定时器    ▪java代码 发送GET、POST请求
▪Entity Framework底层操作封装(3)    ▪HttpClient 发送GET、POST请求    ▪使用spring框架,应用启动时,加载数据
▪Linux下Apache网站目录读写权限的设置    ▪单键模式的C++描述    ▪学习ORM框架—hibernate(一):初识hibernate
 


站内导航:


特别声明:169IT网站部分信息来自互联网,如果侵犯您的权利,请及时告知,本站将立即删除!

©2012-2021,,E-mail:www_#163.com(请将#改为@)

浙ICP备11055608号-3