正在回答
4回答
你判断下图中的mapList是否为null?是否获取到值?然后在看看有没有将map集合添加到List<Map<String,String>>中?如果mapList中没有值就会循环了,也不会执行System.out.println("map1");这行代码了。祝学习愉快~
慕虎8754231
2018-07-24 11:23:52
package com.java.servlet; import java.io.IOException; import java.util.HashMap; import java.util.List; import java.util.Map; 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.java.user.User; /** * 对图书分类进行信息保存的Servlet */ @WebServlet("/CatgoryServlet") public class CatgoryServlet extends HttpServlet { protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { //获取工程名 String path = request.getContextPath(); //获得context的信息 List<Map<String, String>> mapList=(List<Map<String, String>>)this.getServletContext().getAttribute("map"); //获得请求参数 String catgoryId=request.getParameter("id"); String catgoryName=request.getParameter("catgoryName"); String catgoryDec=request.getParameter("description"); System.out.println("map2"); Map<String, String> catgoryMap=new HashMap<String, String>(); System.out.println("map3"); for (Map<String, String> map1 : mapList) { System.out.println("map1"); //如果找到相同的id或名称,提示用户该图书分类已存在,请勿重复添加 if(map1.containsKey("catgoryId")) { response.sendRedirect(path+"/catgory.jsp?message=0"); System.out.println("图书分类id或名称重复,已返回到界面"); return; }else { catgoryMap.put("catgoryId", catgoryId); catgoryMap.put("catgoryName", catgoryName); catgoryMap.put("catgoryDec", catgoryDec); mapList.add(catgoryMap); this.getServletContext().setAttribute("map",catgoryMap); System.out.println("添加成功!"); } } } protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }
额,请问老师为什么代码不执行for循环里面的代码呢?
chrismorgen
2018-07-20 18:09:07
想要检测id是否重复添加,你只需要获得用户录入的id和图书分类的集合就可以实现你说的功能,如下图所示,先判断用户录入的id是否存在于bookClassMap集合中,如果存在则返回true,不存在则返回false,如果flag为false,则执行添加分类,是这样的逻辑,对于同学说的“图书分类并不需要定义一个单独的类”这里不是很理解,祝学习愉快~
chrismorgen
2018-07-20 17:27:46
对图书分类进行添加时不需要遍历整个集合,只需要向map集合中添加数据即可。根据你的描述,我不是很清楚你的整个思路,对于添加图书分类,只需要创建一个map集合用来存储图书分类的信息就可以了,如下图所示。
从网页搭建入门Java Web2018版
- 参与学习 人
- 提交作业 1088 份
- 解答问题 10204 个
如果你有Java语言基础,又想以后从事Java Web开发,那么本路径是你的不二选择!本路径从网页搭建开始入手,通过大量案例来学习Java Web基础。定能助你完成Java Web小白的蜕变!
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星