程序图
描述
ThreadCache类是ThreadLocal<T>类的封装,UserManagerServlet请求方法里面创建一个User对象,然后,将对象放到ThreadLocal中,然后,从UserManagerDao获得该对象,再返回给Servlet
程序
ThreadCache
package com.tgb.util; import com.tgb.entity.User; public class ThreadCache { private static ThreadLocal<User> threadLocal; static { threadLocal= new ThreadLocal<User>(); } public static User getUser(){ return threadLocal.get(); } public static void setUser(User user){ threadLocal.set(user); } }
Servlet
package com.tgb.servlet; import java.io.IOException; import javax.servlet.ServletException; import javax.servlet.http.HttpServlet; import javax.servlet.http.HttpServletRequest; import javax.servlet.http.HttpServletResponse; import com.tgb.entity.User; import com.tgb.service.UserManagerService; import com.tgb.util.ThreadCache; public class UserManagerServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doPost(request,response); } public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { int id = Integer.parseInt(request.getParameter("id")); String name = request.getParameter("name"); String password = request.getParameter("password"); User user = new User(); user.setId(id); user.setName(name); user.setPassword(password); ThreadCache.setUser(user); UserManagerService userManagerService = new UserManagerService(); User getUser = userManagerService.getUser(); System.out.println(getUser); response.sendRedirect(request.getContextPath() + "/index.jsp"); } }
Dao
package com.tgb.dao; import com.tgb.entity.User; import com.tgb.util.ThreadCache; public class UserDao { public User getUser(){ return ThreadCache.getUser(); } }
增强版Demo
概述
对于上面的demo,非常的简单,主要是让大家了解ThreadLocal的功能,其在项目中真正的用途是存储Connection,从达到Service管理事务的目的,下面将给大家介绍一个比较好的demo。
类图概要
描述
ConnectionContext是数据库连接对象池,使用的是c3p0;
ConnectionPoolManager是ThreadLocal<T>的封装;
TransactionManager是事务的封装;
Filter过滤请求,开启事务,调用Servlet,最后,Filter提交事务;
BaseDao使用泛型和反射,实现简单的ORM思想,使程序操作的都是对象;
总结
demo2里面知识点挺多的,是一个比较全面的例子,分页封装,json封装,ThreadLocal,c3p0,事务应用,反射和泛型,自定义注解(demo,没有应用到项目里),有兴趣的可以下载源码看看,这里不做过多介绍。
版权声明:本文为博主原创文章,未经博主允许不得转载。
时间: 2024-10-20 15:04:39