After successfully able to run a WAR through jetty, I am trying to embed jetty server into my web-application. It is a normal java application consisting servlet. I have used exploded WAR directory (WARless).
But I get the following exception.
2014-02-22 16:27:08.271:INFO:oejw.StandardDescriptorProcessor:NO JSP Support for /, did not find org.apache.jasper.servlet.JspServlet
2014-02-22 16:27:08.319:WARN:oejs.Holder:
java.lang.ClassNotFoundException: ClientServlet
at java.net.URLClassLoader$1.run(Unknown Source)
at java.net.URLClassLoader$1.run(Unknown Source)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(Unknown Source)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:421)
at org.eclipse.jetty.webapp.WebAppClassLoader.loadClass(WebAppClassLoader.java:383)
at org.eclipse.jetty.util.Loader.loadClass(Loader.java:100)
at org.eclipse.jetty.util.Loader.loadClass(Loader.java:79)
at org.eclipse.jetty.servlet.Holder.doStart(Holder.java:107)
at org.eclipse.jetty.servlet.ServletHolder.doStart(ServletHolder.java:298)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.servlet.ServletHandler.initialize(ServletHandler.java:791)
at org.eclipse.jetty.servlet.ServletContextHandler.startContext(ServletContextHandler.java:265)
at org.eclipse.jetty.webapp.WebAppContext.startContext(WebAppContext.java:1242)
at org.eclipse.jetty.server.handler.ContextHandler.doStart(ContextHandler.java:717)
at org.eclipse.jetty.webapp.WebAppContext.doStart(WebAppContext.java:494)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at org.eclipse.jetty.server.handler.HandlerWrapper.doStart(HandlerWrapper.java:95)
at org.eclipse.jetty.server.Server.doStart(Server.java:282)
at org.eclipse.jetty.util.component.AbstractLifeCycle.start(AbstractLifeCycle.java:64)
at com.jetty.RunJetty.main(RunJetty.java:24)
2014-02-22 16:27:08.321:WARN:/:unavailable
Embedded jetty Server code
package com.jetty;
import org.eclipse.jetty.server.Server;
import org.eclipse.jetty.webapp.WebAppContext;
public class RunJetty {
public RunJetty() {
}
public static void main(String[] args) {
Server server=new Server(8080);
WebAppContext wac = new WebAppContext();
wac.setResourceBase("C:/Users/User/j2ee/workspace/CLient1");
wac.setDescriptor("C:/Users/User/j2ee/workspace/CLient1/WebContent/WEB-INF/web.xml");
wac.setContextPath("/");
wac.setParentLoaderPriority(true);
server.setHandler(wac);
try {
server.start();
server.join();
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Servlet Code
package com.jetty;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.omg.CORBA.RepositoryIdHelper;
public class ClientServlet extends HttpServlet {
private static final long serialVersionUID = 8120079003868426157L;
private String greeting="Hello World";
public ClientServlet(){}
public ClientServlet(String greeting)
{
this.greeting=greeting;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
response.setStatus(HttpServletResponse.SC_OK);
response.getWriter().println("<h1>"+greeting+"</h1>");
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>kajh</display-name>
<servlet>
<description></description>
<display-name>ClientServlet</display-name>
<servlet-name>ClientServlet</servlet-name>
<servlet-class>ClientServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ClientServlet</servlet-name>
<url-pattern>/ClientServlet</url-pattern>
</servlet-mapping>
</web-app>
Additionally, I want to use response.sendRedirect in my servlet. Something like,
public class ClientServlet extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = 8120079003868426157L;
private String greeting="Hello World";
public ClientServlet(){}
public ClientServlet(String greeting)
{
this.greeting=greeting;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException
{
response.setContentType("text/html");
response.sendRedirect("http://localhost:8080/CLient1/index.html");
}
}
Please help! I am stuck on this like forever.
Thank you in advance!
Also I am adding the folder structure of my application to have a better understanding
I think the servlet-class should be
<servlet-class>com.jetty.ClientServlet</servlet-class>
Edit: Made it show the codeformat also.
Related
This question already has answers here:
#WebServlet fails in Netbeans 11.0 with java.lang.RuntimeException: com.example.NewServlet.<init>(NewServlet.java:1)
(2 answers)
Closed 2 years ago.
When I run a web application with Java 8, Tomcat 8, Netbeans 8, it runs perfectly fine. Running the same application with Netbeans 11, the below error occurs, even though it is still Java 8, Tomcat 8 in Netbeans 11.
This is the tomcat error log.
Mar 05, 2020 9:30:40 AM org.apache.catalina.core.StandardContext filterStart
SEVERE: Exception starting filter DatabaseCheckFilter
java.lang.RuntimeException:
at filters.DatabaseCheckFilter.<init>(DatabaseCheckFilter.java:1)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
at sun.reflect.NativeConstructorAccessorImpl.newInstance(NativeConstructorAccessorImpl.java:62)
at sun.reflect.DelegatingConstructorAccessorImpl.newInstance(DelegatingConstructorAccessorImpl.java:45)
at java.lang.reflect.Constructor.newInstance(Constructor.java:423)
at java.lang.Class.newInstance(Class.java:442)
at org.apache.catalina.core.ApplicationFilterConfig.getFilter(ApplicationFilterConfig.java:275)
at org.apache.catalina.core.ApplicationFilterConfig.setFilterDef(ApplicationFilterConfig.java:424)
at org.apache.catalina.core.ApplicationFilterConfig.<init>(ApplicationFilterConfig.java:115)
at org.apache.catalina.core.StandardContext.filterStart(StandardContext.java:4072)
at org.apache.catalina.core.StandardContext.start(StandardContext.java:4726)
at org.apache.catalina.core.ContainerBase.addChildInternal(ContainerBase.java:799)
at org.apache.catalina.core.ContainerBase.addChild(ContainerBase.java:779)
at org.apache.catalina.core.StandardHost.addChild(StandardHost.java:601)
at org.apache.catalina.startup.HostConfig.deployDescriptor(HostConfig.java:675)
at org.apache.catalina.startup.HostConfig.deployDescriptors(HostConfig.java:601)
at org.apache.catalina.startup.HostConfig.deployApps(HostConfig.java:502)
at org.apache.catalina.startup.HostConfig.start(HostConfig.java:1317)
at org.apache.catalina.startup.HostConfig.lifecycleEvent(HostConfig.java:324)
at org.apache.catalina.util.LifecycleSupport.fireLifecycleEvent(LifecycleSupport.java:142)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1065)
at org.apache.catalina.core.StandardHost.start(StandardHost.java:840)
at org.apache.catalina.core.ContainerBase.start(ContainerBase.java:1057)
at org.apache.catalina.core.StandardEngine.start(StandardEngine.java:463)
at org.apache.catalina.core.StandardService.start(StandardService.java:525)
at org.apache.catalina.core.StandardServer.start(StandardServer.java:754)
at org.apache.catalina.startup.Catalina.start(Catalina.java:595)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at org.apache.catalina.startup.Bootstrap.start(Bootstrap.java:289)
at org.apache.catalina.startup.Bootstrap.main(Bootstrap.java:414)
The code for the class is
package filters;
import dataaccesslayer.DatabaseCheck;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import utilities.exceptions.ExceptionLogger;
public class DatabaseCheckFilter implements Filter {
// The filter configuration object we are associated with. If
// this value is null, this filter instance is not currently
// configured.
private FilterConfig filterConfig = null;
public DatabaseCheckFilter() {
}
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {
boolean databaseError = false;
try {
DatabaseCheck check = new DatabaseCheck();
databaseError = check.Check(response);
if (databaseError == true) {
RequestDispatcher fd=request.getRequestDispatcher("/error/unavailable.jsp");
fd.forward(request,response);
}
else {
chain.doFilter(request, response);
}
} catch (Exception exception) {
ExceptionLogger.logException(exception);
}
}
public FilterConfig getFilterConfig() {
return (this.filterConfig);
}
public void setFilterConfig(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
public void destroy() {
}
public void init(FilterConfig filterConfig) {
this.filterConfig = filterConfig;
}
}
An extract from the web.xml is
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<filter>
<filter-name>UserInfoFilter</filter-name>
<filter-class>filters.UserInfoFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UserInfoFilter</filter-name>
<url-pattern>/scheduler.jsp</url-pattern>
</filter-mapping>
<filter>
<filter-name>DatabaseCheckFilter</filter-name>
<filter-class>filters.DatabaseCheckFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>DatabaseCheckFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
Netbeans 11+ version solved this problem.
Running the just released Netbeans 11.3 fixed this problem.
I have a SpringBoot application running on WebLogic Server Version: 12.2.1.3.0
When I define a custom servlet Filter its working fine on Embedded Tomcat. However, when i deploy my application as a war file to wlserver it throws following error after each request. What am i missing here?
<Could not load user defined filter in web.xml: com.thy.bwsadmin.CORSFilter.
java.lang.AbstractMethodError
at weblogic.servlet.internal.FilterManager$FilterInitAction.run(FilterManager.java:400)
at weblogic.security.acl.internal.AuthenticatedSubject.doAs(AuthenticatedSubject.java:328)
at weblogic.security.service.SecurityManager.runAsForUserCode(SecurityManager.java:197)
at weblogic.servlet.provider.WlsSecurityProvider.runAsForUserCode(WlsSecurityProvider.java:203)
at weblogic.servlet.provider.WlsSubjectHandle.run(WlsSubjectHandle.java:71)
at weblogic.servlet.internal.FilterManager.initFilter(FilterManager.java:130)
at weblogic.servlet.internal.FilterManager.loadFilter(FilterManager.java:92)
at weblogic.servlet.internal.FilterManager.preloadFilters(FilterManager.java:72)
at weblogic.servlet.internal.WebAppServletContext.preloadResources(WebAppServletContext.java:1928)
at weblogic.servlet.internal.WebAppServletContext.start(WebAppServletContext.java:3106)
at weblogic.servlet.internal.WebAppModule.startContexts(WebAppModule.java:1843)
at weblogic.servlet.internal.WebAppModule.start(WebAppModule.java:884)
at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:360)
at weblogic.application.internal.ExtensibleModuleWrapper$StartStateChange.next(ExtensibleModuleWrapper.java:356)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
at weblogic.application.internal.ExtensibleModuleWrapper.start(ExtensibleModuleWrapper.java:138)
at weblogic.application.internal.flow.ModuleListenerInvoker.start(ModuleListenerInvoker.java:124)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:233)
at weblogic.application.internal.flow.ModuleStateDriver$3.next(ModuleStateDriver.java:228)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
at weblogic.application.internal.flow.ModuleStateDriver.start(ModuleStateDriver.java:78)
at weblogic.application.internal.flow.StartModulesFlow.activate(StartModulesFlow.java:52)
at weblogic.application.internal.BaseDeployment$2.next(BaseDeployment.java:752)
at weblogic.application.utils.StateMachineDriver.nextState(StateMachineDriver.java:45)
at weblogic.application.internal.BaseDeployment.activate(BaseDeployment.java:262)
This is the content of my web.xml file
<web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<display-name>MWSAdminService</display-name>
<filter>
<filter-name>CORSFilter</filter-name>
<filter-class>com.sample.CORSFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CORSFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
I am setting servlet dependency as provided to prevent jar conflicts.
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<scope>provided</scope>
</dependency>
This is my Filter class.
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import com.thy.bwsadmin.service.SecurityUserService;
#Component
#Order(Ordered.HIGHEST_PRECEDENCE)
public class CORSFilter implements Filter {
#Autowired
SecurityUserService securityUserService;
#Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
throws IOException, ServletException {
HttpServletResponse response = (HttpServletResponse) res;
HttpServletRequest request = (HttpServletRequest) req;
boolean isAuthenticated = authenticateUser(request.getHeader("identity_no"), request.getRequestURI());
if (isAuthenticated) {
if ("OPTIONS".equalsIgnoreCase(request.getMethod())) {
response.setStatus(HttpServletResponse.SC_OK);
} else {
chain.doFilter(req, res);
}
} else {
response.sendError(HttpServletResponse.SC_OK, "401");
}
}
private boolean authenticateUser(String userId, String requestURI) {
if (Util.isNotEmpty(userId)
&& securityUserService.isAuthorizedForEndpoint(userId.trim(), requestURI)) {
return true;
}else{
return false;
}
}
}
As a solution i tried to remove the filter definitions in web.xml file and registered my filter as a bean configuration since this is a SpringBoot application. I also removed #Component and #Order annotations from my filter.
But the result was the same as above. It is still working on Tomcat but not in Weblogic. Here is the code for filter config bean.
#Configuration
public class Filters {
#Bean
public FilterRegistrationBean<CORSFilter> loggingFilter() {
FilterRegistrationBean<CORSFilter> registrationBean = new FilterRegistrationBean<>();
registrationBean.setFilter(new CORSFilter());
registrationBean.addUrlPatterns("/*");
return registrationBean;
}
}
Your servlet api provided by weblogic is probably old version and your filter class needs to override init method.
Add below code at your filter class;
#Override
public void init(FilterConfig filterConfig) throws ServletException {};
At new versions of servlet api, filter class has default empty init method.
Here is the web.xml code:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>Projeto_joas</display-name>
<resource-ref>
<res-ref-name>jdbc/DiaDiaDev</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<servlet>
<display-name>FacesServlet</display-name>
<servlet-name>FacesServlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>FacesServlet</servlet-name>
<url-pattern>*.jsf</url-pattern>
</servlet-mapping>
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<context-param>
<param-name>com.sun.faces.expressionFactory</param-name>
<param-value>com.sun.el.ExpressionFactoryImpl</param-value>
</context-param>
<!-- <filter> -->
<!--<filter-name>FilterHibernate</filter-name> -->
<!--<filter-class>util.filter.ConexaoHibernateFilter</filter-class> -->
<!--</filter> -->
<!--<filter-mapping> -->
<!-- <filter-name>FilterHibernate</filter-name> -->
<!--<url-pattern>*.jsf</url-pattern> -->
<!--</filter-mapping> -->
</web-app>
The server runs just fine this way, if i remove the comments on the filter, it won't
start and will throw me those exceptions:
SEVERE: A child container failed during start
java.util.concurrent.ExecutionException: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
Caused by: org.apache.catalina.LifecycleException: Failed to start component [StandardEngine[Catalina].StandardHost[localhost]]
Caused by: org.apache.catalina.LifecycleException: A child container failed during start
and
WARNING: Failed to retrieve JNDI naming context for container [StandardEngine[Catalina].StandardHost[localhost].StandardContext[/Projeto_joas]] so no cleanup was performed for that container
javax.naming.NamingException: No naming context bound to this class loader
the Filter class:
package util.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import org.hibernate.SessionFactory;
import util.HibernateUtil;
public class ConexaoHibernateFilter implements Filter {
private SessionFactory sf;
#Override
public void init(FilterConfig arg0) throws ServletException {
this.sf = HibernateUtil.getSessionFactory();
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
FilterChain chain) throws IOException, ServletException {
try {
this.sf.getCurrentSession().beginTransaction();
chain.doFilter(servletRequest, servletResponse);
this.sf.getCurrentSession().getTransaction().commit();
this.sf.getCurrentSession().close();
} catch (Throwable ex) {
try {
if (this.sf.getCurrentSession().getTransaction().isActive()) {
this.sf.getCurrentSession().getTransaction().rollback();
}
} catch (Throwable t) {
t.printStackTrace();
}
throw new ServletException(ex);
}
}
#Override
public void destroy() {
// TODO Auto-generated method stub
}
}
For me also same error was coming. The mistake I did was I didn't add any body to destroy and init methods.
So for me it worked by simply added some print statement inside the body of the destroy and init method.
#Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
response.setContentType("text/html");
PrintWriter pw = response.getWriter();
pw.println("Error 404 bad request");
// chain.doFilter(request, response);
}
#Override
public void destroy() {
System.out.println("destroyed"); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
#Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("initilized"); // Generated from nbfs://nbhost/SystemFileSystem/Templates/Classes/Code/GeneratedMethodBody
}
I was testing a demo servlet file But, the servlet doesn't seem to respond. I'm not able to understand the problem.
When I click submit on the HTML form the URL is
localhost:8080/Beer-V1/SelectBeer.do
But, shouldn't it be /BeerSelect? Because of #WebServlet("/BeerSelect") ???
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web- app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" metadata-complete="false"
version="3.0">
<servlet>
<servlet-name>CH3 Beer</servlet-name>
<servlet-class>com.example.web.BeerSelect</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CH3 Beer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping>
</web-app>
BeerSelect.java
package com.example.web;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
#WebServlet("/BeerSelect")
public class BeerSelect extends HttpServlet {
private static final long serialVersionUID = 1L;
public BeerSelect() {
super();
}
#Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Beer Selection Advice<br>");
String c = request.getParameter("color");
out.println("<br> Got Beer Color " + c);
}
}
When I click submit on the HTML form the URL is localhost:8080/Beer-V1/SelectBeer.do
But, shouldn't it be /BeerSelect? Because of #WebServlet("/BeerSelect") ???
web-container associates a "context-path" for each of the web-application deployed and in your case, I believe it is "Beer-V1".
You have overridden the mapping in web.xml as below and hence you are seeing *.do
<servlet-mapping>
<servlet-name>CH3 Beer</servlet-name>
<url-pattern>/SelectBeer.do</url-pattern>
</servlet-mapping>
The xml DD overrides the annotations.
I have modified my application to find out the number of users logged in a web application below is my piece of code..
the listener class
import javax.servlet.ServletContext;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
public class SessionCounter implements HttpSessionListener
{
private static int count;
public static int getActiveSessions() {
return count;
}
public SessionCounter()
{
}
//The "sessionCount" attribute which has been set in the servletContext should not be modified in any other part of the application.
//Since we are using serveltContext in both the methods to modify the same variable, we have synchronized it for consistency.
public void sessionCreated(HttpSessionEvent e)
{
count++;
ServletContext sContext = e.getSession().getServletContext();
synchronized (sContext)
{
sContext.setAttribute("sessionCount", new Integer(count));
}
}
public void sessionDestroyed(HttpSessionEvent e)
{
count--;
ServletContext sContext = e.getSession().getServletContext();
synchronized (sContext)
{
sContext.setAttribute("sessionCount", new Integer(count));
}
}
}
and the main servlet is ..
package com.saral;
import java.io.IOException;
import org.apache.log4j.Logger;
import org.apache.log4j.PropertyConfigurator;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet implementation class First
*/
//#WebServlet("/First")
public class MyServlet extends HttpServlet
{
private static final long serialVersionUID = 1L;
static final Logger logger = Logger.getLogger(MyServlet.class);
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PropertyConfigurator.configure("log4j.properties");
logger.info("before---->");
// TODO Auto-generated method stub
String name=request.getParameter("txtName");
response.setContentType("text/html");
PrintWriter out=response.getWriter();
out.println("Hello,"+name);
out.println("<br> this output is generated by a simple servlet.");
out.println("Total Number of users logged in--->"+SessionCounter.getActiveSessions());
out.close();
}
}
and the web.xml is ...
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>FirstDemo</display-name>
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/log4j.properties</param-value>
</context-param>
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.saral.MyServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/helloServlet</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>home.html</welcome-file>
</welcome-file-list>
<listener>
<listener-class>com.saral.SessionCounter</listener-class>
</listener>
</web-app>
but I am getting the total number of users logged in as 0 , which is not perfect, please advise where I am wrong and how can I overcome from this.
When a client request come to the Tomcat server and you don't call request.getSession(), then the Tomcat server stil creates a session automatically. After that, the method sessionCreated(...) in your SessionCounter class is called.
The method sessionDestroyed(...) will be called when a session is destroyed. That occurs when you call session.invalidate(). If you close a tab on browser or close a browser, the session is still alive on your tomcat server.
I think so. You can use some diffrent listeners to archive your goal: HttpSessionAttributeListener, HttpSessionBindingListener,...