模块化web应用中不同Context的相互调用

摘要:大型的web应用,采用模块化设计可以使得多个team同时开发;每个模块可以完全独立的使用资源(比如,连接到不同的数据库,实现分库分表)。

下图示例中,是一个简化的银行柜员系统。其中的四个模块所需要的用户数据不尽相同;比如客户关系模块,可以查看用户信息,账户信息以及用户社会关系等;转账模块就只需要用户权限以及账户信息;用户的账户又有普通储蓄账户和理财账户之分。这些信息都需要不同的权限来访问,此时,分模块开发可以更加方便的设计数据库、简化架构设计。
这里写图片描述

  • 代码的实现
    软件环境 - Tomcat, JavaEE
    a) 修改Tomcat Context.xml,允许不同context之间的相互访问。
    添加crossContext="true" 到Context属性中。
    这里写图片描述
    b) 创建不同的Web Project。在Servlet中相互调用。
    下面的示例中使用了两个Web Project, Context分别是/webmodule, /simpleweb
    • /simpleweb中访问/webmodule
      • 连接到数据库test1
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

public class Connector {
    static {
        try {
            Class.forName("org.postgresql.Driver");
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }
    public void checkUser() {
        try {
            Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test1", "****", "****");
            conn.prepareStatement("select * from test1").executeQuery();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
 - 在servlet中访问context
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connector cot = new Connector();
        cot.checkUser();
        System.out.println("BindChecker ....");
       request.getServletContext().getContext("/webmodule").getRequestDispatcher("/UserChecker").forward(request, response);
    }
  • /webmodule中访问/simpleweb
    • 连接到数据库test2
....
Connection conn = DriverManager.getConnection("jdbc:postgresql://localhost:5432/test2", "****", "****");
            conn.prepareStatement("select * from test2").executeQuery();
....
 - 在servlet中访问context
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        Connector cot = new Connector();
        cot.checkUser();
        System.out.println("UserChecker....");
        request.getServletContext().getContext("/simpleweb").getRequestDispatcher("/index.html").forward(request, response);
    }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值