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.
Related
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");
}
}
Currently, i have function, which is to convert the data from MYSQL to CSV. The CSV function contain the webconfig where use the viewResolver. The problem is, when i used below function, the page cannot view but the CSV file can be download and vice versa. Is there anything that i need to configure ?
-Configure ContentNegotiatingViewResolver
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
WebConfig- full code
package com.portal.dmtt.csvDownload.config;
import com.portal.dmtt.csvDownload.viewResolver.CsvViewResolver;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.accept.ContentNegotiationManager;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.ContentNegotiationConfigurer;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.ContentNegotiatingViewResolver;
import java.util.ArrayList;
import java.util.List;
#Configuration
public class WebConfig extends WebMvcConfigurerAdapter {
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true);
}
/*
* Configure ContentNegotiatingViewResolver
*/
#Bean
public ViewResolver contentNegotiatingViewResolver(ContentNegotiationManager manager) {
ContentNegotiatingViewResolver resolver = new ContentNegotiatingViewResolver();
resolver.setContentNegotiationManager(manager);
// Define all possible view resolvers
List<ViewResolver> resolvers = new ArrayList<>();
resolvers.add(csvViewResolver());
resolver.setViewResolvers(resolvers);
return resolver;
}
/*
* Configure View resolver to provide Csv output using Super Csv library to
* generate Csv output for an object content
*/
#Bean
public ViewResolver csvViewResolver() {
return new CsvViewResolver();
}
}
Export Controller
package com.portal.dmtt.csvDownload.controller;
import com.portal.dmtt.repo.dmttDAO;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
#Controller
public class ExportController {
#Autowired
private dmttDAO dmttDAO;
/**
* Handle request to download an Excel document
*/
#GetMapping("/dl")
public String download(Model model) {
model.addAttribute("results", dmttDAO.getAllResultSet());
return "";
}
}
Abstract View
package com.portal.dmtt.csvDownload.view;
import org.springframework.web.servlet.view.AbstractView;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
public abstract class AbstractCsvView extends AbstractView {
private static final String CONTENT_TYPE = "text/csv";
public AbstractCsvView() {
setContentType(CONTENT_TYPE);
}
#Override
protected boolean generatesDownloadContent() {
return true;
}
#Override
protected final void renderMergedOutputModel(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response) throws Exception {
response.setContentType(getContentType());
buildCsvDocument(model, request, response);
}
protected abstract void buildCsvDocument(
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)
throws Exception;
}
CSV View
package com.portal.dmtt.csvDownload.view;
import com.portal.dmtt.model.exceptionMonitoring.FN_Result_Set;
import org.supercsv.io.CsvBeanWriter;
import org.supercsv.io.ICsvBeanWriter;
import org.supercsv.prefs.CsvPreference;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;
import java.util.Map;
public class CsvView extends AbstractCsvView {
#Override
protected void buildCsvDocument(Map<String, Object> model, HttpServletRequest request, HttpServletResponse
response) throws Exception {
response.setHeader("Content-Disposition", "attachment; filename=\"my-csv-file.csv\"");
List<FN_Result_Set> fnResultSetList = (List<FN_Result_Set>) model.get("results");
String[] header = {"SP_ID", "SP_ID", "XFER_XMIT_STATUS", "XFER_FILE_NAME", "UPDATE_TS", "YYMM", "REMARKS"};
try {
ICsvBeanWriter csvWriter = new CsvBeanWriter(response.getWriter(),
CsvPreference.STANDARD_PREFERENCE);
csvWriter.writeHeader(header);
for (FN_Result_Set user : fnResultSetList) {
csvWriter.write(user, header);
}
csvWriter.close();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
View Resolver
package com.portal.dmtt.csvDownload.viewResolver;
import com.portal.dmtt.csvDownload.view.CsvView;
import org.springframework.web.servlet.View;
import org.springframework.web.servlet.ViewResolver;
import java.util.Locale;
public class CsvViewResolver implements ViewResolver {
#Override
public View resolveViewName(String s, Locale locale) throws Exception {
return new CsvView();
}
}
One of the problems is that your CSVViewResolver is resolving a view for any view name. You may want to return null from CSVViewResolver.resolveViewName() if s, the view name, is not empty .
Another issue is that the browser (at least my Chrome) doesn't send text/csv as Accept header, but text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8
Set the media type explicitly in configureContentNegotiation for CSV:
#Override
public void configureContentNegotiation(ContentNegotiationConfigurer configurer) {
configurer
.defaultContentType(MediaType.APPLICATION_JSON)
.favorPathExtension(true)
.mediaType("csv", MediaType.parseMediaType("text/csv"));
}
Remove the Bean contentNegotiatingViewResolver
You shouldn't create a contentNegotiatingViewResolver as one is provided by Spring Boot. If you provide one, you will have two of this type, and yours will not have the Thymeleaf ViewResolver. As your CSVViewResolver will return a view for any view name, the view will be resolved in the ContentNegotiatingViewResolver provided by you, not in the one provided by Spring.
Details:
The csvViewResolver bean will be picked up by the Spring Boot's ContentNegotiatingViewResolver along others like BeanNameViewResolver, ThymeleafViewResolver, ViewResolverComposite, InternalResourceViewResolver.
To debug this set a breakpoint on DispatcherServlet.resolveViewName:
protected View resolveViewName(String viewName, Map<String, Object> model, Locale locale,
HttpServletRequest request) throws Exception {
for (ViewResolver viewResolver : this.viewResolvers) {
View view = viewResolver.resolveViewName(viewName, locale);
if (view != null) {
return view;
}
}
return null;
}
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 have an issue on instantiating servlet class wtih simple test application inserting records in DB using j7ee ejb 3.1 and jpa 2.1. I'm a newby to ejb and jpa and I'm trying to test a solution.
I'm using NetBeans 8.0.
I have separated layers for entity classes and for ejb.
I have entity class Doctor.java located in com.tsc.deo.entities (DEO is the name of application):
package com.tsc.deo.entities;
import java.io.Serializable;
import javax.persistence.Basic;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.NamedQueries;
import javax.persistence.NamedQuery;
import javax.persistence.Table;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import javax.xml.bind.annotation.XmlRootElement;
/**
*
* #author IK
*/
#Entity
#Table(name = "doctor")
#XmlRootElement
#NamedQueries({
#NamedQuery(name = "Doctor.findAll", query = "SELECT d FROM Doctor d"),
#NamedQuery(name = "Doctor.findByIDDoctor", query = "SELECT d FROM Doctor d WHERE d.iDDoctor = :iDDoctor"),
#NamedQuery(name = "Doctor.findBySirname", query = "SELECT d FROM Doctor d WHERE d.sirname = :sirname"),
#NamedQuery(name = "Doctor.findByName", query = "SELECT d FROM Doctor d WHERE d.name = :name"),
#NamedQuery(name = "Doctor.findByPatientIDPatient", query = "SELECT d FROM Doctor d WHERE d.patientIDPatient = :patientIDPatient")})
public class Doctor implements Serializable {
private static final long serialVersionUID = 1L;
#Id
#GeneratedValue(strategy = GenerationType.IDENTITY)
#Basic(optional = false)
#Column(name = "IDDoctor")
private Integer iDDoctor;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "Sirname")
private String sirname;
#Basic(optional = false)
#NotNull
#Size(min = 1, max = 45)
#Column(name = "Name")
private String name;
#Basic(optional = false)
#NotNull
#Column(name = "Patient_IDPatient")
private int patientIDPatient;
public Doctor() {
}
public Doctor(Integer iDDoctor) {
this.iDDoctor = iDDoctor;
}
public Doctor(Integer iDDoctor, String sirname, String name, int patientIDPatient) {
this.iDDoctor = iDDoctor;
this.sirname = sirname;
this.name = name;
this.patientIDPatient = patientIDPatient;
}
public Integer getIDDoctor() {
return iDDoctor;
}
public void setIDDoctor(Integer iDDoctor) {
this.iDDoctor = iDDoctor;
}
public String getSirname() {
return sirname;
}
public void setSirname(String sirname) {
this.sirname = sirname;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getPatientIDPatient() {
return patientIDPatient;
}
public void setPatientIDPatient(int patientIDPatient) {
this.patientIDPatient = patientIDPatient;
}
#Override
public int hashCode() {
int hash = 0;
hash += (iDDoctor != null ? iDDoctor.hashCode() : 0);
return hash;
}
#Override
public boolean equals(Object object) {
// TODO: Warning - this method won't work in the case the id fields are not set
if (!(object instanceof Doctor)) {
return false;
}
Doctor other = (Doctor) object;
if ((this.iDDoctor == null && other.iDDoctor != null) || (this.iDDoctor != null && !this.iDDoctor.equals(other.iDDoctor))) {
return false;
}
return true;
}
#Override
public String toString() {
return iDDoctor + sirname + name + " | ";
}
}
I have the bean class:
package com.tsc.deo.beans;
import com.tsc.deo.entities.Doctor;
import java.io.Serializable;
import java.util.List;
import javax.ejb.Stateless;
import javax.inject.Named;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
/**
*
* #author IK
*/
#Stateless
#Named
public class DoctorSessionBean implements Serializable, DoctorSession, DoctorSessionLocal {
public DoctorSessionBean () {}
// Add business logic below. (Right-click in editor and choose
// "Insert Code > Add Business Method")
#PersistenceContext
private EntityManager em;
// private Logger log = null;
public EntityManager getEntityManager() {
try {
// Context ctx = (Context) new InitialContext().lookup("java:comp/env");
// return (EntityManager) ctx.lookup("persistence/LogicalName");
return em;
} catch (Exception e) {
// Logger.getLogger(getClass().getName()).log(Level.SEVERE, "exception caught", e);
// throw new RuntimeException(e);
e.printStackTrace(System.out);
throw new RuntimeException(e);
}
}
public List<Doctor> getDoctors() {
return getEntityManager().createNamedQuery("Doctor.findAll").getResultList();
}
public void insertDBDoctor(Doctor doc) {
EntityManager em = getEntityManager();
em.getTransaction().begin();
em.persist(doc);
em.getTransaction().commit();
em.close();
}
}
With Remote and Local interfaces:
package com.tsc.deo.beans;
import com.tsc.deo.entities.Doctor;
import java.util.List;
import javax.ejb.Remote;
import javax.persistence.EntityManager;
/**
*
* #author IK
*/
#Remote
public interface DoctorSession {
public EntityManager getEntityManager();
public List<Doctor> getDoctors();
}
package com.tsc.deo.beans;
import com.tsc.deo.entities.Doctor;
import java.util.List;
import javax.ejb.Local;
import javax.persistence.EntityManager;
/**
*
* #author IK
*/
#Local
public interface DoctorSessionLocal {
public EntityManager getEntityManager();
public List<Doctor> getDoctors();
}
And I have a servlet which is trying to store new entity in DB (connect to DB works ok):
package com.tsc.deo.servlets;
import com.tsc.deo.beans.DoctorSessionBean;
import com.tsc.deo.entities.Doctor;
import java.io.IOException;
import java.io.PrintWriter;
import javax.ejb.EJB;
import javax.persistence.EntityManager;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
*
* #author IK
*/
#WebServlet(name = "TestUpdateDBServlet", urlPatterns = {"/TestUpdateDBServlet"})
public class TestUpdateDBServlet extends HttpServlet {
#EJB
private DoctorSessionBean doctorSessionBean;
/**
* Processes requests for both HTTP <code>GET</code> and <code>POST</code>
* methods.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
protected void processRequest(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
Doctor doc = new Doctor();
doc.setIDDoctor(8);
doc.setSirname("Материнка");
doc.setName("Оля");
doc.setPatientIDPatient(81);
doctorSessionBean.insertDBDoctor(doc);
response.setContentType("text/html;charset=UTF-8");
try (PrintWriter out = response.getWriter()) {
/* TODO output your page here. You may use following sample code. */
out.println("<!DOCTYPE html>");
out.println("<html>");
out.println("<head>");
out.println("<title>Servlet TestUpdateDBServlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h1>Servlet TestUpdateDBServlet at " + request.getContextPath() + "</h1>");
out.println(doctorSessionBean.getDoctors());
out.println("</body>");
out.println("</html>");
}
}
// <editor-fold defaultstate="collapsed" desc="HttpServlet methods. Click on the + sign on the left to edit the code.">
/**
* Handles the HTTP <code>GET</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Handles the HTTP <code>POST</code> method.
*
* #param request servlet request
* #param response servlet response
* #throws ServletException if a servlet-specific error occurs
* #throws IOException if an I/O error occurs
*/
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
}
/**
* Returns a short description of the servlet.
*
* #return a String containing servlet description
*/
#Override
public String getServletInfo() {
return "Short description";
}// </editor-fold>
}
After running the application the error message poped up in my browser:
"javax.servlet.ServletException: Error instantiating servlet class com.tsc.deo.servlets.TestUpdateDBServlet
In the root of cause it's said that it couldn't find DoctorSessionBean:
"javax.naming.NameNotFoundException: com.tsc.deo.beans.DoctorSessionBean#com.tsc.deo.beans.DoctorSessionBean not found"
What it the reason of this issue and how can I correct it?
Now GlassFish 4.0 in NetBeans is popping up the error message:
"SEVERE: The web application [/DEO] created a ThreadLocal with key of type [org.glassfish.pfl.dynamic.codegen.impl.CurrentClassLoader$1] (value [org.glassfish.pfl.dynamic.codegen.impl.CurrentClassLoader$1#2380e2]) and a value of type [org.glassfish.web.loader.WebappClassLoader] (value [WebappClassLoader (delegate=true; repositories=WEB-INF/classes/)]) but failed to remove it when the web application was stopped. Threads are going to be renewed over time to try and avoid a probable memory leak."
In your code you have
#Named
public class DoctorSessionBean implements
This means that the bean will be name doctorSessionBean. If you don't specify a name it will use the bean name in lower case.
look here for http://docs.oracle.com/javaee/6/tutorial/doc/gjbak.html information.
Giving Beans EL Names
To make a bean accessible through the EL, use the #Named built-in qualifier:
import javax.inject.Inject;
import javax.enterprise.context.RequestScoped;
import javax.inject.Named;
#Named
#RequestScoped
public class Printer {
#Inject #Informal Greeting greeting;
...
The #Named qualifier allows you to access the bean by using the bean name,
with the first
letter in lowercase. For example, a Facelets page would refer to the bean as printer.
You can specify an argument to the #Named qualifier to use a nondefault name:
#Named("MyPrinter")
With this annotation, the Facelets page would refer to the bean as MyPrinter.
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.