Video tutorial to demonstrate how to send an Email using Java Mail API in a Java web application.
Click here to download source code
Everything you want to know about Java.
package com.hubberspot.javaee.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 javax.servlet.annotation.WebFilter;
// @WebFilter annotation makes HostFilter class
// a filter in Java EE application. /* tells
// annotation that filter each and every request
// coming to server. Here the filter prints IP
// address of the request on the console.
@WebFilter("/*")
public class HostFilter implements Filter {
private FilterConfig filterConfig;
public void destroy() {
System.out.println("Destroyed ... ");
}
public void doFilter(
ServletRequest request,
ServletResponse response,
FilterChain chain)
throws IOException, ServletException {
String ipAddress = request.getRemoteHost();
System.out.println("Remote IP Address : " + ipAddress);
// pass the request along the filter chain
chain.doFilter(request, response);
}
public void init(FilterConfig fConfig) throws ServletException {
this.filterConfig = fConfig;
}
}
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;
// @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();
try {
out.println("<html>");
out.println("<body>");
out.println("<h2>Hello "
+ getServletConfig().getInitParameter("user")
+ "</h2>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
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--;
}
}
}
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();
}
}
}
package com.hubberspot.listener;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
// @WebListener annotation informs container that
// this class is a web listener which will listen to
// various events happening during lifecycle of application
// Here this class listens to StartUp and ShutDown of the
// application.
// We make class implements ServletContextListener which has two
// methods contextInitialized() and contextDestroyed() , which
// are called by the container whenever a servlet context is
// started or shutdown
@WebListener
public class StartStopAppListener implements ServletContextListener {
public void contextInitialized(ServletContextEvent servletContextEvent) {
System.out.println("Servlet Context Initialized ... ");
}
public void contextDestroyed(ServletContextEvent servletContextEvent) {
System.out.println("Servlet Context Destroyed ... ");
}
}
package com.hubberspot.javaee.listener;
import javax.servlet.annotation.WebListener;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionAttributeListener;
import javax.servlet.http.HttpSessionBindingEvent;
// @WebListener annotation informs container that
// this class is a web listener which will listen to
// various events happening during lifecycle of application
// Here this class listens to changes made to HttpSession
// attributes.
// We make class implements HttpSessionAttributeListener
// which has three methods : attributeRemoved(), attributeAdded()
// and attributeReplaced() , which are called by the container
// whenever attributes are added, removed, or replaced
// within the HTTP session.
@WebListener
public class MySessionAttributeListener implements HttpSessionAttributeListener {
public void attributeRemoved(HttpSessionBindingEvent event) {
System.out.println("Method called when HttpSession attribute removed :");
HttpSession session = event.getSession();
System.out.println("Session ID : " + session.getId());
System.out.println("Session Name : " + event.getName());
System.out.println("Session Value : " + event.getValue());
}
public void attributeAdded(HttpSessionBindingEvent event) {
System.out.println("Method called when HttpSession attribute added :");
HttpSession session = event.getSession();
System.out.println("Session ID : " + session.getId());
System.out.println("Session Name : " + event.getName());
System.out.println("Session Value : " + event.getValue());
}
public void attributeReplaced(HttpSessionBindingEvent event) {
System.out.println("Method called when HttpSession attribute replaced :");
HttpSession session = event.getSession();
System.out.println("Session ID : " + session.getId());
System.out.println("Session Name : " + event.getName());
System.out.println("Session Value : " + event.getValue());
}
}
Run HelloWorldServlet.java and methods mentioned in above listener will be called by the container.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;
// @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();
HttpSession session = request.getSession();
// attributeAdded method gets executed
session.setAttribute("user", "Jonty");
// attributeReplaced method gets executed
session.setAttribute("user", "Dinesh");
// attributeRemoved method gets executed
session.removeAttribute("user");
}
}
Output of the program : package com.hubberspot.javaee;
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(name = "HelloWorldServlet" , urlPatterns = { "/HelloWorldServlet" })
public class HelloWorldServlet extends HttpServlet {
protected void doGet(
HttpServletRequest request,
HttpServletResponse response
) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
try {
out.println("<html>");
out.println("<body>");
out.println("<h2>Hello World !!!</h2>");
out.println("</body>");
out.println("</html>");
} finally {
out.close();
}
}
}
<servlet>
<servlet-name>HelloWorldServlet</servlet-name>
<servlet-class>com.hubberspot.javaee.HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloWorldServlet</servlet-name>
<url-pattern>/HelloWorldServlet</url-pattern>
</servlet-mapping>
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Index Page !!!</title>
</h:head>
<h:body>
<h:form>
<h1>The Welcome Index Form !!!.</h1>
<h:panelGrid columns="2" cellspacing="1" cellpadding="1">
<h:panelGroup>
<h:outputLabel for="firstName">
<h:outputText value="FirstName: " />
</h:outputLabel>
</h:panelGroup>
<h:panelGroup>
<h:inputText id="firstName" value="#{welcome.firstName}"/>
</h:panelGroup>
<h:panelGroup>
<h:outputLabel for="lastName">
<h:outputText value="LastName: " />
</h:outputLabel>
</h:panelGroup>
<h:panelGroup>
<h:inputText id="lastName" value="#{welcome.lastName}"/>
</h:panelGroup>
<h:panelGroup>
<h:commandButton id="submit" value="Submit"
action="#{welcome.welcomeUser}" />
</h:panelGroup>
</h:panelGrid>
</h:form>
</h:body>
</html>
<?xml version='1.0' encoding='UTF-8' ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:h="http://java.sun.com/jsf/html">
<h:head>
<title>Welcome !!!</title>
</h:head>
<h:body>
<h:form><h1>
<h:outputText id="welcomeUser"
value="Welcome #{welcome.firstName} #{welcome.lastName} to JSF !!!."/>
</h1></h:form>
</h:body>
</html>
package com.hubberspot.jsf;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.SessionScoped;
@ManagedBean
@SessionScoped
public class Welcome {
// firstName to store value entered in index.xhtml
private String firstName;
// lastName to store value entered in index.xhtml
private String lastName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getLastName() {
return lastName;
}
public void setLastName(String lastName) {
this.lastName = lastName;
}
// method called when user clicks submit button in index.xhtml
// It returns String as welcome. Based on this String flow gets
// forwarded to welcome.xhtml
public String welcomeUser() {
return "welcome";
}
}
Overview of Deployment Descriptor file named as web.xml<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" 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">
<context-param>
<param-name>javax.faces.PROJECT_STAGE</param-name>
<param-value>Development</param-value>
</context-param>
<servlet>
<servlet-name>Faces Servlet</servlet-name>
<servlet-class>javax.faces.webapp.FacesServlet</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Faces Servlet</servlet-name>
<url-pattern>/faces/*</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>faces/index.xhtml</welcome-file>
</welcome-file-list>
</web-app>
Final Package Structure for the web application