我很困惑。这是我的问题:
我在一个与Servlet连接的jsp文件中有一个jtable。到目前为止一切正常。在我的Servlet中,我需要通过EntityManager连接到数据库,但我不能使用它,因为它给了我NullPointerException。我有一个HomeController我在没有任何问题的情况下管理EntityManager,但我无法使用我的Servlet中的函数。这是我的源代码:
HomeController.java :
@Controller
public class HomeController {
private static final Logger logger = LoggerFactory
.getLogger(HomeController.class);
@PersistenceContext
private EntityManager entityManager;
(...)
/**
* Lists users by points in desc order
*
* @return list with users ordered by points
*/
public List<Usuario> listaUsuarios() {
return entityManager.createQuery(
"select u from Usuario u order by puntos desc").getResultList();
}
}
InvasionServlet.java :
@WebServlet("/InvasionServlet")
public class InvasionServlet extends HttpServlet {
private static final long serialVersionUID = -9049034342389418838L;
private static final Logger logger = LoggerFactory
.getLogger(InvasionServlet.class);
@PersistenceContext
private EntityManager entityManager;
/* Manejo de tablas */
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String action = request.getParameter("action");
if (action != null) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
response.setContentType("application/json");
if (action.equals("list")) {
logger.info("loading users list");
List<Usuario> usuariosOrdenados = entityManager.createQuery(
"select u from Usuario u order by puntos desc").getResultList();
JsonElement element = gson.toJsonTree(usuariosOrdenados,
new TypeToken<List<Usuario>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
String listData = jsonArray.toString();
// Return Json in the format required by jTable plugin
listData = "{\"Result\":\"OK\",\"Records\":" + listData + "}";
try {
response.getWriter().print(listData);
} catch (IOException e) {
String error = "{\"Result\":\"ERROR\",\"Message\":"
+ e.getStackTrace() + "}";
response.getWriter().print(error);
}
}
}
}
}
我无论如何都无法加载数据,有什么建议吗?我认为这是一个明显的问题,但我无法想象。
答案 0 :(得分:2)
问题在于(与HomeContoller不同)Servlet不是(并且永远不会是)Spring Managed Bean,因此永远不会注入EntityManager。
由于您似乎已经在使用Spring MVC,我建议使用Spring MVC控制器替换Servlet,它看起来如下所示。否则,您需要研究在Servlet中获取对Spring Managed Bean(EntityManager)的引用的策略。
@Controller
public class MyController(){
@PersistenceContext
private EntityManager entityManager;
@ResponseBody
@RequestMapping(path="pathToBeCalled")
public String loadData(@RequestParam("action") String action){
if (action != null) {
Gson gson = new GsonBuilder().setPrettyPrinting().create();
if (action.equals("list")) {
logger.info("loading users list");
List<Usuario> usuariosOrdenados = entityManager.createQuery(
"select u from Usuario u order by puntos desc").getResultList();
JsonElement element = gson.toJsonTree(usuariosOrdenados,
new TypeToken<List<Usuario>>() {
}.getType());
JsonArray jsonArray = element.getAsJsonArray();
String listData = jsonArray.toString();
listData = "{\"Result\":\"OK\",\"Records\":" + listData + "}";
return listData;
}
}
}
}