我有一个带有单个控制器的Java MVC应用程序。数据库在servlet上下文侦听器类中初始化。我将数据库对象作为servlet上下文属性传递给控制器servlet和webservice类。在控制器servlet中,“db”属性工作正常但在Web服务类中我得到null和非法状态异常。
错误堆栈跟踪 -
CREATE TABLE ads (ID INTEGER,txt1 TEXT,txt2 INTEGER,int1 INTEGER)
webservice类
javax.servlet.ServletException: A MultiException has 2 exceptions. They
are:
1. java.lang.NullPointerException
2. java.lang.IllegalStateException: Unable to perform operation: create on
com.home.mystorywriter.UserWS
org.glassfish.jersey.servlet.WebComponent.serviceImpl(WebComponent.java:489)
org.glassfish.jersey.servlet.WebComponent.service(WebComponent.java:427)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java: 388)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java: 341)
org.glassfish.jersey.servlet.ServletContainer.service(ServletContainer.java: 228)
org.apache.tomcat.websocket.server.WsFilter.doFilter(WsFilter.java:52)
root cause
java.lang.NullPointerException
at com.home.mystorywriter.UserWS.<init>(UserWS.java:36)
at sun.reflect.NativeConstructorAccessorImpl.newInstance0(Native Method)
Web.xml
package com.home.mystorywriter;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletContext;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.Context;
import javax.ws.rs.core.MediaType;
import com.google.gson.Gson;
@Path("/users")
public class UserWS {
@Context
private HttpServletRequest req;
private HttpServletResponse res;
private ServletContext context ;
DAOdb db = (DAOdb)req.getServletContext().getAttribute("db");
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("allUsers")
public String getAllUsers() {
List<Profile> userlist = db.getProfileListOfAllUsers();
Gson gson = new Gson();
String jsonUsers = gson.toJson(userlist);
return jsonUsers;
}
}
答案 0 :(得分:0)
@Context注入发生在Web服务类或类方法中。下面的代码工作正常。
@Path("/users")
public class UserWS {
private ServletContext context ;
DAOdb db;
public UserWS() {
System.out.println("Inside Constructor " + context);
}
@Context
public void setServletContext(ServletContext context) {
System.out.println("servlet context set here");
this.context = context;
db = (DAOdb)context.getAttribute("db");
}
@GET
@Produces(MediaType.APPLICATION_JSON)
@Path("/allUsers")
public String getAllUsers() {
System.out.println("Inside get method:"+ context);
System.out.println("db value"+ db);
Profile userlist = db.getProfileWithoutPic();
Gson gson = new Gson();
String jsonUsers = gson.toJson(userlist);
return jsonUsers;
}
}