ajax好像没有把消息发送到servlet,老师帮忙看一下
# 具体遇到的问题
# 报错信息的截图
# 相关课程内容截图
# 尝试过的解决思路和结果
# 粘贴全部相关代码,切记添加代码注释(请勿截图)
package com.imooc.mgallery.controller;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
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.imooc.mgallery.entity.Painting;
import com.imooc.mgallery.service.PaintingService;
import com.imooc.mgallery.utils.PageModel;
/**
* 后台管理功能controller
* 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 {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//System.out.println(".......................");
String method = request.getParameter("method");
// System.out.println(method);
if (method.equals("list")) {
this.list(request,response);
} else if (method.equals("delete")) {
//System.out.println(".......................");
this.delete(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 "price":
painting.setPrice(Integer.parseInt(fi.getString("utf-8")));
break;
case "category":
painting.setCategory(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();//生成一个随机的 唯一的文件名
//截取文件名的最后一个 . 后面的所有字符串
String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
//写入目标文件
//3. 文件保存到服务器目录
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 IOException
* @throws ServletException
*/
private void update(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
FileItemFactory factory = new DiskFileItemFactory();
ServletFileUpload sf = new ServletFileUpload(factory);
try {
int isPreviewModified = 0;
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 "price":
painting.setPrice(Integer.parseInt(fi.getString("utf-8")));
break;
case "category":
painting.setCategory(Integer.parseInt(fi.getString("utf-8")));
break;
case "description":
painting.setDescription(fi.getString("utf-8"));
break;
case "id":
painting.setId(Integer.parseInt(fi.getString("utf-8")));
break;
case "isPreviewModified":
isPreviewModified = Integer.parseInt(fi.getString("utf-8"));
break;
default:
break;
}
} else {
//System.out.println("文件上传项:" + fi.getFieldName());
if (isPreviewModified == 1) {//文件改变
String path = request.getServletContext().getRealPath("/upload");
//System.out.println("上传文件目录:" + path);
//String fileName = "test.jpg";
String fileName = UUID.randomUUID().toString();//生成一个随机的 唯一的文件名
//截取文件名的最后一个 . 后面的所有字符串
String suffix = fi.getName().substring(fi.getName().lastIndexOf("."));
//写入目标文件
//3. 文件保存到服务器目录
fi.write(new File(path, fileName + suffix));
painting.setPreview("/upload/" + fileName + suffix);
}
}
}
paintingService.update(painting, isPreviewModified);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
request.getRequestDispatcher("/management.html").forward(request, response);
}
private void delete(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
// PrintWriter out = response.getWriter();
System.out.println("******************");
try {
Integer id = Integer.parseInt(request.getParameter("id"));
//System.out.println("id:----------------" + id);
paintingService.delete(id);
Map<String, String> msg = new HashMap<String, String>();
msg.put("result", "ok");
// String msg = "{\"result\":\"ok\"}";
//System.out.println("id:" + id);
response.getWriter().print(JSON.toJSONString(msg));
} catch (Exception e) {
// TODO: handle exception
Map<String, String> msg = new HashMap<String, String>();
msg.put("result", e.getMessage());
response.getWriter().print(JSON.toJSONString(msg));
}
//request.getRequestDispatcher("/management.html").forward(request, response);
}
}
在这里输入代码,可通过选择【代码语言】突出显示
//list.jsp
<%@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 src="js/jquery-3.4.1.min.js" type="text/javascript"></script>
<script src="js/sweetalert2.js" type="text/javascript"></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(delObj){
var id = $(delObj).attr("data-id");
var pname = $(delObj).attr("data-pname");
var preview = $(delObj).attr("data-preview");
Swal.fire({
title:"确定要删除[" + pname + "]吗?",
html:"<img src='" + preview + "' style='width:361px;height:240px'>",
showCancelButton:true,
confirmButtonText:"是",
cancelButtonText:"否"
}).then(function(result){
// console.log("-")
if(result.value == true){
//console.log("+")
$.ajax({
"url": "/management?method=delete&id=" + id,
"type":"get",
"dataType":"json",
"success":function(json){
//console.log("++");
if(json.result == "ok"){
window.location.reload();
} else{
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" varStatus="idx">
<tr>
<td>
<c:choose>
<c:when test="${painting.category == 1}">现实主义</c:when>
<c:when test="${painting.category == 2}">抽象主义</c:when>
<c:otherwise>未知类型</c:otherwise>
</c:choose>
</td>
<td>${painting.pname }</td>
<td><fmt:formatNumber pattern="¥0.00" value="${painting.price }"></fmt:formatNumber></td>
<td>${painting.description }</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" data-id="${painting.id }" data-pname="${painting.pname }" data-preview="${painting.preview }" onclick="del(this)" href="javascript:void(0)">删除</a>
</td>
</tr>
</c:forEach>
</table>
<!-- 分页组件 -->
<ul class="page">
<li><a href="/management?method=list&p=1">首页</a></li>
<li><a href="/management?method=list&p=${pageModel.hasPreviousPage?pageModel.page - 1:1 }">上页</a></li>
<c:forEach begin="1" end="${pageModel.totalPages}" var="pno" step="1">
<li class="${pno==pageModel.page?'active':''}"><a href="/management?method=list&p=${pno }">${pno }</a></li>
</c:forEach>
<li><a href="/management?method=list&p=${pageModel.hasNextPage?pageModel.page + 1:pageModel.totalPages}">下页</a></li>
<li><a href="/management?method=list&p=${pageModel.totalPages }">尾页</a></li>
</ul>
</fieldset>
</div>
</body>
</html>
//PaintingService
package com.imooc.mgallery.service;
/**
* service完成完整的程序业务逻辑
* @author zxy
*
*/
import java.util.List;
import javax.management.RuntimeErrorException;
import com.imooc.mgallery.dao.PaintingDao;
import com.imooc.mgallery.entity.Painting;
import com.imooc.mgallery.utils.PageModel;
import com.imooc.mgallery.utils.XmlDataSource;
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);
}
}
/**
* 新增数据
* @param painting
*/
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 = " + id + "]的油画不存在");
}
return p;
}
public void update(Painting newPainting,int isPreviewModified) {
Painting painting = paintingDao.findById(newPainting.getId());
painting.setCategory(newPainting.getCategory());
painting.setDescription(newPainting.getDescription());
painting.setPname(newPainting.getPname());
painting.setPrice(newPainting.getPrice());
if (isPreviewModified == 1) {//图片被更改了
painting.setPreview(newPainting.getPreview());
}
paintingDao.update(painting);
}
public void delete(Integer id) {
paintingDao.delete(id);
}
public static void main(String[] args) {
PaintingService paintingService = new PaintingService();
PageModel pageModel = paintingService.pagination(2, 6);
// System.out.println(pageModel.getPageData());
List<Painting> paintingList = pageModel.getPageData();
for (Painting painting : paintingList) {
System.out.println(painting.getPname());
}
System.out.println(pageModel.getPageStartRow() + ":" + pageModel.getPageEndRow());
}
}
//PaintingDao
package com.imooc.mgallery.dao;
/**
* 油画数据访问对象
* 获取原始数据 对其进行分页处理
* Dao负责与底层数据进行交互
* @author zxy
*
*/
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) {
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> list = XmlDataSource.getRawData();
List<Painting> categoryList = new ArrayList<Painting>();
for (Painting painting : list) {
if (painting.getCategory() == category) {
categoryList.add(painting);
}
}
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 p = null;
for (Painting painting : data) {
if (painting.getId() == id) {
p = painting;
break;
}
}
return p;
}
public void update(Painting painting) {
XmlDataSource.update(painting);
}
public void delete(Integer id) {
XmlDataSource.delete(id);
}
}
//XmlDataSource
package com.imooc.mgallery.utils;
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 com.imooc.mgallery.entity.Painting;
/**
* 数据源类,用于将XML文件解析为Java对象
*
*
* @author zxy
*
*/
public class XmlDataSource {
//通过static关键字保证数据的全局唯一
private static List<Painting> data = new ArrayList();
private static String dataFile;
static {
//得到painting.xml文件完整物理路径
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 document = reader.read(dataFile);
//Xpath得到XML节点集合
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");
// System.out.println(id + ":" + pname);
Painting painting = new Painting();
painting.setId(Integer.parseInt(id));
painting.setPname(pname);
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) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取所有油画Painting 对象
* @return
*/
public static List<Painting> getRawData() {
return data;
}
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");
//3.创建painting节点的子节点
p.addAttribute("id", String.valueOf(data.size()));
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) {
// 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();//保证内存与文件的数据一致
}
}
/**
* 更新对应id的XML油画数据
* @param painting
*/
public static void update(Painting painting) {
SAXReader reader = new SAXReader();
Writer writer = null;
try {
Document document = reader.read(dataFile);
//节点路径[@属性名=属性值]
// /root/painting[@id=x]
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());
p.selectSingleNode("preview").setText(painting.getPreview());
writer = new OutputStreamWriter(new FileOutputStream(dataFile),"utf-8");
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 delete(Integer id) {
SAXReader reader = new SAXReader();
Writer writer = null;
try {
Document document = reader.read(dataFile);
List<Node> nodes = document.selectNodes("/root/painting[@id=" + id +"]");
if (nodes.size() == 0) {
throw new RuntimeException("id = " + id + "编号油画不存在");
}
Element p = (Element)nodes.get(0);
p.getParent().remove(p);
writer = new OutputStreamWriter(new FileOutputStream(dataFile),"utf-8");
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 main(String []args) {
Painting painting = new Painting();
painting.setPname("Jhon snow");
painting.setCategory(1);
painting.setPrice(5000);
painting.setPreview("/upload/Jhon snow.jpg");
painting.setDescription("snow");
XmlDataSource.append(painting);
}
}
正在回答 回答被采纳积分+1
- 参与学习 人
- 提交作业 9410 份
- 解答问题 16556 个
综合就业常年第一,编程排行常年霸榜,无需脱产即可学习,北上广深月薪过万 无论你是未就业的学生还是想转行的在职人员,不需要基础,只要你有梦想,想高薪
了解课程
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星