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")
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");
}
}
![Eclipse Screen Shot the file structure and errors are lie in the image, if there is any improper file structure please let me know ][1]The Error shows like in the following image,Hello Everyone i am a servlet beginer , i have a problem with the following servlet code, could any one help to fix it.it shows javax.servlet.http cannot be resolved how to fix this issues?
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.second.po.User;
import com.second.serivce.UserService;
public class regServlet extends HttpServlet {
//UserDao userDao=new UserDao();//模式一直接通过UserDao访问数据库
private UserService userService=new UserService();//通过类之间的组合关系将其组合
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uname =request.getParameter("uname").trim();
String pwd =request.getParameter("pwd").trim();
String email =request.getParameter("email").trim();
String phone =request.getParameter("phone").trim();
String address =request.getParameter("address").trim();
int age =Integer.parseInt(request.getParameter("age"));
int gender =Integer.parseInt(request.getParameter("gender"));
int degree =Integer.parseInt(request.getParameter("degree"));
java.sql.Date joinTime=new java.sql.Date(new java.util.Date().getTime());
User user=new User("老高","1234","1808029435#qq.com",18,"13378052446","北京",0,1,joinTime);
userService.register(user);
request.getRequestDispatcher("reg_ok.jsp").forward(request,response);
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request,response);
}
}
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.
I am working on sample application called bookstore where I have used Dependency Injection. Very simple application. I am using JavaEE 6, GlassFish 3.1.2, Static data in a class (no db), Eclipse Juno.
I can provide more info if needed.
Error I get:
WARNING: StandardWrapperValve[com.bookstore.web.BookListServlet]: PWC1406: Servlet.service() for servlet com.bookstore.web.BookListServlet threw exception
java.lang.NullPointerException
at com.bookstore.web.BookListServlet.doGet(BookListServlet.java:29)
at javax.servlet.http.HttpServlet.service(HttpServlet.java:668)
This I know is Dependency is not injected. Class instance is not created to use it. If I remove #Inject and created an instance of a class than the page is loading fine.
Servlet code generating error: See bold comments
package com.bookstore.web;
import java.io.IOException;
import javax.inject.Inject;
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.bookstore.BookRepositoryImp;
#WebServlet("/book/")
public class BookListServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
#Inject
private BookRepositoryImp bookRepo;
public BookListServlet() {
super();
}
protected void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
**//bookRepo = new BookRepositoryImp(); If uncommect this code and remove #Inject than page working fine**
req.setAttribute("books", bookRepo.listBooks());
String path = "/WEB-INF/pages/book-list.jsp";
getServletContext().getRequestDispatcher(path).forward(req, res);
}
protected void doPost(HttpServletRequest req, HttpServletResponse res) throws ServletException,
IOException {
}
}
Project structure:
Have you tried moving your beans.xml file into the WEB-INF folder where your web.xml lives, maybe for some reason your beans.xml file is not copied properly to the resulting war file.