Error With ServletContextListener - java

I am studying servlets and I made one example from book but I got nullpointerexception.
Here are my classes:
package chala;
public class Dog {
private String breed;
public Dog(String breed) {
this.breed = breed;
}
public String getBreed() {
return breed;
}
public void setBreed(String breed) {
this.breed = breed;
}
}
Dog class is POJO class with simple functionality.
package chala;
import javax.servlet.ServletContext;
import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
public class CtxListener implements ServletContextListener {
#Override
public void contextDestroyed(ServletContextEvent event) {
ServletContext sc = event.getServletContext();
String breed = sc.getInitParameter("breed");
Dog d = new Dog(breed);
sc.setAttribute("dog", d);
}
#Override
public void contextInitialized(ServletContextEvent event) {
// TODO Auto-generated method stub
}
}
This is context listener class where I get servlet context object, get init parameter from it, and creating Dog object, then setting attribute of servlet context.
package chala;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
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 CtxListenerTester
*/
#WebServlet("/CtxListenerTester")
public class CtxListenerTester extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Servlet Context Listener Example");
out.print("<BR/>");
ServletContext sc = (ServletContext) getServletContext();
System.out.println(sc.getAttribute("dog"));
Dog dog = (Dog) getServletContext().getAttribute("dog");
out.print("Dogs breed is :" + dog.getBreed());
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
This is my servlet where I am getting servlet context attribute (DOG object) and calling Dogs getBreed() method. When I start and send GET request I am getting nullpointerexception.
Here 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"
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>ContextListenerDemo</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>
<context-param>
<param-name>breed</param-name>
<param-value>Labrador</param-value>
</context-param>
<listener>
<listener-class>chala.CtxListener</listener-class>
</listener>
</web-app>

you set the attribute in contextDestroyed() method that will invoked while context is being destroyed you need to set that attribute in contextInitialized()

Related

requestDispatcher.forward() returns blank webpage

Genuinely Stumped I'm new to Trying to Develop in java and I'm struggling with creating a user login page.
I want to check if the user has a session and has a key available that I've set at authentication if not I want them to be forwarded to the loginPage.jsp
The code that I've provided works when I don't use the following mapping for my servlet.
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/</url-pattern> -- This works by itself only works on paths not .jsp files
<url-pattern>*.jsp</url-pattern> -- if i include this i only get blank webpages
</servlet-mapping>
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_4_0.xsd" id="WebApp_ID" version="4.0">
<display-name>Project1</display-name>
<servlet>
<servlet-name>ControllerServlet</servlet-name>
<servlet-class>ControlServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ControllerServlet</servlet-name>
<url-pattern>/</url-pattern> //Works when by itself
<url-pattern>*.jsp</url-pattern> //breaks when i enabled this
</servlet-mapping>
<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>
Control Servlet.java
import java.io.IOException;
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;
import javax.servlet.http.HttpSession;
/**
* Servlet implementation class ControlServlet
*/
public class ControlServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public ControlServlet() {
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
HttpSession session = request.getSession(false);
if (session == null) {
// Not created yet. Now do so yourself.
session = request.getSession();
} else {
// Already created.
}
//Check if User is Logged in
String pathInfo = (request.getPathInfo() != null) ? request.getPathInfo() : request.getServletPath();
System.err.println("check1");
System.err.println(session.getAttribute("name") == null);
System.err.println("check2");
System.err.println(!"/loginPage.jsp".equals(pathInfo));
System.err.println(pathInfo);
if (session.getAttribute("name") == null && !"/loginPage.jsp".equals(pathInfo))
{
RequestDispatcher requestDispatcher = request.getRequestDispatcher("/loginPage.jsp");
requestDispatcher.forward(request, response);
//response.sendRedirect("loginPage.jsp");
System.err.println("did this ever happen?");
}else {
}
}
/**
* #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);
}
}

Http error 404 in servlet: No webpage was found for the web address

PrintNamesServlet.java:
This servlet prints the entered name of the user
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(name = "PrintNamesServlet")
public class PrintNamesServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("Ram Dhakal");
}
}
CounterServlet.java:
Counts the number of hits or visit in the page
import javax.servlet.ServletException; import
javax.servlet.annotation.WebServlet; import
javax.servlet.http.HttpServlet; import
javax.servlet.http.HttpServletRequest; import
javax.servlet.http.HttpServletResponse; import java.io.IOException;
import java.io.PrintWriter;
#WebServlet(name = "CounterServlet") public class CounterServlet
extends HttpServlet {
int totalHits;
public void init() throws ServletException{
totalHits = 0;
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.print("Total visit count: " + totalHits++);
} public void destroy(){
}
}
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1">
<servlet>
<servlet-name>PrintNamesServlet</servlet-name>
<servlet-class>PrintNamesServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>PrintNamesServlet</servlet-name>
<url-pattern>/PrintNamesServlet</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>CounterServlet</servlet-name>
<servlet-class>CounterServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>CounterServlet</servlet-name>
<url-pattern>/CounterServlet</url-pattern>
</servlet-mapping>
</web-app>
I am getting error:
No webpage was found for the web address: http://localhost:8080/
As, I am trying to run the servlet for the first time, I am not getting what is wrong with my code. I typed http://localhost:8080/PrintNamesServlet in the url.
You have used Servlet 3.0 specification
Lets takes look at it
In Servlet 3.0, servlet metadata can be specified using #WebServlet
#WebServlet(name="mytest",
urlPatterns={"/myurl"})
public class TestServlet extends javax.servlet.http.HttpServlet {
....
}
In this way the servlet is accessed by using the url pattern specified in the annotation.
##WebServlet(name="mytest",urlPatterns={"/myurl"})
according to that servlet is acceseed using
http://localhost:8080/myurl
In you case you have only specified name you have to specify urlPatterns also, so you can able to call you servlet properly.
#WebServlet(name = "CounterServlet",urlPatterns={"/CounterServlet"}) public class CounterServlet extends HttpServlet {}
And you do not need to use web.xml file.
When you use annotations like this #WebServlet(name = "PrintNamesServlet") the web.xml mapping is not used.
You have to either remove these annotations or add urlMapping attribute to them.

HTTP Status 404-The requested resource is not available

few months ago i've worked on this project for my university (a quiz game) and all was fine! Now i've re-opened the eclipse project but i don't know why, it doesn't work! I've already searched in the old topic, because i know this is a recurrent problem, but i don't know how to solve it! I think is just a configuration problem because i've wrote the entire project on another workstation and there all was fine. Now i'm trying to run the servlet on my Mac with Eclipse Mars and tomcat 8.0.
Here i report the code of one of my servlet and the xml file.
package servlet;
import java.io.IOException;
import java.sql.SQLException;
import javax.servlet.ServletConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
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 database.DbHelper;
/**
* Servlet implementation class Login
*/
#WebServlet("/Login")
public class Login extends HttpServlet {
private static final long serialVersionUID = 1L;
private DbHelper dbHelper = null;
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
ServletContext context = config.getServletContext();
String driver = context.getInitParameter("dbDriver");
String path = context.getInitParameter("dbUrl");
String user = context.getInitParameter("dbUser");
String pass = context.getInitParameter("dbPassword");
try {
dbHelper = new DbHelper(driver, path, user, pass);
} catch (ClassNotFoundException | SQLException e) {
e.printStackTrace();
}
}
#Override
public void destroy() {
super.destroy();
if(dbHelper!=null){
try {
dbHelper.destroy();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
HttpSession session=request.getSession();
String username=request.getParameter("username");
String password=request.getParameter("password");
try {if (dbHelper.isPlayer(username, password)){
session.setAttribute("username",username);
response.sendRedirect("Player");
} else
if (dbHelper.isAuthor(username, password)){
session.setAttribute("username",username);
response.sendRedirect("Author");
}else{
request.setAttribute("error", 1);
request.getRequestDispatcher("jsp/login.jsp").forward(request, response);
}
} catch (SQLException e) {
e.printStackTrace();
response.sendRedirect("html/error.html");
}
}
#Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}
The XML file :
<?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_3_0.xsd"
version="3.0"
metadata-complete="true">
<display-name>CheckMyBrain</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>
<context-param>
<description>Database URL</description>
<param-name>dbUrl</param-name>
<param-value>jdbc:mysql://localhost:3306/Quiz</param-value>
</context-param>
<context-param>
<description>Database user</description>
<param-name>dbUser</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<description>Database password</description>
<param-name>dbPassword</param-name>
<param-value>root</param-value>
</context-param>
<context-param>
<description>Database driver</description>
<param-name>dbDriver</param-name>
<param-value>com.mysql.jdbc.Driver</param-value>
</context-param>
<context-param>
<param-name>smtpHost</param-name>
<param-value>smtp.gmail.com</param-value>
</context-param>
<context-param>
<param-name>smtpPort</param-name>
<param-value>587</param-value>
</context-param>
<context-param>
<param-name>smtpUser</param-name>
<param-value>checkmybrain37#gmail.com</param-value>
</context-param>
<context-param>
<param-name>smtpPass</param-name>
<param-value>stosultomcat</param-value>
</context-param>
</web-app>
folders here
Tomcat location is not on workspace metadata.
When i run the Servlet

Servlet's service and init method are being called, but not doGet

I have a simple Servlet that looks like this:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class Bla extends HttpServlet {
private static final long serialVersionUID = 16252534;
#Override
public void init() throws ServletException {
System.out.println("init");
}
#Override
public void doGet(HttpServletRequest req, HttpServletResponse resp)
throws ServletException, IOException {
System.out.println("doGet");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
out.println("<html><h1>It works!!</h1></html>");
}
#Override
public void service(ServletRequest req, ServletResponse resp) throws ServletException, IOException {
System.out.println("service");
}
#Override
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doPost");
}
#Override
public void destroy() {
System.out.println("Destroy servlet");
}
}
and a web.xml that looks like this:
<?xml version="1.0" encoding="UTF-8" ?>
<web-app>
<display-name>Archetype Created Web Application</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>Bla</servlet-name>
<servlet-class>instrurental_proj.servlets.Bla</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Bla</servlet-name>
<url-pattern>/bla</url-pattern>
</servlet-mapping>
</web-app>
When I visit the url http://localhost:8080/instrurental/bla, the following is printed out in the console:
init
service
but not doGet as I expect. Also, nothing is printed out in the browser! (I'm expecting it to say "It Works").
I've been struggling with this issue since yesterday. Does anyone have any suggestions, what could the problem be?
Why are u overriding the service method. There is no need of that. Remove it or else call
super.service(request,response);
REASON
Try to see the source of HttpServlet class. There you will see that depending on the method that is used to called the servlet i.e. GET/POST the necessary method doGet() or doPost() is called. And when the container actually receives a request it starts a new thread and and serves the client by calling service() method. So if you override it and don't call the super class' service method or define your own strategyhow GET will be called, doGet() method will never be called. Your request never calls doGet() method, its the service() method which calls it.

Getting error while servlet program HTTP Status 404 - /HelloWorldServlet/

My Servlets program
package com.srccodes.example;
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;
/**
* Servlet implementation class Helloworld
*/
#WebServlet("/Helloworld")
public class Helloworld extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Helloworld() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter printWriter = response.getWriter();
printWriter.println("<h1>Hello World!</h1>");
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
}
}
update :
wec.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" id="WebApp_ID" version="3.0">
<display-name>HelloWorldServlet</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>
while running above program on tomcat server am getting error
error --> http://i.stack.imgur.com/655Ew.png.
how to resolve this problem,please try to suggest me,good answers will appriciate
Their is nothing wrong in code you provided above.
your servlet name is 'Helloworld' and URL you are tryng is
http://localhost:8080/HelloworldServlet
if you want to run same servlet try
http://localhost:8080/HelloworldServlet/Helloworld
also Restart your server and check for URL.
Remove "Servlet" from the url, something like http://localhost:8080/Helloworld
Is this class part of a WAR application? Try putting the WAR name between the port and HelloWorld.

Categories