This question already has answers here:
Should I override service() or doPost()?
(5 answers)
Overriding HttpServlet service method
(2 answers)
Closed 12 months ago.
I am fresher in java web application development .
I tried just running the servlet file(not even through html file just servlet file) .
Service method is executing and displaying the statement (I commented in order to execute the get method print statement)
but doGet and doPost is not been called.
Will anyone can help me
import java.io.IOException;
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 Myservlet
*/
#WebServlet("/Myservlet")
public class Myservlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public Myservlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#service(HttpServletRequest request, HttpServletResponse response)
*/
protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
/*PrintWriter out = response.getWriter();
out.print("In service method");*/
//response.getWriter().println("Hello Server service method");
}
/**
* #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());
response.getWriter().println("Hello Server, Get method");
}
/**
* #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);
response.getWriter().println("Hello Server, Post method");
}
}
Related
Could anyone please help me?
Locally, on my mahcine I am running Tomcat 8.
I have used Eclipse to create a very very very simple Java Servlet by reading some online tutorials, Here's the code:
package com.theopentutorials.servlets;
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 HelloWorldServlet
*/
#WebServlet("/HelloWorldServlet")
public class HelloWorldServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public HelloWorldServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* #see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
PrintWriter out = response.getWriter();
out.println("Hello World");
}
/**
* #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);
}
}
I am successfully running this servlet on my machine and can access it fine from other machines in the same domain.
My web browser simply displays the string "Hello World" as expected.
So, now I'd like to push it to CloudFoundry.
So I use eclipse to export as a WAR file. Fine.
Next to CloudFoundry and I execute the following:
cf push Karry -p FirstServlet.war
All works fine. I see CloudFoundry installing java buildpacks etc. Finally it says App Started OK.
So now I browse to the url provided and I get:
What have I done wrong?
Thanks,
Mitch.
Did you try the /HelloWorldServlet endpoint? This is where I would look for this servlet, as defined in the code in
#WebServlet("/HelloWorldServlet")
i trying to open a pdf right after i created.
I want to see the result in my browser, but i dosen't.
By the way, the programm runs on a server.
If i try to open the pdf there, no problem - all works fine.
Just the client can't see the pdf if he clicks, for example, on a button.
Here's my code:
#WebServlet("/GeneratePdfCustomer")
public class GeneratePdfCustomer extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
final int id = Integer.parseInt(request.getParameter("id"));
makePdf(request, response, "POST",id);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
public void makePdf(HttpServletRequest request,
HttpServletResponse response, String methodGetPost, int id)
throws ServletException, IOException {
response.setContentType("application/pdf");
try {
Document document = new Document();
PdfWriter.getInstance(document, response.getOutputStream());
document.open();
document.add(new Paragraph("Test"));
document.close();
} catch (Exception e) {
System.out.println("Error" + e);
}
}
}
I using the iText library.
EDIT:
Now i have change my servlet code, but still not working for me.
I can't see the pdf in my browser. Firefox and IE both are show nothing.
package de.WorldCheckCustomer.model;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Date;
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 com.itextpdf.text.Document;
import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Paragraph;
import com.itextpdf.text.pdf.PdfWriter;
#WebServlet("/GeneratePdfCustomer")
public class GeneratePdfCustomer extends HttpServlet {
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
makePdf(request, response);
}
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
makePdf(request, response);
}
public void makePdf(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
// Set content type to application / pdf
// browser will open the document only if this is set
response.setContentType("application/pdf");
// Get the output stream for writing PDF object
OutputStream out = response.getOutputStream();
try {
Document document = new Document();
/* Basic PDF Creation inside servlet */
PdfWriter.getInstance(document, out);
document.open();
document.add(new Paragraph("Tutorial to Generate PDF using Servlet"));
document.add(new Paragraph(
"PDF Created Using Servlet, iText Example Works"));
document.close();
} catch (DocumentException exc) {
throw new IOException(exc.getMessage());
} finally {
out.close();
}
}
private static final long serialVersionUID = 6067021675155015602L;
}
I have springmvc and angularjs app up and running.
In Springmvc i have a bean named userSessionBean.
Now i am adding an interceptor to spring mvc and in its pre handel method i am trying to access userSessionBean.
My question is "Can i inject userSessionBean inside interceptor "
/**
*
*/
package com.loginLite.remote.authentication.interceptors;
import java.util.Random;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
import com.remote.authentication.model.UserSessionBean;
/**
* #author jamju02
*
*/
public class AuthenticationInteceptor implements HandlerInterceptor {
#Autowired
private UserSessionBean userSessionBean = null;
/**
* #return the userSessionBean
*/
public UserSessionBean getUserSessionBean() {
return userSessionBean;
}
/**
* #param userSessionBean the userSessionBean to set
*/
public void setUserSessionBean(UserSessionBean userSessionBean) {
userSessionBean = userSessionBean;
}
#Override
public boolean preHandle(HttpServletRequest request,
HttpServletResponse response, Object handler) throws Exception {
System.out.println("Pre-handle");
return true;
}
#Override
public void postHandle(HttpServletRequest request,
HttpServletResponse response, Object handler,
ModelAndView modelAndView) throws Exception {
Random rnd = new Random();
int tokenNumber = 100000 + rnd.nextInt(900000);
userSessionBean.setAuthTokenNumber(String.valueOf(tokenNumber));
response.addHeader("AUTH_TOKEN",userSessionBean.getAuthTokenNumber());
System.out.println("Post-handle");
}
#Override
public void afterCompletion(HttpServletRequest request,
HttpServletResponse response, Object handler, Exception ex)
throws Exception {
System.out.println("After completion handle");
}
}
My dispatcher servlet
<mvc:interceptors>
<bean class="com.paychex.loginLite.remote.authentication.interceptors.AuthenticationInteceptor">
<property name="userSessionBean" ref="userSessionBean"></property>
</bean>
</mvc:interceptors>
<bean id="userSessionBean"
class="com.paychex.loginLite.remote.authentication.model.UserSessionBean"
scope="session">
<aop:scoped-proxy />
</bean>
I was finally able to solve the issue which i was troubling me.
The mistake was, i was implementing the interface "HandlerInterceptor" for my interceptor class, as soon as i removed the interface and extended class "HandlerInterceptorAdapter" dependency injection started working fine.
This is the servlet code where I get the Nullpointer exxception.There are no objects that I need to get Initialized. What would be the problem?
package sms.controller;
import sms.model.DbConnection;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.Date;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import net.sf.json.JSONArray;
import net.sf.json.JSONObject;
public class StaffManagementServlet extends HttpServlet {
Connection con = null;
Statement st = null;
ResultSet rs = null;
PrintWriter out;
JSONArray jsonArray;
JSONObject jsonObject;
private static final long serialVersionUID = 1L;
/**
* #see HttpServlet#HttpServlet()
*/
public StaffManagementServlet() {
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
doPost(request, response); //line 50
}
/**
* #see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
* response)
*/
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
String action = request.getParameter("action");
System.out.println(action+"--------");
if (action.equalsIgnoreCase("registration")) { //line 63
userRegistration(request, response);
}
if (action.equalsIgnoreCase("login")) {
userLogin(request, response);
}
if (action.equalsIgnoreCase("section")) {
getSection(request, response);
}
if (action.equalsIgnoreCase("question")) {
getQuestion(request, response);
}
if (action.equalsIgnoreCase("semister")) {
getSemister(request, response);
}
if (action.equalsIgnoreCase("branch")) {
getBranch(request, response);
}
if (action.equalsIgnoreCase("forget")) {
forgetPassword(request, response);
}
if (action.equalsIgnoreCase("setPass")) {
setPassword(request, response);
}
}
This is the error I get when I run the sevlet on the server.
java.lang.NullPointerException
sms.controller.StaffManagementServlet.doPost(StaffManagementServlet.java:63)
sms.controller.StaffManagementServlet.doGet(StaffManagementServlet.java:50)
javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
Your action is NULL so when you call action.equalsIgnoreCase("registration"). It throws NullPointerException.
BEST practice for this case is using CONSTANT as first variable when compare.
if ("registration".equalsIgnoreCase(action)) {
// ....
} else if ("login".equalsIgnoreCase(action)) {
// ....
}
// ....
else {
throw new ServletException("Invalid action");
// OR process default action here if action missing
}
action is null. So calling a method on it throws a NullPointerException. You need to pass an action parameter to your request, or to deal with the possibility of action being null in the doPost() method.
In Myeclipse I created a web project called web1,and added a servlet called servlet1,the web.xml is as followed:
<?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">
<servlet>
<servlet-name>servlet1</servlet-name>
<servlet-class>servlet1</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>servlet1</servlet-name>
<url-pattern>/test</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
but when I typed the address:http://localhost:8080/web/test in the browser,it didn't work.I tried many times but have no answer.what's the problem?thanks a lot!
Here is the code:
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 servlet1 extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6214906967399177511L;
/**
* Constructor of the object.
*/
public servlet1() {
super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* #param request the request send by the client to the server
* #param response the response send by the server to the client
* #throws ServletException if an error occurred
* #throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the GET method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* #param request the request send by the client to the server
* #param response the response send by the server to the client
* #throws ServletException if an error occurred
* #throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01 Transitional//EN\">");
out.println("<HTML>");
out.println(" <HEAD><TITLE>A Servlet</TITLE></HEAD>");
out.println(" <BODY>");
out.print(" This is ");
out.print(this.getClass());
out.println(", using the POST method");
out.println(" </BODY>");
out.println("</HTML>");
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* #throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
Well as usual, you forgot to say super.init(config);
#Override
public void init(ServletConfig config) throws ServletException {
super.init(config);
}
You're servlet never got initialized, because you overrode method, and forgot to call parents' init.
That's why, if you do not know the internals, do NOT override anything, except if you're sure what are you doing.