查询逻辑有问题

查询逻辑有问题

自己看的头晕,还是求助吧

问题描述:查询时输入不存在的数字还会查出来数据,SearchGoodsByIdServlet.java中的ifelse走不到else。条件有问题吗是。

还有jsp界面的textbox是不是要加check啊,或者这种练习意思到了就行,没必要加。

Goods.java

package com.imooc.goods;

public class Goods {
	private Integer goodsId;
	private String goodsName;
	private String goodsType;
	private Float price;
	private String description;

	public Goods() {

	}

	public Goods(Integer goodsId, String goodsName, String goodsType, Float price, String description) {
		super();
		this.goodsId = goodsId;
		this.goodsName = goodsName;
		this.goodsType = goodsType;
		this.price = price;
		this.description = description;
	}

	public Integer getgoodsId() {
		return goodsId;
	}

	public void setgoodsId(Integer goodsId) {
		this.goodsId = goodsId;
	}

	public String getGoodsName() {
		return goodsName;
	}

	public void setGoodsName(String goodsName) {
		this.goodsName = goodsName;
	}

	public String getGoodsType() {
		return goodsType;
	}

	public void setGoodsType(String goodsType) {
		this.goodsType = goodsType;
	}

	public Float getPrice() {
		return price;
	}

	public void setPrice(Float price) {
		this.price = price;
	}

	public String getDescription() {
		return description;
	}

	public void setDescription(String description) {
		this.description = description;
	}


}

GoodsAddServlet.java

package com.imooc.goods;

import java.io.IOException;
import java.util.List;

import javax.servlet.ServletContext;
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 CreateServlet
 */
@WebServlet("/create")
public class GoodsAddServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public GoodsAddServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		String goodsId = request.getParameter("goodsId");
		String goodsName = request.getParameter("goodsName");
		String goodsType = request.getParameter("goodsType");
		String price = request.getParameter("price");
		String description = request.getParameter("description");
		Goods good = new Goods(Integer.parseInt(goodsId),goodsName,goodsType,Float.parseFloat(price),description);

		ServletContext context = request.getServletContext();
		List<Goods> goods = (List)context.getAttribute("goods");
		goods.add(good);
		context.setAttribute("goods", goods);
		request.getRequestDispatcher("/goods.jsp").forward(request, response);	
	}

}

GoodsListServlet.java

package com.imooc.goods;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
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 ListServlet
 */
@WebServlet("/list")
public class GoodsListServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public GoodsListServlet() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		ServletContext context = request.getServletContext();
		if (context.getAttribute("goods") == null) {
			List<Goods> list = new ArrayList<Goods>();
			Goods goods = new Goods(1001, "IPhone", "手机", 5499f, "可以打电话");
			list.add(goods);
			list.add(new Goods(1002, "Samsung", "手机", 6499f, "可以玩游戏"));
			context.setAttribute("goods", list);

		}
		request.getRequestDispatcher("/goods.jsp").forward(request, response);
	}

}

SearchGoodsByIdServlet.java

package com.imooc.goods;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.ServletContext;
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 SearchServlet
 */
@WebServlet("/search")
public class SearchGoodsByIdServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public SearchGoodsByIdServlet() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		String searchId = request.getParameter("id");
		response.setContentType("text/html;charset=utf-8");
		ServletContext context = request.getServletContext();
		List<Goods> goods = (List)context.getAttribute("goods");
		for(Goods good : goods) {
			Integer goodsId = (Integer)good.getgoodsId();
			if(Integer.parseInt(searchId) == goodsId) {
				context.setAttribute("searchGoods", good);
			}else{
				response.getWriter().println("商品id不存在");
			}
		}
		request.getRequestDispatcher("/searchById.jsp").forward(request, response);
	}
}

goods.jsp

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>商品列表</title>
<link href="css/bootstrap.css" type="text/css" rel="stylesheet">
</link>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<style type="text/css">
.pagination {
	margin: 0px
}

.pagination>li>a, .pagination>li>span {
	margin: 0 5px;
	border: 1px solid #dddddd;
}

.glyphicon {
	margin-right: 3px;
}

.form-control[readonly] {
	cursor: pointer;
	background-color: white;
}

#dlgPhoto .modal-body {
	text-align: center;
}

.preview {
	max-width: 500px;
}
</style>
<script>
	$(function() {

		$("#btnAdd").click(function() {
			$('#dlgForm').modal()
		});
	})
</script>
</head>

<body>
	<div class="container">
		<div class="row">
			<h1 style="text-align: center">IMOOC商品信息表</h1>
			<div class="panel panel-default">
				<div class="clearfix panel-heading ">
					<div>
						<label class="form-inline">
							<div class="form-group" style="width: 850px;">
								<button class="btn btn-primary" id="btnAdd">新增</button>
							</div>
							<div class="form-group pull-right">
								<form action="/goods/search" method="post">
									<input type="text" class="form-control" id="searchById"
										name="id" placeholder="根据商品id进行查询">
									<button type="submit" class="btn btn-primary">查询</button>
								</form>
							</div>
						</label>
					</div>
					<table class="table table-bordered table-hover">
						<thead>
							<tr>
								<th>序号</th>
								<th>商品编号</th>
								<th>商品名称</th>
								<th>商品类别</th>
								<th>价格</th>
								<th>备注</th>
								<th>&nbsp;</th>
							</tr>
						</thead>
						<tbody>
							<c:forEach items="${applicationScope.goods }" var="good"
								varStatus="idx">
								<tr>
									<td>${idx.index + 1 }</td>
									<td>${good.goodsId }</td>
									<td>${good.goodsName }</td>
									<td>${good.goodsType }</td>
									<td style="color: red; font-weight: bold">¥<fmt:formatNumber
											value="${good.price }" pattern="0,000.00"></fmt:formatNumber>
									</td>
									<td>${good.description }
								</tr>
							</c:forEach>
						</tbody>

					</table>
				</div>
			</div>
		</div>
		<!-- 表单 -->
		<div class="modal fade" tabindex="-1" role="dialog" id="dlgForm">
			<div class="modal-dialog" role="document">
				<div class="modal-content">
					<div class="modal-header">
						<button type="button" class="close" data-dismiss="modal"
							aria-label="Close">
							<span aria-hidden="true">&times;</span>
						</button>
						<h4 class="modal-title">新增商品</h4>
					</div>
					<div class="modal-body">
						<form action="/goods/create" method="post">
							<div class="form-group">
								<label>商品编号</label> <input type="text" name="goodsId"
									class="form-control" id="empno" placeholder="请输入商品编号">
							</div>
							<div class="form-group">
								<label>商品名称</label> <input type="text" name="goodsName"
									class="form-control" id="ename" placeholder="请输入商品名称">
							</div>
							<div class="form-group">
								<label>商品类别</label> <select id="gname" name="goodsType"
									class="form-control">
									<option value="服装">服装</option>
									<option value="家用">家用电器</option>
									<option value="生活">生活用品</option>
								</select>
							</div>
							<div class="form-group">
								<label>价格</label> <input type="text" name="price"
									class="form-control" id="sal" placeholder="请输入价格">
							</div>
							<div class="form-group">
								<label>备注</label> <input type="text" name="description"
									class="form-control" id="sal" placeholder="请输入备注">
							</div>
							<div class="form-group" style="text-align: center;">
								<button type="submit" class="btn btn-primary">保存</button>
							</div>
						</form>
					</div>
				</div>
				<!-- /.modal-content -->
			</div>
			<!-- /.modal-dialog -->
		</div>
		<!-- /.modal -->
</body>

</html>

searchById.jsp

<%@ page contentType="text/html; charset=utf-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt"%>
<!DOCTYPE html>
<html>

<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1">
<title>商品信息</title>
<link href="css/bootstrap.css" type="text/css" rel="stylesheet">
</link>
<script type="text/javascript" src="js/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="js/bootstrap.js"></script>
<style type="text/css">
.pagination {
	margin: 0px
}

.pagination>li>a, .pagination>li>span {
	margin: 0 5px;
	border: 1px solid #dddddd;
}

.glyphicon {
	margin-right: 3px;
}

.form-control[readonly] {
	cursor: pointer;
	background-color: white;
}

#dlgPhoto .modal-body {
	text-align: center;
}

.preview {
	max-width: 500px;
}
</style>
</head>

<body>
	<button class="btn btn-primary"
		style="margin-left: 30px; margin-top: 40px;"
		onclick="javascript:history.back(-1);">返回</button>
	<div class="container">
		<div class="row">
			<h1 style="text-align: center">IMOOC商品信息表</h1>
			<table class="table table-bordered table-hover">
				<thead>
					<tr>
						<th>商品编号</th>
						<th>商品名称</th>
						<th>商品类别</th>
						<th>价格</th>
						<th>备注</th>

					</tr>
				</thead>
				<tbody>

					<tr>
								<td>${applicationScope.searchGoods.goodsId }</td>
								<td>${applicationScope.searchGoods.goodsName }</td>
								<td>${applicationScope.searchGoods.goodsType }</td>
								<td style="color: red; font-weight: bold">¥<fmt:formatNumber
										value="${applicationScope.searchGoods.price }"
										pattern="0,000.00"></fmt:formatNumber>
								<td>${applicationScope.searchGoods.description }</td>
					</tr>

				</tbody>
			</table>
		</div>
	</div>
	</div>
</body>

</html>


正在回答

登陆购买课程后可参与讨论,去登陆

1回答

同学你好,建议同学在遍历之前定义商品变量,表示查询到的商品信息。在遍历完成后判断一下商品变量是否为null。

在jsp界面中判断一下作用域中商品信息是否为null,如果为null,表示没有查询到商品,如果不为null,则展示商品信息。

查看代码如下:

http://img1.sycdn.imooc.com//climg/5ff1633f0980cde907020437.jpg

http://img1.sycdn.imooc.com//climg/5ff162d4094ca1a805860439.jpg

祝学习愉快~

  • sx1011 提问者 #1

    jsp里是判断msg和searchGoods一样,还是只能判断msg。

    2021-01-03 21:44:40
  • 好帮手慕阿慧 回复 提问者 sx1011 #2

    同学你好,jsp里判断msg与searchGoods不一样。 同学将searchGoods对象放在了servletcontext中,将msg放在了request域中,所以在jsp里只能判断msg。

    祝学习愉快

    2021-01-04 09:47:11
  • sx1011 提问者 回复 好帮手慕阿慧 #3

    可以再详细一下吗?,这两个域为啥不能判断servletcontext,和为啥只能判断request

    2021-01-04 10:41:39
问题已解决,确定采纳
还有疑问,暂不采纳

恭喜解决一个难题,获得1积分~

来为老师/同学的回答评分吧

0 星
请稍等 ...
意见反馈 帮助中心 APP下载
官方微信

在线咨询

领取优惠

免费试听

领取大纲

扫描二维码,添加
你的专属老师