访问 JAVA 类中的会话属性
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/17487396/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Accessing a session attribute in a JAVA Class
提问by praveen
I'm trying to fetch a session attribute in a java class. I came across this post: get HttpSession|Request from simple java class not servlet class... I tried to do what Matej tymes suggested. I wrote a RequestFilter and tried to fetch the request and session object. And from there i tried to get the session attribute. But i'm getting a null object. Please find my code below:
我正在尝试在 java 类中获取会话属性。我遇到了这篇文章:从简单的 java 类而不是 servlet 类获取 HttpSession|Request......我尝试按照 Matej tymes 的建议进行操作。我写了一个 RequestFilter 并试图获取请求和会话对象。从那里我尝试获取会话属性。但我得到一个空对象。请在下面找到我的代码:
Front Controller Servlet:
public void doGet(HttpServletRequest request,HttpServletResponse response)throws IOException, ServletException{
PrintWriter out=response.getWriter();
response.setContentType("text/html");
String userName=request.getParameter("userName");
String pass=request.getParameter("userPassWord");
String clientId = request.getParameter("client");
try {
Class.forName("com.mysql.jdbc.Driver");
connection =
DriverManager.getConnection("jdbc:mysql://localhost:3306/ABC", "xyz", "*****");
String queryString = "SELECT * FROM userInfo WHERE UserName=?";
//connection =ConnectionFactory.getInstance().getConnection();
ptmt = connection.prepareStatement(queryString);
ptmt.setString(1, userName);
resultSet = ptmt.executeQuery();
//Creating Servlet Context object
if(resultSet.next() && pass.equalsIgnoreCase(resultSet.getString("UserPass")))
{
HttpSession session=request.getSession(true);
session.setAttribute("loggedUser", userName);
session.setAttribute("clientId", clientId);
ServletContext context=getServletContext();
RequestDispatcher dispatcher=context.getRequestDispatcher("/tabmenu.html");
dispatcher.forward(request, response);
}else{
request.setAttribute("wrongUser",userName);
ServletContext context=getServletContext();
RequestDispatcher dispatcher=context.getRequestDispatcher("/fail");
dispatcher.forward(request, response);
}
} catch (SQLException e) {
e.printStackTrace();
}catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/**
* Servlet Filter implementation class RequestFilter
*/
@WebFilter("/RequestFilter")
public class RequestFilter implements Filter {
private static ThreadLocal<HttpServletRequest> localRequest = new ThreadLocal<HttpServletRequest>();
/**
* Default constructor.
*/
public RequestFilter() {
// TODO Auto-generated constructor stub
}
/**
* @see Filter#destroy()
*/
public void destroy() {
// TODO Auto-generated method stub
}
public static HttpServletRequest getRequest() {
System.out.println("Fetching the Request!!!");
return localRequest.get();
}
public static HttpSession getSession() {
System.out.println("Fetching the Session!!!");
HttpServletRequest request = localRequest.get();
return (request != null) ? request.getSession() : null;
}
/**
* @see Filter#doFilter(ServletRequest, ServletResponse, FilterChain)
*/
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
// place your code here
// pass the request along the filter chain
chain.doFilter(request, response);
if (request instanceof HttpServletRequest) {
localRequest.set((HttpServletRequest) request);
}
try {
chain.doFilter(request, response);
}
finally {
localRequest.remove();
}
}
/**
* @see Filter#init(FilterConfig)
*/
public void init(FilterConfig fConfig) throws ServletException {
// TODO Auto-generated method stub
}
}
}
采纳答案by home
There are at least 2 problems in your code:
您的代码中至少有两个问题:
The
@WebFilter("/RequestFilter")
annotation does not make sense to me. It MUST be set in a way to hit all incoming requests interested in the ThreadLocal value, e.g."/*"
.You pass the request twice to the chain. You must first set the
ThreadLocal
value, then forward to the chain, and finally remove theThreadLocal
value. Just remove the firstchain.doFilter(...)
invocation.public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // pass the request along the filter chain chain.doFilter(request, response); <-------------------- PROBLEM if (request instanceof HttpServletRequest) { localRequest.set((HttpServletRequest) request); } try { chain.doFilter(request, response); } finally { localRequest.remove(); } }
该
@WebFilter("/RequestFilter")
批注没有道理给我。它必须以某种方式设置以命中所有对 ThreadLocal 值感兴趣的传入请求,例如"/*"
。您将请求两次传递给链。您必须先设置
ThreadLocal
值,然后转发到链,最后删除ThreadLocal
值。只需删除第一个chain.doFilter(...)
调用。public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException { // pass the request along the filter chain chain.doFilter(request, response); <-------------------- PROBLEM if (request instanceof HttpServletRequest) { localRequest.set((HttpServletRequest) request); } try { chain.doFilter(request, response); } finally { localRequest.remove(); } }