老师来看看 为什么出现空指针异常
update.js
<%@page contentType="text/html;charset=utf-8" %>
<!-- 修改油画页面 -->
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>作品更新</title>
<link rel="stylesheet" type="text/css" href="css\create.css">
<script type="text/javascript" src="js/jquery-3.5.1.min.js"></script>
<script type="text/javascript" src="js/validation.js"></script>
<script type="text/javascript">
<!-- 提交前表单校验 -->
function checkSubmit() {
var result = true;
var r1 = checkEmpty("#pname", "#errPname");
var r2 = checkCategory("#category", "#errCategory");
var r3 = checkPrice("#price", "#errPrice");
var r4 = null;
if ($("#isPreviewModified").val() == "1") {
r4 = checkFile("#painting", "#errPainting");
}else {
r4 = true;
}
var r5 = checkEmpty("#description", "#errDescription");
if (r1 && r2 && r3 && r4 && r5) {
return true;
} else {
return false;
}
}
$(function () {
$("#category").val(${painting.category});
})
function selectPreview() {
checkFile("#painting", "#errPainting");
$("#preview").hide();
$("#isPreviewModified").val(1);
}
</script>
</head>
<body>
<div class="container">
<fieldset>
<legend>作品更新</legend>
<form action="/management?method=update" method="post"
autocomplete="off" enctype="multipart/form-data"
onsubmit="return checkSubmit()">
<ul class="ulform">
<li>
<span>油画名称</span>
<span id="errPname"></span>
<input id="pname" name="pname" value="${painting.pname}" onblur="checkEmpty('#pname','#errPname')"/>
</li>
<li>
<span>油画类型</span>
<span id="errCategory"></span>
<select id="category" name="category" onchange="checkCategory('#category','#errCategory')">
<option value="-1">请选择油画类型</option>
<option value="1">现实主义</option>
<option value="2">抽象主义</option>
</select>
</li>
<li>
<span>油画价格</span>
<span id="errPrice"></span>
<input id="price" name="price" value="${painting.price}" onblur="checkPrice('#price','#errPrice')"/>
</li>
<li>
<span>作品预览</span>
<input type="hidden" id="isPreviewModified" name="isPreviewModified" value="0"/>
<span id="errPainting"></span><br/>
<img id="preview" src="${painting.preview}" style="width:361px;height:240px"/><br/>
<input id="painting" name="painting" type="file" style="padding-left:0px;" accept="image/*"
onchange="selectPreview()"/>
</li>
<li>
<span>详细描述</span>
<span id="errDescription"></span>
<textarea
id="description" name="description"
onblur="checkEmpty('#description','#errDescription')"
>${painting.description}</textarea>
</li>
<li style="text-align: center;">
<input type="hidden" id="id" name="id" value="${painting.id}"/>
<button type="submit" class="btn-button">提交表单</button>
</li>
</ul>
</form>
</fieldset>
</div>
</body>
</html>
XmlDataSource
package com.mgallery.utils;
import com.mgallery.entity.Painting;
import com.sun.xml.internal.bind.v2.model.core.EnumLeafInfo;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.io.SAXReader;
import java.awt.*;
import java.io.*;
import java.net.URLDecoder;
import java.util.ArrayList;
import java.util.List;
/*数据源,用于将XML文件解析为Java对象*/
public class XmlDataSource {
private static List<Painting> data = new ArrayList();
//初始化
private static String dataFile;
static {
dataFile = XmlDataSource.class.getResource("/painting.xml").getPath();
reload();
}
private static void reload() {
//处理路径中特殊字符
URLDecoder decoder = new URLDecoder();
try {
//转为标准字符串,指定编码格式
dataFile = decoder.decode(dataFile, "UTF-8");
System.out.println(dataFile);
//利用Dom4j对XML进行解析
//解析对象
SAXReader reader = new SAXReader();
Document document = reader.read(dataFile);
List<Node> nodes = document.selectNodes("/root/painting");
//清空原有数据
data.clear();
for (Node node : nodes) {
Element element = (Element) node;
//数据提取 属性
String id = element.attributeValue("id");
String name = element.elementText("pname");
//实例化对象,并赋值
Painting painting = new Painting();
painting.setId(Integer.parseInt(id));
painting.setPname(name);
painting.setCategory(Integer.parseInt(element.elementText("category")));
painting.setPrice(Integer.parseInt(element.elementText("price")));
painting.setPreview(element.elementText("preview"));
painting.setDescription(element.elementText("description"));
data.add(painting);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取所有油画 Painting对象
*
* @return Painting List
*/
public static List<Painting> getRawData() {
return data;
}
/**
* 追加新的油画数据
*
* @param painting Painting实体对象
*/
public static void append(Painting painting) {
//1. 读取XML文档,得到Document对象
SAXReader reader = new SAXReader();
Writer writer = null;
try {
Document document = reader.read(dataFile);
//2. 创建新的painting节点
Element root = document.getRootElement();//得到<root>根节点
Element p = root.addElement("painting");//添加新的painting节点
p.addAttribute("id", String.valueOf(data.size() + 1));
p.addElement("pname").setText(painting.getPname());
p.addElement("category").setText(painting.getCategory().toString());
p.addElement("price").setText(painting.getPrice().toString());
p.addElement("preview").setText(painting.getPreview());
p.addElement("description").setText(painting.getDescription());
//4. 写入XML,完成追加
writer = new OutputStreamWriter(new FileOutputStream(dataFile), "UTF-8");
document.write(writer);//新节点更新
System.out.println(dataFile);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
reload();//内存与文件一致性
}
}
/**
* 更新对应id的XML油画数据
*
* @param painting 要更新的油画数据
* @throws IOException
*/
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.getCategory().toString());
p.selectSingleNode("price").setText(painting.getPrice().toString());
p.selectSingleNode("preview").setText(painting.getPreview());
p.selectSingleNode("description").setText(painting.getDescription());
writer = new OutputStreamWriter(new FileOutputStream(dataFile), "UTF-8");
document.write(writer);
} catch (Exception e) {
e.printStackTrace();
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
reload();
}
}
public static void main(String[] args) {
/* List<Painting> ps = XmlDataSource.getRawData();
System.out.println(ps);*/
Painting p = new Painting();
p.setPname("测试油画");
p.setCategory(1);
p.setPrice(3000);
p.setPreview("/upload/10.jpg");
p.setDescription("测试油画描述");
XmlDataSource.append(p);
}
}
PaintingDao
package com.mgallery.dao;
import com.mgallery.entity.Painting;
import com.mgallery.utils.PageModel;
import com.mgallery.utils.XmlDataSource;
import java.util.ArrayList;
import java.util.List;
//油画数据访问对象
public class PaintingDao {
/**
* 分页查询油画数据
* @param page 页号(第几页)
* @param rows 每页记录数(一页多少行)
* @return PageModel 分页对象
*/
//page: rows:
public PageModel pagination(int page ,int rows){
List<Painting> list = XmlDataSource.getRawData();
PageModel pageModel = new PageModel(list,page,rows);
return pageModel;
}
/**
* 按类别分页查询
* @param category 分类编号
* @param page 页号
* @param rows 每页行数
* @return 分页对象
*/
public PageModel pagination(int category,int page,int rows){
List<Painting> paintingList = XmlDataSource.getRawData();
List<Painting> categoryList = new ArrayList<>();
for (Painting p :paintingList){
if (p.getCategory() == category){
categoryList.add(p);
}
}
PageModel pageModel = new PageModel(categoryList,page,rows);
return pageModel;
}
/**
* 数据新增
*/
public void create(Painting painting){
XmlDataSource.append(painting);
}
/**
* 按编号查询油画
* @param id 油画编号
* @return 油画对象
*/
public Painting findById(Integer id) {
List<Painting> data = XmlDataSource.getRawData();
Painting painting = null;
for (Painting p : data) {
if (p.getId() == id) {
painting = p;
break;
}
}
return painting;
}
/**
* 数据修改
* @param painting 修改的Painting数据
*/
public void update(Painting painting){
XmlDataSource.update(painting);
}
}
PaintingService
package com.mgallery.service;
import com.mgallery.dao.PaintingDao;
import com.mgallery.entity.Painting;
import com.mgallery.utils.PageModel;
import com.mgallery.utils.XmlDataSource;
import java.util.List;
//PaintingService油画服务类
public class PaintingService {
private PaintingDao paintingDao = new PaintingDao();
/**
* pagination 数据分页查询
*
* @param page 页号
* @param rows 每页行数
* @param category 可选参数,分类编号
* @return 分页对象
*/
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);
}
}
/**
* 新增油画
*
* @param painting 准备新增的Painting数据
*/
public void create(Painting painting) {
paintingDao.create(painting);
}
/**
* 按编号查询油画
*
* @param id 油画编号
* @return 油画对象
*/
public Painting findById(Integer id) {
Painting p = paintingDao.findById(id);
if (p == null) {
throw new RuntimeException("[id = " + id + "]油画不存在");
}
return p;
}
/**
* 修改油画
*
* @param newPainting 修改的Painting数据
*/
public void update(Painting newPainting, int isPreviewModified) {
Painting painting = paintingDao.findById(newPainting.getId());
if (isPreviewModified == 1) {
painting.setPreview(newPainting.getPreview());
}
paintingDao.update(painting);
}
public static void main(String[] args) {
PaintingService service = new PaintingService();
PageModel model = service.pagination(2, 6);
List<Painting> list = model.getPageData();
for (Painting p : list) {
System.out.println(p.getPname());
}
System.out.println(model.getPageStartRow() + ":" + model.getPageEndRow());
}
}
ManagementControlle
package com.mgallery.controller;
import com.mgallery.entity.Painting;
import com.mgallery.service.PaintingService;
import com.mgallery.utils.PageModel;
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 javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.util.List;
import java.util.UUID;
@WebServlet("/management")
public class ManagementController extends HttpServlet {
//油画服务类
private PaintingService paintingService = new PaintingService();
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("UTF-8");
resp.setContentType("text/html;charset=UTF-8");
//判断哪种处理方法
String method = req.getParameter("method");
if (method.equals("list")) {
//显示分页查询列表
this.list(req, resp);
} else if (method.equals("delete")) {
//调用删除方法
} else if (method.equals("show_create")) {
//显示新增页面
this.showCreatePage(req, resp);
} else if (method.equals("create")) {
this.create(req, resp);
} else if (method.equals("show_update")) {
//显示修改页面
this.showUpdatePage(req, resp);
} else if (method.equals("update")) {
this.update(req, resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
private void list(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//分页查询 接收页号和每页行数
String page = req.getParameter("p");
String rows = req.getParameter("r");
//判断是否传入 无,添加默认值
if (page == null) {
page = "1";
}
if (rows == null) {
rows = "6";
}
//接收分页数据
PageModel pageModel = paintingService.pagination(Integer.parseInt(page), Integer.parseInt(rows));
req.setAttribute("pageModel", pageModel);
req.getRequestDispatcher("/WEB-INF/jsp/list.jsp").forward(req, resp);
}
//新增油画页面
private void showCreatePage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.getRequestDispatcher("/WEB-INF/jsp/create.jsp").forward(req, resp);
}
//新增油画方法
private void create(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//文件上传时的数据处理与标准表单完全不同
//上传顺序 1. 初始化FileUpload组件
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sf = new ServletFileUpload(factory);
//2. 遍历所有FileItem
try {
List<FileItem> formData = sf.parseRequest(req);
//实例化painting对象
Painting painting = new Painting();
for (FileItem fi : formData) {
if (fi.isFormField()) {
//true 普通输入项
System.out.println("普通输入项:" + fi.getFieldName() + ":" + fi.getString("UTF-8"));
switch (fi.getFieldName()) {
case "pname":
painting.setPname(fi.getString("UTF-8"));
break;
case "category":
painting.setCategory(Integer.parseInt(fi.getString("UTF-8")));
break;
case "price":
painting.setPrice(Integer.parseInt(fi.getString("UTF-8")));
break;
case "description":
painting.setDescription(fi.getString("UTF-8"));
break;
default:
break;
}
} else {
//false 文件上传框
System.out.println("文件上传项:" + fi.getFieldName());
//3. 文件保存到服务器目录
String path = req.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);//新增功能
//相应重定向 返回油画列表页,对数据进行展示
resp.sendRedirect("/management?method=list");
} catch (Exception e) {
e.printStackTrace();
}
//显示更新页面
private void showUpdatePage(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取id
String id = req.getParameter("id");
Painting painting = paintingService.findById(Integer.parseInt(id));
req.setAttribute("painting", painting);
//请求转发
req.getRequestDispatcher("/WEB-INF/jsp/update.jsp").forward(req, resp);
}
//修改油画方法
private void update(HttpServletRequest req, HttpServletResponse resp) {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sf = new ServletFileUpload(factory);
try {
List<FileItem> list = sf.parseRequest(req);
Painting p = new Painting();
int isPreviewModified = 0;
//遍历
for (FileItem f : list) {
if (f.isFormField()) {
switch (f.getFieldName()) {
case "pname":
p.setPname(f.getString("UTF-8"));
break;
case "category":
p.setCategory(Integer.parseInt(f.getString("UTF-8")));
break;
case "price":
p.setPrice(Integer.parseInt(f.getString("UTF-8")));
break;
case "description":
p.setDescription(f.getString("UTF-8"));
break;
case "id":
p.setId(Integer.parseInt(f.getString("UTF-8")));
break;
case "isPreviewModified":
isPreviewModified = Integer.parseInt(f.getString("UTF-8"));
default:
break;
}
} else {
if (isPreviewModified == 1) {
String path = req.getServletContext().getRealPath("/upload");
String fileName = UUID.randomUUID().toString();
String suffix = f.getName().substring(f.getName().lastIndexOf("."));
f.write(new File(path, fileName + suffix));
p.setPreview("/upload/" + fileName + suffix);
}
}
paintingService.update(p, isPreviewModified);
resp.sendRedirect("/management?method=list");
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
正在回答
同学你好,update()方法写错位置了。同学应该在遍历完List<FileItem>表单项后再调用update()方法。
参考代码如下:
如果我的回答解决了你的疑惑,请采纳!祝学习愉快!
- 参与学习 人
- 提交作业 9393 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星