用JSP做后台管理系统

添加新闻

/**
  * 获取从页面读取的数据
  * @param request
  * @return 单个新闻信息
  * @throws UnsupportedEncodingException
  */
 private News getNews(HttpServletRequest request) throws UnsupportedEncodingException {
  request.setCharacterEncoding("UTF-8");
  //读取用户选择的是哪一个主题ID
  String id = request.getParameter("topic");
  //把值转换为Int类型 传给 Topic实体类
  Topic topic = new Topic(Integer.parseInt(id));
  //标题
  String title = request.getParameter("title");
  //作者
  String author = request.getParameter("author");
  //摘要
  String summary = request.getParameter("summary");
  //内容
  String ncontent = request.getParameter("ncontent");
  
  News news = new News(topic,title,author,summary,ncontent); 
  
  return news;
 }

 /**
  * 添加新闻
  */
 public void addNews(HttpServletRequest request, HttpServletResponse response)
 throws ServletException, IOException {
  boolean b = ndi.addNews(getNews(request));  
  if( b){
   selectNews(request, response);
   }else{
    request.setAttribute("errorInfo", "新闻添加失败!");
    request.getRequestDispatcher("error.jsp").forward(request, response); 
   }
 }

下面详细说为什么获取错了。

第一步:

  我先手动从数据库往表中添加数据,结果发现可以。但是不能执行。

第二步:

  我修改了要添加进news实体类中的值,改为了字符串而并非是页面的内容,结果上面显示说,有FK约束。还是不能执行。

第三步:

  终于知道错误所在了,好开心。然后就把我之前建错的外键约束给改了。

  t_news : id ==t_topic : id ---> t_news : tid == t_topic : id

  因为我把两个表中的主键给关联一起了,所以就不能执行。改成新闻表中的主题ID列与主题表中的ID列相对应就可以了。结果发现还是不能执行。

第四步:

  又跳转到页面上,发现我竟然没有给下拉菜单个名字!!

  唉,真是粗心大意的我啊。然后想起了教员所谓的要让程序找到你的下拉框才能给值,于是就给了id。

  这样应该就行了吧。结果还是不行。

第五步:

  问了教员。他就看了一眼,说了句:

  <%--想要获取select的value值,就需要给他一个名字。切记:用name而非id,ID是唯一的,适用于CSS,name利于后台获取 --%>

  原来,不是id而是name啊。
     <select name="topic">
      <c:forEach items="${topicList}" var="topic">      
       <option value="${topic.id}" />${topic.tname}
      </c:forEach>    
      </select>

这个项目终于能见睁开眼看世界了。看着自己创造出来的东西真心幸福。

最后告诫我一句,调试真的很重要,英语单词真的很重要,课外知识真的很重要。

原文地址:https://www.cnblogs.com/liping0720/p/4876107.html