标签:
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(); } }
版权声明:本文为博主原创文章,未经博主允许不得转载。
标签:
原文地址:http://blog.csdn.net/jiben2qingshan/article/details/47171517