当我想要检索的值乘以时,我在检索servlet之间的数据(整数值)时遇到问题。我在我的第一个servlet中有这个函数,
private int totalNumberOf(Map<String,Integer> cart) {
int counter = 0;
for (String key : cart.keySet())
counter += cart.get(key);
return counter;
}
我也有它的属性(放在doGet()方法的末尾)...
req.setAttribute("quantity", new Integer(totalNumberOf(cart)));
,这个函数可以为我提供购物车中的产品总数,每当我向购物车添加商品时都会更新价值,所以当我完成购买时,我可以获得更新的产品数量值目前在购物车中。
现在出现了问题,当我尝试进行虚构结账时(因为我只对每种类型的产品都有通用价格)而且我必须将项目数乘以通用价格(这里&#39; NullPointer出现了。)
这是我的第二个servlet的代码,
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer quantity;
int toPay;
int genericValue = 20;
quantity = (Integer) req.getAttribute("quantity");
toPay = quantity.intValue() * genericValue; // NullPointer
}
我已经尝试过各种方式,但我无法摆脱丑陋的NullPointer。希望你能帮助我一点......
UPDATE Servlet1
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
String mensajeBienvenida = "";
Map<String,Integer> carrito = null;
String articuloElegido = req.getParameter("producto");
HttpSession session = req.getSession();
if (session.isNew()) {
session.invalidate();
RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/error.html");
dispatcher.forward(req, res);
}
else {
String nombreUsuario = ((Usuario)session.getAttribute("user")).getNombre();
if (session.getAttribute("carrito") == null) {
carrito = new HashMap<String,Integer>();
session.setAttribute("carrito",carrito);
mensajeBienvenida="Bienvenido a la tienda, " + nombreUsuario + "!";
}
else {
carrito = (Map<String,Integer>) session.getAttribute("carrito");
mensajeBienvenida = "Qué bien que sigas comprando, " + nombreUsuario + "!";
}
insertarEnCarrito(carrito, articuloElegido);
}
req.setAttribute("mensaje", mensajeBienvenida);
req.setAttribute("cesta", cestaDeLaCompraEnHTML(carrito));
req.setAttribute("cantidad", numeroTotalLibros(carrito));
RequestDispatcher dispatcher = getServletContext().getNamedDispatcher("VistaTienda");
dispatcher.forward(req, res);
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
private void insertarEnCarrito(Map<String,Integer> carrito, String articulo) {
if (carrito.get(articulo) == null){
carrito.put(articulo, new Integer(1));
}
else {
int numeroArticulos = (Integer)carrito.get(articulo).intValue();
carrito.put(articulo, new Integer(numeroArticulos+1));
}
}
private String cestaDeLaCompraEnHTML(Map<String,Integer> carrito) {
String cestaEnHTML = "";
for (String key : carrito.keySet())
cestaEnHTML += "<p>["+key+"], "+carrito.get(key)+" unidades</p>";
return cestaEnHTML;
}
private int numeroTotalLibros(Map<String,Integer> carrito) {
int counterLibro = 0;
for (String key : carrito.keySet())
counterLibro += carrito.get(key);
return counterLibro;
}
}
Servlet2
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
String mensajeBienvenida;
String cestaDeLaCompraEnHTML;
mensajeBienvenida = (String) req.getAttribute("mensaje");
cestaDeLaCompraEnHTML = (String) req.getAttribute("cesta");
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
out.println("<BODY>" + mensajeBienvenida + "<br>");
out.println(cestaDeLaCompraEnHTML + "<br>");
out.println("PRUEBA CANTIDAD LIBROS EN TOTAL - " + req.getAttribute("cantidad") + "<br>");
out.println("<a href=\"form.html\">Seguir comprando!</a></BODY></HTML>");
out.println("<a href=\"login.html\">Anular Compra</a></BODY></HTML>");
out.println("<a href=\"pagar\">Pagar Compra</a></BODY></HTML>");
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
Servlet3
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer cantidadLibro;
int pagar;
int valorLibro = 20;
Map<String,Integer> carrito = (Map<String,Integer>) session.getAttribute("carrito");
Usuario usuario = (Usuario) session.getAttribute("user");
cantidadLibro = (Integer) req.getAttribute("cantidad");
if (cantidadLibro == null){
cantidadLibro = 0;
} else {
cantidadLibro = (Integer) req.getAttribute("cantidad");
}
// pagar = cantidadLibro.intValue() * valorLibro;
res.setContentType("text/html");
PrintWriter out = res.getWriter();
out.println("<HTML>");
out.println("<HEAD><TITLE>Tienda con login!</TITLE></HEAD>");
out.println("<BODY><p><b>COMPRA REALIZADA!</b><br>");
out.println("<br><p>Total a pagar por su compra - " + "<br>");
out.println("<br><p>PRUEBA getAttribute - " + req.getAttribute("cantidad") + "<br>");
out.println("<br><p>Gracias por su compra " + usuario.getNombre() + " " + usuario.getApellidos() + "<br>");
out.println("<br><p>e-mail del usuario - " + usuario.getEmail() + "<br>");
out.println("<br><p>User ID - " + usuario.getId() + "<br>");
session.invalidate();
}
@Override
public void doPost(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
doGet( req,res );
}
答案 0 :(得分:0)
你听说过debugging
工具吗?
您的quantity
变量的值为null
,可能是因为请求中的abscense属性quantity
。这就是为什么你得到NPE
:null * (primitive numeric constant)
- &gt; NullPointerException
。
答案 1 :(得分:0)
您的getAttribute
函数可能返回null。记得在代码中进行空检查。在您致电if (quantity != null)
.intValue()
检查
另一种可能的解决方案是检查返回的是什么.getAttribute()而不是检查设置的数量。您还可以为数量指定默认值。
if (req.getAttribute("quantity") == null) {
quantity = 0;
} else {
quantity = (Integer) req.getAttribute("quantity");
}
答案 2 :(得分:0)
从你的代码看起来,“quantity.intValue()”会抛出你的空指针,因为数量为空。试试这个:
@Override
public void doGet(HttpServletRequest req, HttpServletResponse res ) throws IOException, ServletException {
HttpSession session = req.getSession();
Integer quantity = 0;
int toPay;
int genericValue = 20;
if (req.getAttribute("quantity") != null) {
quantity = (Integer) req.getAttribute("quantity");
}
toPay = quantity.intValue() * genericValue;
}
请注意,我不仅要使用值0初始化数量(因此它不为空)我还要对“req.getAttribute(”quantity“)”添加空检查,这样就不会将null赋给数量.getAttribute返回null的情况。
答案 3 :(得分:0)
除了您的代码可能需要的重构和优化之外,您要引用的问题是您正在设置属性&#34; cantidad&#34;到请求而不是会话。
在Servlet1中,替换此
req.setAttribute("cantidad", numeroTotalLibros(carrito));
用这个
session.setAttribute("cantidad", numeroTotalLibros(carrito));
在Servlet3中,替换此
cantidadLibro = (Integer) req.getAttribute("cantidad");
用这个
cantidadLibro = (Integer) session.getAttribute("cantidad");
原因是您将请求从Servlet1转发到Servlet2,因此在Servlet2中您可以访问&#34;转发&#34;请求及其所有属性,但Serlvet3在稍后阶段被独立调用。我想那就是当你按下&#34; Pagar&#34;在呈现的HTML页面中。因此,您无法再通过请求访问这些属性,因为它是一个不同的请求。如果您之前将它们存储在那里,您可以通过会话访问它们。
希望这有帮助。