为什么点击修改按钮后无法跳转回list页面呢,找不到错误了,请老师帮忙
package com.imooc.mgallery.controller;
import java.io.File;
import java.io.IOException;
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.imooc.mgallery.entity.Painting;
import com.imooc.mgallery.service.PaintingService;
import com.imooc.mgallery.utils.PageModel;
/**
* 后台管理功能Controller
*/
@WebServlet("/management")
public class ManagementController extends HttpServlet {
private PaintingService paintingService = new PaintingService();
private static final long serialVersionUID = 1L;
/**
* @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 {
request.setCharacterEncoding("UTF-8");
response.setContentType("text/html;charset=utf-8");
// 通过method参数区分不同的操作
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);
}
}
/**
* @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) throws ServletException, IOException {
//文件上传时的数据处理与标准表单完全不同
/*
String pname = request.getParameter("pname");
System.out.println(pname);
*/
//1. 初始化FileUpload组件
FileItemFactory factory = new DiskFileItemFactory();
/**
* FileItemFactory 用于将前端表单的数据转换为一个个FileItem对象
* ServletFileUpload 则是为FileUpload组件提供Java web的Http请求解析
*/
ServletFileUpload sf = new ServletFileUpload(factory);
//2. 遍历所有FileItem
try {
List<FileItem> formData = sf.parseRequest(request);
Painting painting = new Painting();
for(FileItem fi:formData) {
if(fi.isFormField()) {
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 {
System.out.println("文件上传项:" + fi.getFieldName());
//3.文件保存到服务器目录
String path = request.getServletContext().getRealPath("/upload");
System.out.println("上传文件目录:" + path);
//String fileName = "test.jpg";
String fileName = UUID.randomUUID().toString();
//fi.getName()得到原始文件名,截取最后一个.后所有字符串,例如:wxml.jpg->.jpg
String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
//fi.write()写入目标文件
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();
}
}
/**
* 显示更新页面
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
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);
}
/**
* 更新油画列表
* @param request
* @param response
* @throws ServletException
* @throws IOException
*/
private void update(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException{
System.out.println("已跳转至update");
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sf = new ServletFileUpload(factory);
try {
List<FileItem> formData = sf.parseRequest(request);
String id = null;
String is = null;
Painting painting = new Painting();
for(FileItem fi:formData) {
if(fi.isFormField()) {
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;
case "isPreviewModified":
is = fi.getString("utf-8");
break;
case "id":
id = fi.getString("utf-8");
painting.setId(Integer.parseInt(id));
break;
default:
break;
}
}
else {
System.out.println("文件上传项:" + fi.getFieldName());
if(is.equals("1")) {
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);
}else {
painting.setPreview(null);
}
}
}
paintingService.update(painting, Integer.parseInt(is));
// response.sendRedirect("/management?method=list");
response.sendRedirect("/management?method=list");//返回列表页
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}<%@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.4.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 = checkFile('#painting', '#errPainting');
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" onblur="checkEmpty('#pname','#errPname')" value="${painting.pname }"/>
</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" onblur="checkPrice('#price','#errPrice')" value="${painting.price }"/>
</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>package com.imooc.mgallery.dao;
import java.util.ArrayList;
import java.util.List;
import com.imooc.mgallery.entity.Painting;
import com.imooc.mgallery.utils.PageModel;
import com.imooc.mgallery.utils.XmlDataSource;
/**
* 油画数据访问对象
*/
public class PaintingDao {
/**
* 分页查询油画数据
* @param page 页号
* @param rows 每页记录数
* @return PageModel分页对象
*/
public PageModel pagination(int page,int rows) {
//Painting油画对象集合
List<Painting> list = XmlDataSource.getRawData();
//PageModel分页处理得到分页数据及分页附加
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> list = XmlDataSource.getRawData();
List<Painting> categoryList = new ArrayList();
for(Painting p:list) {
if(p.getCategory() == 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> data = XmlDataSource.getRawData();
Painting painting = null;
for(Painting p : data) {
if(p.getId() == id) {
painting = p;
break;
}
}
return painting;
}
/**
* 更新数据
* @param painting
*/
public void update(Painting painting) {
XmlDataSource.update(painting);
}
}package com.imooc.mgallery.service;
import java.util.List;
import com.imooc.mgallery.dao.PaintingDao;
import com.imooc.mgallery.entity.Painting;
import com.imooc.mgallery.utils.PageModel;
/**
* PaintingService油画服务类
*/
public class PaintingService {
private PaintingDao paintingDao = new PaintingDao();
/**
* pagination数据分页查询
* @param pageNo 页号
* @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;
}
public void update(Painting newPainting, int isPreviewModified) {
int id = newPainting.getId();
Painting p = paintingDao.findById(id);//原始的painting
if(isPreviewModified == 1) {
p.setPreview(newPainting.getPreview());
}
p.setCategory(newPainting.getCategory());
p.setDescription(newPainting.getDescription());
p.setPname(newPainting.getPname());
paintingDao.update(p);
}
public static void main(String[] args) {
PaintingService paintingService = new PaintingService();
PageModel pageModel = paintingService.pagination(2, 6);
List<Painting> paintingList = pageModel.getPageData();
for(Painting painting : paintingList) {
System.out.println(painting.getPname());
}
System.out.println(pageModel.getPageStartRow() + ":" + pageModel.getPageEndRow());
}
}31
收起
正在回答 回答被采纳积分+1
2回答
java工程师2020版
- 参与学习 人
- 提交作业 9410 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程

恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星