Counting the number of users in web App in servlet - java

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,...

Related

How to set Priority Order of displaying context param parameters on server?

I am trying to get the parameters names in a Servlet Context object from context param elements in an order given in the web.xml file. But on running code on the server, displayed parameter order is not the same as to mention in the web.xml file.
DemoServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class DemoServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter pw=response.getWriter();
ServletContext context=getServletContext();
//we are getting all the initialization parameter from the web.xml file
Enumeration<String> e=context.getInitParameterNames();
while(e.hasMoreElements()) {
String s=e.nextElement();
pw.println("<br>"+context.getInitParameter(s));
}
pw.close();
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>Servlet6ServletContextInterface2</display-name>
<servlet>
<servlet-name>demo</servlet-name>
<servlet-class>DemoServlet</servlet-class>
</servlet>
<context-param>
<param-name>DriverName</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<context-param>
<param-name>Username</param-name>
<param-value>Pranay Singh</param-value>
</context-param>
<context-param>
<param-name>Password</param-name>
<param-value>abc123</param-value>
</context-param>
<servlet-mapping>
<servlet-name>demo</servlet-name>
<url-pattern>/context</url-pattern>
</servlet-mapping>
</web-app>
Expected Results:
com.mysql.jdbc.Driver Pranay Singh abc123
Actual Results:
Pranay Singh com.mysql.jdbc.Driver abc123
The params are intended to be accessed by their name, so the orders are not guaranteed.
If you really need them in a specific order, you can hard-code the param names (in your own order) into a collection:
List<String> paramNames = Arrays.asList("DriverName", "Username", "Password");
for(String paramName: paramNames) {
pw.println("<br>" + context.getInitParameter(paramName));
}
Or if you want to keep the params dynamic without hard-coding anything, you can at least sort them.
Enumeration<String> e = context.getInitParameterNames();
List<String> paramNames = Collections.list(e);
Collections.sort(paramNames);
for(String paramName: paramNames) {
pw.println("<br>" + context.getInitParameter(paramName));
}

Url doesn't match url-pattern in web.xml

In the web.xml file I have this url pattern:
<url-pattern>/servletPrueba/*</url-pattern>
and in the jsp file I have this link:
Enlace servlet
But I get a 404 error, I think the url matches the url pattern, doesn't it?
here is the servlet,it's onle a test purposes servlet,only for practice
package pruebas;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.RequestDispatcher;
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 servletPrueba
*/
//#WebServlet("/servletPrueba")
public class servletPrueba extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public servletPrueba() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//response.getWriter().append("Served at: ").append(request.getContextPath());
RequestDispatcher despachador = null;
String ruta = request.getPathInfo();
PrintWriter out = response.getWriter();
out.println(request.getPathInfo());
out.println(request.getServletPath());
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
//doGet(request, response);
PrintWriter out = response.getWriter();
out.println("POST");
}
}
webb.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>pruebas</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>servletPrueba</servlet-name>
<servlet-class>pruebas.servletPrueba</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servletPrueba</servlet-name>
<url-pattern>/servletPrueba/*</url-pattern>
</servlet-mapping>
</web-app>
Here is a complete example (I did not use Maven, however I could) :

Getting HTTP Status 400 error while running a Servlet class using Tomcat server

I am totally new to writing servlets. I have created a simple HelloWorld program, but while running the application I'm getting the following error:
HTTP Status 404 - /HelloWorld/HelloWorld
type Status report
message /HelloWorld/HelloWorld
description: The requested resource is not available.
Below is my code:
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("/HelloWorld")
public class HelloWorld extends HttpServlet {
private static final long serialVersionUID = 1L;
public HelloWorld() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out=response.getWriter();
out.println("Hello World");
}
}
And my web.xml
<display-name>HelloWorld</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>
I'm using Tomcat version:7.0 and my IDE is Eclipse Luna. Why is this error being thrown?
your_war_file_name/HelloWorld... You can find the war file name under webapps folder in Tomcat directory. Here I just recreated the same. My war file name is website.war. It works for me. The url is http://localhost:8090/website/developer . I got the response "Hello World" .... :)
package com.test.developer;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Test extends HttpServlet{
private static final long serialVersionUID = 1L;
public Test() {
super();
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("Inside servelt");
PrintWriter out=response.getWriter();
out.println("Hello World");
}
}
and my 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>website</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>developer</servlet-name>
<servlet-class>com.test.developer.Test</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>developer</servlet-name>
<url-pattern>/developer</url-pattern>
</servlet-mapping>
</web-app>

Filter servlet not working with glassfish in netbeans

This is my 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_2_5.xsd" id="WebApp_ID" version="2.5">
<filter>
<display-name>MyFilter</display-name>
<filter-name>MyFilter</filter-name>
<filter-class>AB_DB.MyFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>MyFilter</filter-name>
<url-pattern>/MyFilter</url-pattern>
</filter-mapping>
<servlet>
<description></description>
<display-name>Profile</display-name>
<servlet-name>Profile</servlet-name>
<servlet-class>AB_DB.Profile</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Profile</servlet-name>
<url-pattern>/Profile</url-pattern>
</servlet-mapping>
</web-app>
This is the filter servlet I've tried
package AB_DB;
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 javax.servlet.http.HttpServletRequest;
public class MyFilter implements Filter {
public MyFilter() {
}
public void destroy() {
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
String requri = ((HttpServletRequest) request).getRequestURI().substring(((HttpServletRequest) request).getContextPath().length() + 1);
System.out.println(requri);
//if request uri starts with user/ then system will forward the request to Profile servlet
if (requri.startsWith("user/")) {
//get userid from request uri
String id = requri.substring(5);
System.out.println(id);
//set attribute "user" with userid value
request.setAttribute("user", id);
//forward the request to Profile servlet
request.getRequestDispatcher("/Profile")
.forward(request, response);
} else {
chain.doFilter(request, response);
}
}
public void init(FilterConfig fConfig) throws ServletException {
}
}
However in the GlassFish 4 server log, there is no errors at all when running the project. The URI isnt even being printed out with 'System.out.println(id);' so I assume that the filter isnt even being injected.
Can anyone see any issues with my code? The sevlet Profile isn't being ran
You have mapped oyur filter to /MyFilter
<url-pattern>/MyFilter</url-pattern>
and that doesn't match with URL you are requesting
/user/Surname1993
so your filter won't get invoked

Can't compile servlet file.

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.

Categories

Resources