i want session Object not in servlet class but ordinary from we application.
WEB.XML
I don't think it's possible, to directly access session and request object. What you can do is pass the session and/or request object from servlet to a Java class either in some method or in constructor of the Java class.
There are multiple ways to do that, but.. don't. Only your web layer should have access to the session. The other layers should only get the parameters from the session that it needs. For example:
service.doSomeBusinessLogic(
session.getAttribute("currentUser"),
session.getAttribute("foo"));
The options that you have to obtain the request, and from it - the session in a non-servlet class, that is still in the web layer:
ThreadLocal
in a Filter
(and clean it afterwards)call this:
RequestFilter.getSession();
RequestFilter.getRequest();
on your custom filter:
public class RequestFilter implements Filter {
private static ThreadLocal<HttpServletRequest> localRequest = new ThreadLocal<HttpServletRequest>();
public static HttpServletRequest getRequest() {
return localRequest.get();
}
public static HttpSession getSession() {
HttpServletRequest request = localRequest.get();
return (request != null) ? request.getSession() : null;
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (servletRequest instanceof HttpServletRequest) {
localRequest.set((HttpServletRequest) servletRequest);
}
try {
filterChain.doFilter(servletRequest, servletResponse);
} finally {
localRequest.remove();
}
}
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void destroy() {
}
}
that you'll register it into your web.xml file:
<filter>
<filter-name>RequestFilter</filter-name>
<filter-class>your.package.RequestFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>RequestFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>