how to show online user using servlet mapping - java

i want to show online users using this servlet ......
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.servlet.ServletContext;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.chatapp.useroperation.Client;
#WebServlet(name = "onlineUsersServlet", urlPatterns = { "/getOnlineUsersList" })
public class ListOfOnlineUsers extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {
String commaSepeparatedStr ="";
ServletContext appScope = request.getServletContext();
String channel = request.getParameter("channel");
final Map<String, List<Client>> clients = (Map<String, List<Client>>) appScope.getAttribute(LoginServlet.CLIENTS);
System.out.println(clients);
if(clients.size()> 0){
final List<Client> onlineClients = clients.get(channel);
if(onlineClients !=null){
for (Client client : onlineClients) {
if(commaSepeparatedStr.equals("") ){
commaSepeparatedStr = client.getUserName();
}else{
commaSepeparatedStr =commaSepeparatedStr+","+ client.getUserName();
}
}
}
}
response.getWriter().write(commaSepeparatedStr);
response.flushBuffer();
}
}
how can i pass value to this servlet from a jsp so that it store the username in its list......is it possible to put value in that servlet from session.

in your jsp do something like this:
<form action="/YOURWEBAPPNAME/onlineUsersServlet/getOnlineUsersList" method="get">
<input type="text" name="test" value="Hello World">
<input type="submit" value="Send">
</form>
in you doGet method do this:
String userInput = request.getParameter("test");
and feel free using that stuff.
put that stuff in the session with:
request.getSession(false).setAttribute("input",userInput);
and read it with:
String lInput = (String) request.getSession(false).getAttribute("input");

If you want to Store a Value from a session to a servlet, just attach an attribute to the Session;
During Login, get the username and store the value into the Session;
HttpSession sess = request.getSession();//Create new Session
//Get the username from login input
String username = request.getParameter("name");
//Attach the name to the Session.
sess.setAttribute("username", username);
Get the value anytime as long as the session is active.
HttpSession sess = request.getSession(false);//Use the current Session
//Get the value fron the Session
String username = (String) sess.getAttribute("username");//get the Attribute Username
You need to have Attached the Attribute to the Session before you can get it this way.

There are variables with a different scope that you can, or not, access from different places in your code. In JavaEE there are variables with request, session and application scope.
The request scope means that you can set it and use it in all your classes for the current request and that's what you seem to need right now.
I'm sorry I can't help you more right now but with this info Google or the SO search box should be your friend. I'll add details later.
Edit -
Stefan beike's answer has these details I'm talking about.

Related

Questions regarding JSP & servlet & MongoDB Mlab

I am new to MongoDB Mlab, which means not familiar with how to use it and how to connect it with a DAO file. And I encounter a technical issue on SERVLET. Firstly, I try to extract data from MongoDB mlab to get an email & password of a user for my login page. And I also capture the email & password entered by a user on login JSP page by using "request.getParameter("")" method. These two points work fine because I already tested them. More info about my issue is that when I try to extract email and password from MongoDB mlab, I store these two parameters into a user object, and store the user object into an ArrayList. Then return this Arraylist to the login Servlet. Using for-each loop to traversal this list. I put the codes below.
When I try to enter an email and password on the login page, this is the result I encountered
how can I solve it
FDao.java
package Dao;
import static com.sun.corba.se.spi.presentation.rmi.StubAdapter.request;
import java.net.UnknownHostException;
import java.sql.*;
import java.util.*;
import javax.servlet.RequestDispatcher;
import model.Book;
import model.Staff;
import model.User;
import org.bson.Document;
public class FDao {
public List<User> checkLogin() throws UnknownHostException {
Iterator it = DB.getDB().getCollection("users").find().iterator();
List<User> aUser = new ArrayList();
while(it.hasNext()){
Document o = (Document) it.next();
aUser.add(new User(o.getString("email"), o.getString("password")));
}
return aUser;
}
}
LoginServlet.java(I capture string email and string password from login JSP page)
#WebServlet("/Login")
public class LoginServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public LoginServlet() {
super();
}
FDao userDao = new FDao();
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
String email = request.getParameter("email");
String password = request.getParameter("pass");
List<User> users = new ArrayList();
users = userDao.checkLogin();
for (User user : users) {
if (email.equals(user.getEmail()) && password.equals(user.getPassword()) ) {
//HttpSession session = request.getSession();
//session.setAttribute("user", user);
request.getRequestDispatcher("/home.jsp").include(request, response); //the problem looks like appeared in this line of code
//out.println("Hello World");
} else {
//String message = "Your account does not exist in out database!";
//request.setAttribute("message", message); //message is object
request.getRequestDispatcher("/Login.jsp").include(request, response);//the problem looks like appeared in this line of code
//out.println("Nothing");
}
break;
}
}
}

Authenticate GET request from html extensions in AEM

Good day,
When a user hit specific url with an extension on html, I want to validate if user has logged in. If the user is not logged in, I want to redirect them to my custom login page (this part is done). Else, I want to do nothing - meaning the current page that they are on, should continue being displayed.
I want this to meet client requirements (the default AEM login page should stay as is.
Scenario
The page is /content/mysite/page.html
If I am not logged in, I should be redirected to /content/mysite/login.html
If I am logged in, I should still see this page : /content/mysite/page.html
Now, my problem comes when I am logged in. Instead of seeing content of the page : /content/mysite/page.html, there page is simply blank. There are no contents to be displayed.
Maybe I do not get the concepts of servlets or I do not know how to handle this kind of problem.
Please help resolve this or suggest another route to handle this
Here is my the code I have so far:
package com.company.patientsportal.core.auth;
import java.io.IOException;
import java.util.Map;
import javax.jcr.Repository;
import javax.jcr.Session;
import javax.servlet.ServletException;
import org.apache.felix.scr.annotations.Activate;
import org.apache.felix.scr.annotations.Properties;
import org.apache.felix.scr.annotations.Property;
import org.apache.felix.scr.annotations.Reference;
import org.apache.felix.scr.annotations.Service;
import org.apache.felix.scr.annotations.sling.SlingServlet;
import org.apache.sling.api.SlingHttpServletRequest;
import org.apache.sling.api.SlingHttpServletResponse;
import org.apache.sling.api.resource.ResourceResolver;
import org.apache.sling.api.servlets.SlingAllMethodsServlet;
import org.apache.sling.engine.SlingRequestProcessor;
#Service
#SlingServlet(resourceTypes={"patientsportal/components/structure/page"}, selectors="html", methods = "GET", metatype=true, description="My Authentication Verifier")
#Properties
(
{
#Property(name="login.form", description="The form on which the user to enter authentication credentials.", value="")
}
)
public class CheckAuthentication extends SlingAllMethodsServlet
{
/**
*
*/
private static final long serialVersionUID = 8552708551560032677L;
private Map<String, Object> redirects;
#Reference
private Repository repository;
#Reference
private SlingRequestProcessor requestProcessor;
#Override
protected void doGet(SlingHttpServletRequest request, SlingHttpServletResponse response) throws ServletException, IOException
{
ResourceResolver resolver = request.getResourceResolver();
Session session = resolver.adaptTo(Session.class);
String userId = session.getUserID();
String url = request.getRequestPathInfo().getResourcePath();
url = url.substring(0, url.lastIndexOf("/")) + ".html";
if (String.valueOf(userId) == null || (String.valueOf(userId) != null ? String.valueOf(userId).equals("anonymous") : false))
{
String loginForm = getLoginForm("login.form");
if (loginForm != null)
{
response.sendRedirect(loginForm + "?url=" + url);
}
else
{
response.sendRedirect("/content/patientsportal/login.html?url=" + url);
}
}
else
{
//Do nothing or something in the else
//So far, do nothing does not work. It returns blank page even if I do not include the else part
}
}
private String getLoginForm(String loginForm)
{
if (redirects != null)
{
loginForm = (String) redirects.get(loginForm);
return loginForm;
}
return null;
}
#Activate
protected void activate(Map<String, Object> properties)
{
redirects = properties;
}
}
The ideal way of implementing login functionality is to either use the OOTB AEM authentication handler or implement Sling AuthenticationHandler and extending DefaultAuthenticationFeedbackHandler. You can find the code references to implement in lot of blogs -
acs-aem-samples
How to Create Custom Authentication Handler in CQ
After you have implemented this and have created/configured your own login page /form, you need to setup CUG on the pages that are to be exposed only to a logged in user. The details around it are available in AEM documentation here

passing form values submitted in a servlet to a java class and hence inserting into database

The form values are submitted to the servlet and I need to retrieve those values into a class "RegisterDetails" and hence insert into the database "userdetails".. I used session to store the values and later retrieve it in the class file. Its a failure. How am I supposed to bring those values into the class file??? Later I need to pass the values into a jsp as well. Please instruct me. If there's any mistakes please help me...
Servlet: p1.java
import java.io.IOException;
import java.sql.Connection;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
//import reg.common.Co;
//import agge.db.geg;
//import agge.model.m_login;
import reg.db.RegisterDetails;
/**
* Servlet implementation class p1
*/
#WebServlet("/p1")
public class p1 extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public p1() {
super();
// TODO Auto-generated constructor stub
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session = request.getSession();
String a=request.getParameter("username1");
String b=request.getParameter("password1");
String c = request.getParameter("confirmpassword1");
String d = request.getParameter("email1");
String ee = request.getParameter("mob1");
String f =request.getParameter("address1");
System.out.println("Hai User "+a);
System.out.println("Password is "+b);
session.setAttribute("de", a);
session.setAttribute("de1", b);
session.setAttribute("de2", c);
session.setAttribute("de3", d);
session.setAttribute("de4", ee);
session.setAttribute("de5",f);
RegisterDetails details = new RegisterDetails();
session.setAttribute("details", details);
getServletContext().getRequestDispatcher("/jsp/Welcome.jsp").forward(request, response);
}
}
Class: RegisterDetails.java
package reg.db;
import javax.servlet.ServletRequest;
import javax.servlet.http.HttpSession;
import java.sql.*;
public class RegisterDetails {
String user13;
String pass13;
String confpassword13;
String email13;
String mobile13;
String address13;
private ServletRequest session;
String n=(String)session.getAttribute("de");
String n1=(String)session.getAttribute("de1");
String n2=(String)session.getAttribute("de2");
String n3=(String)session.getAttribute("de3");
String n4=(String)session.getAttribute("de4");
String n5=(String)session.getAttribute("de5");
public boolean insertDB() throws Exception {
Connection conn=null;
PreparedStatement st = null;
st=conn.prepareStatement("insert into user_details(username, password, confpassword, email,mobile, address) values ('" + n + "','" + n1 + "','" + n2 + "','" + n3 + "','" + n4 + "',' "+n5+ "')");
ResultSet rs =st.executeQuery();
boolean l_status=false;
while(rs.next()){
user13 = rs.getString("username");
pass13 = rs.getString("password");
confpassword13 = rs.getString("confpassword");
email13 = rs.getString("email");
mobile13 = rs.getString("mobile");
address13 = rs.getString("address");
}
return l_status=true;
}
}
Database connectivity: Dbconnect.java
package reg.common;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class Dbconnect {
Connection conn=null;
public Connection getConnection() {
try {
String driverName = "org.postgresql.Driver";
Class.forName(driverName).newInstance();
conn=DriverManager.getConnection("jdbc:postgresql://localhost:5432/postgres","postgres", "postgres");
}
catch (ClassNotFoundException e) {e.printStackTrace();
System.out.println("db Error1");
}
catch (SQLException e) {
e.printStackTrace();
System.out.println("DB Error 2");
}
catch (Exception e) {
}
return conn;
}
public void closeConnection(Connection connection) {
try{
connection.close();
}
catch (Exception e) {
}
}
}
jsp:Welcome.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# page import="reg.db.RegisterDetails" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>
Hai
<% RegisterDetails details = (RegisterDetails)session.getAttribute("details");%>
</body>
</html>
In your p1 servlet, you are setting your session attribute "details" with a new instance of RegisterDetails without setting any properties of that object (i.e. username, etc.).
Instead, you are setting those properties as cryptically named session attributes ("de", "de1" and so on).
This is likely to cause your issue (aside from all considerations in terms of architecture or security), since the RegisterDetails you retrieve will essentially be an empty object.
Try these few steps ...
1. Instead of storing the parameter values in various String objects, you should set the value of the data members of your RegisterDetails object
Create another class that specifically handles the job of working with the database (use the connection object in that class)
Create methods for CRUD operations in the above class and pass the RegisterDetails object.
Call the insert method of the newly created class from within your servlet and pass the RegisterDetails object in it
Once inserted then add the RegisterDetails object to the servlet request and dispatch the request to your jsp
You are setting the parameters received in your servlet into other session attributes and setting an empty RegisterDetails Object. Instead set the values received in the RegisterDetails object in you servlet. Something like this:-
RegisterDetails details = new RegisterDetails();
details.user13=request.getParameter("username1");
details.pass13=request.getParameter("password1");
details.confpassword13= request.getParameter("confirmpassword1");
details.email13= request.getParameter("email1");
details.mobile13 = request.getParameter("mob1");
details.address13 =request.getParameter("address1");
This should solve your issue, but apart from this I suggest to redesign your solution and follow coding best practices. Alteast generate getter/setter methods for you RegisterDetails class, and then set the object data memeber values using that, intead of directly accessing them.
Edit:- It seems that the access specifier of your data members for RegisterDetails is default, change it to public to access and assign them values, since your servlet and RegisterDetails classes are in different packages. Although the recommended approach would be to set them as private and generate public getter/setters.

Maintain Conversation After Exception (Handled in Pages.xml)

I'm working in a project that I didn't originally start, so there are a lot of artifacts and conventions that I cannot change without considerable effort. Anyway, here's the problem. I need to do multiple file uploads (that are "children" to the entity that is being edited on the "main" parent page) that get cached on the server so that they can be sent somewhere else if/when the user submits. The files uploaded also include metadata that the user enters. The best way I have figured to do this is to render a "dialog" that has an iframe that does the uploading and has the input for the metadata. Then I created an override (using install precedence) of Seam's multipart filter that uses the Apache file upload jar and a custom request wrapper that carries my information into the action call on the server. All goes well unless I throw an exception out of the filter, for example, if the request size is too big. The exception is caught and handled by a pages.xml declaration.
<exception class="org.jboss.seam.web.FileUploadException">
<redirect view-id="#{facesContext.externalContext.requestServletPath}">
<message severity='ERROR'>#{org.jboss.seam.handledException.message}</message>
</redirect>
</exception>
When I normally submit the form in my dialog frame, the conversation in the frame remains (as I want), when the exception is caught, I get a new one (as I don't want). I want the error messages passed by the exception shown in the global messages area of the frame, but I need to remain in the same conversation as before since the "children" that are being added in the dialog are children to the "parent" entity in the main page. Here is the form inside the frame code. I have tried s:button (does not submit the form), tried parameters, and tried hidden inputs with the conversation id.
<h:form id="attachmentModalForm" enctype="multipart/form-data" autocomplete="off" style="background-color: #FFFFFF;">
<ui:include src="layout/messages.xhtml" />
<div id="attachmentModalMain" class="modalMain">
<s:decorate id="attachmentDescriptionDecoration" template="layout/edit.xhtml" styleClass="twoCol">
<ui:define name="label">#{messages['contents.attachmentDialog.label.description']}<s:span styleClass="required">*</s:span></ui:define>
<h:inputText id="attachmentDescription" value="#{attachmentAction.description}" styleClass="textbox" />
</s:decorate>
<s:decorate id="attachmentFileDecoration" template="layout/edit.xhtml" styleClass="twoCol">
<ui:define name="label">#{messages['contents.attachmentDialog.label.file']}<s:span styleClass="required">*</s:span></ui:define>
<input id="attachmentFile" name="attachmentFile" type="file" />
</s:decorate>
</div>
<div id="attachmentModalSubmit" class="modalSubmit">
<h:commandButton id="attachmentSubmitButton" value="#{messages['action.text.submit']}" action="#{attachmentAction.addAttachment()}" onclick="attachmentSubmit();" />
<button id="attachmentCancelButton" type="button" value="#{messages['action.text.cancel']}" onclick="window.parent.hideAttachmentModal();">#{messages['action.text.cancel']}</button>
</div>
<input type="hidden" name="cid" value="#{conversation.id}" />
</h:form>
Here is the filter that overrides Seam's multipart filter.
package XXXXXXXXXXXXX.attachment;
import java.io.File;
import java.io.IOException;
import java.rmi.server.UID;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadBase.SizeLimitExceededException;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.jboss.seam.ScopeType;
import org.jboss.seam.annotations.Install;
import org.jboss.seam.annotations.Name;
import org.jboss.seam.annotations.Scope;
import org.jboss.seam.annotations.intercept.BypassInterceptors;
import org.jboss.seam.annotations.web.Filter;
import org.jboss.seam.web.AbstractFilter;
/**
* This filter is used to override Seam's multipart filter so that we
* can have multiple temporary files on the server cued and ready to
* go to XXXXXXXXX. It uses the Apache Commons FileUpload objects to
* handle the parsing of the request and the temporary files.
*
*/
#Scope(ScopeType.APPLICATION)
#Name("org.jboss.seam.web.multipartFilter")
#Install(precedence = Install.APPLICATION)
#BypassInterceptors
#Filter(within={"org.jboss.seam.web.ajax4jsfFilter", "org.jboss.seam.web.exceptionFilter"})
public class MEDWareMultipartFilter extends AbstractFilter {
// This is unused, we always want temp files since we are caching before upload to XXXXXXXXX.
// Leaving it in to mirror Seam's multipart filter, in case it gets set from the components.xml.
#SuppressWarnings("unused") private boolean createTempFiles = true;
private int maxRequestSize = -1;
private String acceptedFileExtensions = "txt,pdf,doc,docx,xls,xlsx";
public void setCreateTempFiles(boolean createTempFiles) { }
public void setMaxRequestSize(int maxFileSize) {
this.maxRequestSize = maxFileSize;
}
public String getAcceptedFileExtensions() {
return acceptedFileExtensions;
}
public void setAcceptedFileExtensions(String acceptedFileExtensions) {
this.acceptedFileExtensions = acceptedFileExtensions;
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
if (!(response instanceof HttpServletResponse)) {
chain.doFilter(request, response);
return;
}
HttpServletRequest httpRequest = (HttpServletRequest) request;
if (ServletFileUpload.isMultipartContent(httpRequest)) {
File repository = (File) this.getServletContext().getAttribute("javax.servlet.context.tempdir");
DiskFileItemFactory factory = new DiskFileItemFactory(0, repository);
ServletFileUpload upload = new ServletFileUpload(factory);
upload.setSizeMax(maxRequestSize);
List<FileItem> formItems = null;
try {
formItems = upload.parseRequest(httpRequest);
} catch (SizeLimitExceededException slee) {
throw new org.jboss.seam.web.FileUploadException("File size excededs maximum allowed.", slee);
} catch (FileUploadException fue) {
throw new org.jboss.seam.web.FileUploadException("Error uploading file.", fue);
}
Map<String, String> parameters = new HashMap<String, String>();
Map<String, File> fileParameters = new HashMap<String, File>();
if (formItems != null && formItems.size() > 0) {
for (FileItem item : formItems) {
if (item.isFormField()) {
parameters.put(item.getFieldName(), item.getString());
} else {
String fileName = item.getName();
// This is for IE7 (and Safari?) which sends the whole path.
fileName = fileName.substring(fileName.lastIndexOf("\\") + 1);
if (!MyMultipartRequestUtils.isValidFileType(acceptedFileExtensions, fileName)) {
throw new org.jboss.seam.web.FileUploadException("The file type is not an accepted file type.");
}
File tempFile = null;
try {
tempFile = File.createTempFile(new UID().toString().replace(":", "-"), ".upload");
tempFile.deleteOnExit();
item.write(tempFile);
} catch (Exception e) {
throw new org.jboss.seam.web.FileUploadException("Error uploading file. Could not write file to server.");
}
fileParameters.put(fileName, tempFile);
}
}
}
MyMultipartRequestWrapper requestWrapper = new MyMultipartRequestWrapper(httpRequest, parameters, fileParameters);
chain.doFilter(requestWrapper, response);
} else {
chain.doFilter(request, response);
}
}
}
So, to reiterate, if I use the frame to upload files, everything works and the frame continues on the same conversation adding each child to the parent, if I upload a file that is too big, I get the correct message in the global message area of the frame, but the conversation get incremented and then the children are obviously being added to a new parent entity in the new conversation. Any help would be greatly appreciated.
I just ended up adding a field to my custom request wrapper to carry any exceptions I wanted to handle and then handled them in the
#{attachmentAction.addAttachment()}
action call further up the request chain. All works now, I just add my faces messages from there and the conversation does not get incremented the same as if I had a successful upload.

User (session) count in cluster

Is there a good way to get the logged in user count in a Java web application that is running in a cluster?
I wrote a simple HttpSessionListener with a static field, but I suppose this doesn't work in cluster. I can see there is a Spring Security solution, but I read in some forums that this is still not ok in cluster.
The product in which I have to implement this user count is trying to be application server independent, currently we support Tomcat, Weblogic and JBoss. At the moment I need a solution for Weblogic 10.3 clusters.
You can maintain the counter in database which will work in cluster env.
A simple tutorial to demonstrate how to determine active users / sessions in a Java Web Application.
package com.hubberspot.javaee.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;
#WebListener
public class OnlineUsersCounter implements HttpSessionListener {
private static int numberOfUsersOnline;
public OnlineUsersCounter() {
numberOfUsersOnline = 0;
}
public static int getNumberOfUsersOnline() {
return numberOfUsersOnline;
}
public void sessionCreated(HttpSessionEvent event) {
System.out.println("Session created by Id : " + event.getSession().getId());
synchronized (this) {
numberOfUsersOnline++;
}
}
public void sessionDestroyed(HttpSessionEvent event) {
System.out.println("Session destroyed by Id : " + event.getSession().getId());
synchronized (this) {
numberOfUsersOnline--;
}
}
}
Running the below servlet on three different browsers will provide output as : (see fig below)
package com.hubberspot.javaee;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import com.hubberspot.javaee.listener.OnlineUsersCounter;
// #WebServlet annotation has a initParams field which takes
// in initialization parameters for a servlet.
// #WebInitParam annotation takes in a name and value for the
// initialization parameters for the current Servlet.
#WebServlet(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" }
, initParams = { #WebInitParam(name = "user" , value = "Jonty") })
public class HelloWorldServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
// sessionCreated method gets executed
HttpSession session = request.getSession();
session.setMaxInactiveInterval(60);
try {
out.println("<html>");
out.println("<body>");
out.println("<h2>Number of Users Online : "
+ OnlineUsersCounter.getNumberOfUsersOnline()
+ "</h2>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
Output of the program :
Eclipse Browser ->
Firefox Browser ->
Internet Explorer Browser ->
Console Output ->
For more: http://www.hubberspot.com/2013/09/how-to-determine-active-users-sessions.html

Categories