课题打卡,请老师检查有无疏漏

课题打卡,请老师检查有无疏漏

package mgallery.dao;


import java.util.ArrayList;
import java.util.List;
import mgallery.entity.Painting;
import mgallery.utils.PageModel;
import mgallery.utils.XmlDataSource;

public class PaintingDao {
    
    public PageModel pagination(int page, int rows) {
     List<Painting> list = XmlDataSource.getRawData();
     PageModel pageModel  = new PageModel(list,page,rows);    
     return pageModel;
    }
  
    public PageModel pagination(int category, int page, int rows) {
      List<Painting> list = XmlDataSource.getRawData();
      List<Painting> categoryList = new ArrayList();
      for(Painting p: list) {
        if(p.getCategroy() ==category ) {
          categoryList.add(p);
        }        
      }
      PageModel pageModel  = new PageModel(categoryList,page,rows);  
      return pageModel;
    }
    
    public void create(Painting painting) {
      XmlDataSource.append(painting);
    }
    
    public Painting findById(Integer id) {
      List<Painting> list = XmlDataSource.getRawData();
      Painting painting = null;
      for (Painting p:list) {
        if(p.getId() == id) {
          painting = p;
          break;
        }
      }
      return painting;
    }
    
    public void update(Painting painting) {
      XmlDataSource.update(painting);
    }
    
    public void delete(Painting painting) {
      XmlDataSource.delete(painting);
    }
    
}
package mgallery.service;

import javax.management.RuntimeErrorException;
import mgallery.dao.PaintingDao;
import mgallery.entity.Painting;
import mgallery.utils.PageModel;

public class PaintingService {
    private PaintingDao paintingDao = new PaintingDao();
    
    public PageModel pagination(int page,int rows, String...category) {
      if (rows == 0) {
        throw new RuntimeException("无效的rows 参数");
      }      
      if(category.length ==0 || category[0]==null) {
        return paintingDao.pagination(page, rows);
      }else {
        return paintingDao.pagination(Integer.parseInt(category[0]), page, rows);
      }
    }
    
    public void create(Painting painting) {
      paintingDao.create(painting);
    }
    
    public Painting findById(Integer id) {
      Painting p = paintingDao.findById(id);
      if(p == null) {
        throw new RuntimeException("该id不存在");
      }
      return p;
      
    }
    
    public void update(Painting painting, String isPreviewModified) {
       Painting npainting = painting; 
      
      if(isPreviewModified.equals("0")) {
        Painting oldPainting = paintingDao.findById(npainting.getId());
        String preview = oldPainting.getPreview();
        npainting.setPreview(preview);
      }
      
      System.out.println(npainting);
      paintingDao.update(npainting);

    }
    
    public void delete(Painting painting) {
      paintingDao.delete(painting);
    }
    

}
package mgallery.controller;

import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;
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 org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileItemFactory;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import mgallery.entity.Painting;
import mgallery.service.PaintingService;
import mgallery.utils.PageModel;

/**
 * Servlet implementation class ManagementController
 */
@WebServlet("/management")
public class ManagementController extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private PaintingService paintingService = new PaintingService();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public ManagementController() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
	    request.setCharacterEncoding("utf-8");
	    response.setContentType("text/html;charset=utf-8");
	    String method = request.getParameter("method");
	    if(method.equals("list")) {
	      this.list(request,response);
	    }else if(method.equals("show_create")){
	      this.showCreatePage(request,response);
	    }else if(method.equals("create")) {
	      this.create(request, response);
	    }else if(method.equals("show_update")) {
	      this.showUpdatePage(request,response);
	    }else if(method.equals("update")) {
	      this.update(request,response);
	    }else if(method.equals("delete")) {
	      this.delete(request,response);
	    }
	    
	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		doGet(request, response);
	}

	private void list(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  String p = request.getParameter("p");
	  String r = request.getParameter("r");
	  if(p==null) {
	    p="1";
	  }
	  if(r == null) {
	    r ="6";
	  }
	  PageModel pageModel = paintingService.pagination(Integer.parseInt(p),Integer.parseInt(r));
	  request.setAttribute("pageModel", pageModel);
	  request.getRequestDispatcher("/WEB-INF/jsp/list.jsp").forward(request, response);
	  
	}
	
	private void showCreatePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	    request.getRequestDispatcher("/WEB-INF/jsp/create.jsp").forward(request, response);
	}
	
	private void create(HttpServletRequest request, HttpServletResponse response) {
	  FileItemFactory factory = new DiskFileItemFactory();
	  ServletFileUpload sf = new ServletFileUpload(factory);
	  
	  try {
      List<FileItem> formData = sf.parseRequest(request);
      Painting painting = new Painting();
      for (FileItem fi:formData) {
        if(fi.isFormField() ) {
          //System.out.println(fi.getFieldName() );
          switch (fi.getFieldName()) {
            case "pname":
              painting.setPname(fi.getString("UTF-8"));
              break;
            case "category":
              painting.setCategroy(Integer.parseInt(fi.getString("UTF-8")));
              break;
            case "price":
              painting.setPrice(Integer.parseInt(fi.getString("UTF-8")));
              break;
            case "description":
              painting.setDescrption(fi.getString("UTF-8"));
              break;
            default:
              break;
          }
          
          
        }else {
          String path = request.getServletContext().getRealPath("/upload");
          //System.out.println(path);
          String fileName = UUID.randomUUID().toString();
          String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
          fi.write(new File(path,fileName + suffix));
          painting.setPreview("/upload/" + fileName + suffix);
          
        }
      }
      
      paintingService.create(painting);
      response.sendRedirect("/management?method=list");
    } catch ( Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
	  
	}
	
	private void showUpdatePage(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	  String id = request.getParameter("id");
	  Painting painting = paintingService.findById(Integer.parseInt(id));
	  request.setAttribute("painting", painting);
	  request.getRequestDispatcher("/WEB-INF/jsp/update.jsp").forward(request, response);
	}
	
	private void update(HttpServletRequest request, HttpServletResponse response) {
	   FileItemFactory factory = new DiskFileItemFactory();
	   ServletFileUpload sf = new ServletFileUpload(factory);
	   String isPreviewModified = null;
	   try {
      List<FileItem> formData = sf.parseRequest(request);
      Painting painting = new Painting();
      for(FileItem fi:formData) {
        switch (fi.getFieldName()) {
          case "pname":
            painting.setPname(fi.getString("UTF-8"));
            break;
          case "category":
            painting.setCategroy(Integer.parseInt(fi.getString("UTF-8")));
            break;
          case "price":
            painting.setPrice(Integer.parseInt(fi.getString("UTF-8")));
            break;
          case "description":
            painting.setDescrption(fi.getString("UTF-8"));
            break;
          case "id":
            painting.setId(Integer.parseInt(fi.getString("UTF-8")));
            break;
          case "isPreviewModified":
            isPreviewModified = fi.getString("UTF-8");
            break;
          default:
            break;
        }       
      }
      
      if(isPreviewModified.equals("1")) {
        for(FileItem fi:formData) {
          if(!fi.isFormField()) {
            String path = request.getServletContext().getRealPath("/upload");
            String fileName = UUID.randomUUID().toString();
            String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
            fi.write(new File(path,fileName + suffix));
            painting.setPreview("/upload/" + fileName + suffix);
            
          }
        }       
      }      
      paintingService.update(painting, isPreviewModified);
      response.sendRedirect("/management?method=list");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  
	}
	
	private void delete(HttpServletRequest request, HttpServletResponse response) throws IOException {
	  
	  Integer id = Integer.parseInt(request.getParameter("id"));
	  try {
	  paintingService.delete(paintingService.findById(id));
	  String result = "{\"result\":\"ok\"}";
	  JSONObject json = JSON.parseObject(result);
      response.getWriter().println(json);
    } catch (IOException e) {
      // TODO Auto-generated catch block
      e.printStackTrace();     
      String result = "{\"result\": "+  e.getMessage()+ "}";
      JSONObject json = JSON.parseObject(result);
      response.getWriter().println(json);
    }  

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

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>油画列表</title>
<link rel="stylesheet" type="text/css" href="css\list.css">
<script type="text/javascript" src="js/jquery-3.4.1.min.js"></script>
<script type="text/javascript" src="js/sweetalert2.js"></script>
<script type="text/javascript">

function showPreview(previewObj){
	   var preview = $(previewObj).attr("data-preview");
	   var pname = $(previewObj).attr("data-pname");
	   swal.fire({
		  title: pname,
	      html: "<img src='"+preview+"' style='width:361px;height:240px'>",
	      showCloseButton: true,
	      showConfirmButton: false,
	   })
}

function del(obj){
	var id = $(obj).attr("data-id");
	var pname = $(obj).attr("data-pname");
	var preview = $(obj).attr("data-preview");
	
	swal.fire({
		   title: "确认要删除" + pname + "油画么",
		   html: "<img src='"+preview+"' style='width:361px;height:240px'>",
		   showCancelButton: true,
		   confirmButtonText:"是",
		   cancelButtonText:"否"	   		
	}).then(function(result){
		if(result.value == true){
			 $.ajax({
		           "url":"/management",
		            "type":"get",
		            "data":{"id":id,"method":"delete"},
		            "datatype":"json",
		            "success":function(data){
		            	var json = JSON.parse(data);

		                if(json.result == "ok"){
		                	console.log("1");
		                	window.location.reload();
		                }else{
		                	console.log("2");
		                	swal.fire({
	                             title: json.result       
		                	})
		                	
		                }
		            }
		    })			
		}
		
	})
	
	
	

	
}

</script>
</head>
<body>
	<div class="container">
		<fieldset>
			<legend>油画列表</legend>
			<div style="height: 40px">
				<a href="/management?method=show_create" class="btn-button">新增</a>
			</div>
			<!-- 油画列表 -->
			<table cellspacing="0px">
				<thead>
					<tr style="width: 150px;">
						<th style="width: 100px">分类</th>
						<th style="width: 150px;">名称</th>
						<th style="width: 100px;">价格</th>
						<th style="width: 400px">描述</th>
						<th style="width: 100px">操作</th>
					</tr>
				</thead>
				<c:forEach items="${pageModel.pageData }" var="painting">
					<tr>
					   <c:choose>
					       <c:when test="${painting.categroy ==1 }">
					       <td>现实主义</td>
					       </c:when>
						  <c:when test="${painting.categroy ==2 }">
						  <td>抽象主义</td>
						  </c:when>
						  <c:otherwise>
						  <td>未知的油画类型</td>
						  </c:otherwise>
					   </c:choose>
						<td>${painting.pname }</td>
						<td><fmt:formatNumber pattern="$,000.00" value="${painting.price }"></fmt:formatNumber>  </td>
						<td>${painting.descrption }</td>
						<td>
							<a class="oplink" data-preview="${painting.preview }"  data-pname="${painting.pname }" href="javascript:void(0)" onclick="showPreview(this)">预览</a>
							<a class="oplink" href="/management?method=show_update&id=${painting.id }">修改</a>
							<a class="oplink" href="javascript:void(0)"  data-id="${painting.id }"  data-pname="${painting.pname }" data-preview="${painting.preview }" onclick ="del(this)">删除</a>
						</td>
					</tr>
				</c:forEach>
			</table>
			<!-- 分页组件 -->
			<ul class="page">
				<li><a href="/management?method=list">首页</a></li>
				<c:if test="${pageModel.hasPreviousPage ==true}">
				<li><a href="/management?method=list&p=${pageModel.page -1}">上页</a></li>
				</c:if>
				<c:forEach begin="1" end="${pageModel.totalPages}" var="pno" step="1">
				<li ${pno==pageModel.page?"class='active'":""} ><a href="/management?method=list&p=${pno}">${pno}</a></li>
                </c:forEach>
                <c:if test="${pageModel.hasNextPage == true}">
				<li><a href="/management?method=list&p=${pageModel.page +1 }">下页</a></li>
				</c:if>
				<li><a href="/management?method=list&p=${pageModel.totalPages }">尾页</a></li>
			</ul>
		</fieldset>
	</div>

</body>
</html>


正在回答

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

3回答

同学你好,代码运行效果是正确的,很棒,继续加油~如果我的回答解决了你的疑惑,请采纳,祝学习愉快~

慕前端8369922 提问者 2020-07-25 01:54:59
package mgallery.utils;

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.UnsupportedEncodingException;
import java.io.Writer;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import mgallery.entity.Painting;

//将xml对象解析为java对象
public class XmlDataSource {
//通过static关键字保证全局唯一
    private static List data = new ArrayList();
    private static String dataFile;
    private static Integer maxId = data.size();
    static { 
      //在程序运行以后得到类路径目录下的painint.xml的路径地址
       dataFile =  XmlDataSource.class.getResource("/painting.xml").getPath();
       //System.out.println(dataFile);
       //倘若上面读取到的路径包含有特殊字符,类似于空格,
       //会被自动转换为%20,导致读取时出错,底下为解决方法
       reload();
       
    }
    
     private static void reload() {
       URLDecoder decode = new URLDecoder();
       try {
        dataFile = decode.decode(dataFile,"UTF-8");
        //利用dom4j对xml文档进行解析
        SAXReader reader = new SAXReader();
        //1.获取Document对象
        Document document = reader.read(dataFile);
        //2.利用xpath得到xml节点集合,导入一定是org.dom4j.node
        List<Node> nodes = document.selectNodes("/root/painting");
        data.clear();
        for (Node node:nodes) {
          Element element = (Element)node;
          String id = element.attributeValue("id");
          String pname = element.elementText("pname");
          Painting painting = new Painting();
          painting.setId(Integer.parseInt(id));
          painting.setPname(pname);
          painting.setCategroy(Integer.parseInt(element.elementText("category")));
          painting.setPrice(Integer.parseInt(element.elementText("price")));
          painting.setPreview(element.elementText("preview"));
          painting.setDescrption(element.elementText("description"));
          if(maxId < painting.getId()) {
            maxId = painting.getId();
          }
          data.add(painting);
          
        }
      } catch (UnsupportedEncodingException | DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }
       
    }
     
    
    public static List<Painting> getRawData(){
      return data;
    }
    
    public static void append(Painting painting) {
        SAXReader reader = new SAXReader();
        Writer writer = null;
        try {
          Document document = reader.read(dataFile);
          Element root = document.getRootElement();
          Element p = root.addElement("painting");
          p.addAttribute("id", String.valueOf(maxId+1));
          maxId += 1;
          p.addElement("pname").setText(painting.getPname());
          p.addElement("category").setText(painting.getCategroy().toString());
          p.addElement("price").setText(painting.getPrice().toString());
          p.addElement("preview").setText(painting.getPreview());
          p.addElement("description").setText(painting.getDescrption());
          writer = new OutputStreamWriter(new FileOutputStream(dataFile),"UTF-8");
          System.out.println(dataFile);
          document.write(writer);
        } catch (Exception e) {
          // TODO Auto-generated catch block
          e.printStackTrace();
        }finally {
          if(writer != null) {
            try {
              writer.close();
            } catch (IOException e) {
              // TODO Auto-generated catch block
              e.printStackTrace();
            }
          }
          reload();
        }
    }
    
    
    public static void update(Painting painting) {
      SAXReader reader = new SAXReader();
      Writer writer = null;
      try {
        Document document =reader.read(dataFile);
        List<Node> nodes = document.selectNodes("/root/painting[@id="+ painting.getId()+"]");
        if(nodes.size() == 0) {
          throw new RuntimeException("id: " + painting.getId() + "不存在");
        }
        Element p = (Element)nodes.get(0);
        p.selectSingleNode("pname").setText(painting.getPname());
        p.selectSingleNode("category").setText(painting.getCategroy().toString());
        p.selectSingleNode("price").setText(painting.getPrice().toString());
        p.selectSingleNode("description").setText(painting.getDescrption());
        p.selectSingleNode("preview").setText(painting.getPreview());
        writer = new OutputStreamWriter(new FileOutputStream(dataFile),"UTF-8");
        document.write(writer);
        
      } catch (DocumentException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }finally {
        if(writer != null) {
          try {
            writer.close();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        reload();
      }
      
    }
    
    
    public static void delete(Painting painting) {
      SAXReader reader = new SAXReader();
      Writer writer = null;
      Document document;
      try {
        document = reader.read(dataFile);
        List<Node> nodes = document.selectNodes("/root/painting[@id="+ painting.getId()+"]");

        if(nodes.size() == 0) {
          throw new RuntimeException("id: " + painting.getId() + "不存在");
        }
        
        Element p =(Element)nodes.get(0);
        Element r = p.getParent();
        r.remove(p);
        writer = new OutputStreamWriter( new FileOutputStream(dataFile),"UTF-8");
        document.write(writer);
        
      } catch (DocumentException | IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
      }finally{
        if(writer != null) {
          try {
            writer.close();
          } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
          }
        }
        reload();
      }

      
    }

        
    public static void main(String[] args) {
      Painting p = new Painting();
      p.setPname("测试油画");
      p.setId(2);
      p.setCategroy(1);
      p.setPrice(4000);
      p.setPreview("/upload/1.jpg");
      p.setDescrption("描述信息");
      XmlDataSource.delete(p);
    }
  
}


好帮手慕阿慧 2020-07-24 15:13:24

同学你好,同学没有提交XmlDataSource类的代码,建议同学贴一下,方便老师检查。

如果我的回答解决了你的疑惑,请采纳!祝学习愉快!

  • 提问者 慕前端8369922 #1
    好的我把它贴在上面了
    2020-07-25 01:55:29
问题已解决,确定采纳
还有疑问,暂不采纳

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

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

0 星
请稍等 ...
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号

在线咨询

领取优惠

免费试听

领取大纲

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