SpringMVC实战--构建学生管理系统(12)
首页部分学生管理页面(添加头像(图像)功能)制作
(源代码见仓库:https://gitee.com/jianghao233/course)
修改代码:
修改:StudentManager.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title></title>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/common.css"/>
<link rel="stylesheet" type="text/css" href="${pageContext.request.contextPath}/static/css/admin-common.css"/>
<script src="${pageContext.request.contextPath}/static/js/jquery.js" type="text/javascript" charset="utf-8"></script>
<script src="${pageContext.request.contextPath}/static/js/admin-student.js" type="text/javascript" charset="utf-8"></script>
</head>
<body>
<div id="class-title">
学生列表
</div>
<div id="add-div">
<input type="button" id="add-button" value="添加" onclick="add()"/>
</div>
<table cellspacing="0" id="table">
<tr>
<th>学号</th>
<th>姓名</th>
<th>密码</th>
<th>班级</th>
<th>操作</th>
</tr>
<c:if test="${empty list }">
<tr>
<td colspan="5">当前没有数据</td>
</tr>
</c:if>
<c:if test="${!empty list }">
<c:forEach items="${list }" var="s" varStatus="l">
<tr>
<td id="stunum${l.count }">${s.stunum }</td>
<td id="stuname${l.count }">${s.stuname }</td>
<td id="password${l.count }">${s.password }</td>
<td id="classname${l.count }">${s.classname }</td>
<td>
<a href="javascript:void(0)" onclick="modify('${s.stuid}','${s.classid }','${l.count}')">编辑</a>
<a href="${pageContext.request.contextPath}/student/delete?stuid=${s.stuid}">删除</a>
</td>
</tr>
</c:forEach>
</c:if>
</table>
<div id="form-div">
<form id="form1" action="${pageContext.request.contextPath}/student/save" method="post" enctype="multipart/form-data"> //修改代码
<input type="hidden" name="stuid" id="stuid">
学号:<input type="text" name="stunum" id="stunum"/><br />
姓名:<input type="text" name="stuname" id="stuname"/><br />
密码:<input type="password" name="password" id="password"/><br />
头像:<input type="file" name="fileurl" id="fileurl"><br>
班级:<select name="classid" id="classid">
<c:forEach items="${classes }" var="c">
<option value="${c.classid }">${c.classname }</option>
</c:forEach>
</select>
<input type="submit" value="提交"/>
</form>
</div>
<script type="text/javascript">
$(function(){
$('#form-div').hide();
});
function add(){
$('#form-div').show();
$("#table").hide();
$('#add-div').hide();
$('#class-title').html("学生信息");
}
function modify(stuid,classid,count){
add();
var stunum = $('#stunum'+count).html();
var stuname = $('#stuname'+count).html();
var password = $('#password'+count).html();
var classname = $('#classname'+count).html();
$('#stuid').val(stuid);
$('#stunum').val(stunum);
$('#stuname').val(stuname);
$('#password').val(password);
var str = "<option value='"+classid+"'>"+classname+"</option>";
var old = $('#classid').html();
$('#classid').html(str+old)
$('#form1').attr('action','${pageContext.request.contextPath}/student/modify');
}
</script>
</body>
</html>
修改 courseAdd.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>课程添加</title>
</head>
<body>
<div id="form-div">
<form action="${pageContext.request.contextPath}/course/save" method="post" enctype="multipart/form-data"> //修改代码
<!-- 有文件上传必须将enctype设为multipart -->
课程名称:<input type="text" name="coursename"/><br />
课程学时:<input type="text" name="hour"/><br />
课程学分:<input type="text" name="score"/><br />
<input type="submit" value="提交" />
</form>
</div>
</body>
</html>
修改 StudentController.java
package com.neuedu.controller;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.neuedu.po.TbClass;
import com.neuedu.po.TbStudent;
import com.neuedu.service.ClassService;
import com.neuedu.service.StudentService;
import com.neuedu.vo.StudentVO;
import oracle.net.aso.s;
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private ClassService classService;
@Autowired
private StudentService studentService;
@RequestMapping({"/","/list"})
//查询所有学生信息
public String list(Model model) {
List<StudentVO> list = studentService.getList();
List<TbClass> classes = classService.getList();
model.addAttribute("list",list);
model.addAttribute("classes",classes);
return "admin/studentManager";
}
@RequestMapping("/save")
public String save(TbStudent tbStudent,@RequestParam("fileurl") MultipartFile multipartFile) { //修改代码
System.out.println(multipartFile); //测试代码
studentService.save(tbStudent);
return "redirect:/student/";
}
@RequestMapping("/modify")
public String modify(TbStudent tbStudent) {
studentService.update(tbStudent);
return "redirect:/student/";
}
@RequestMapping("/delete")
public String delete(Integer stuid) {
studentService.delete(stuid);
return "redirect:/student/";
}
}
修改 springmvc.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.2.xsd">
<!-- springmvc 只负责 controller层 -->
<context:component-scan base-package="com.neuedu.controller"></context:component-scan>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/views/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<mvc:annotation-driven></mvc:annotation-driven>
<!-- 映射静态资源 -->
<!-- 配置拦截器 -->
<mvc:interceptors>
<mvc:interceptor>
<!-- 配置拦截路径(所有路径) -->
<mvc:mapping path="/**"/>
<!-- 配置不拦截路径(不拦截static和login下的路径) -->
<mvc:exclude-mapping path="/static/**"/>
<mvc:exclude-mapping path="/login/**"/>
<bean id="check" class="com.neuedu.interceptor.CheckInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<mvc:resources location="/static/" mapping="/static/**"></mvc:resources>
<!-- url地址为static开头的,全部映射到 static文件夹下,里面存储静态页面的样式;
不用经过spring映射,因为spring映射会将外部网络引用的文件全部拦截 -->
<!-- 多部件文件上传解析器 --> //新增代码
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 上传文件的最大内存为5M -->
<property name="maxUploadSize" value="5000000"></property>
<!-- 上传文件的编码格式为utf-8 -->
<property name="defaultEncoding" value="utf-8"></property>
</bean> //新增代码
</beans>
输出:点击添加信息---输入添加信息--提交---信息成功输出到前台,控制台输出测试代码
但这只是对象传递成功,数据库并没有保存到图片信息,继续修改代码
修改 StudentController.java
package com.neuedu.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.neuedu.po.TbClass;
import com.neuedu.po.TbStudent;
import com.neuedu.service.ClassService;
import com.neuedu.service.StudentService;
import com.neuedu.vo.StudentVO;
import oracle.net.aso.s;
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private ClassService classService;
@Autowired
private StudentService studentService;
@RequestMapping({"/","/list"})
//查询所有学生信息
public String list(Model model) {
List<StudentVO> list = studentService.getList();
List<TbClass> classes = classService.getList();
model.addAttribute("list",list);
model.addAttribute("classes",classes);
return "admin/studentManager";
}
@RequestMapping("/save") //新增代码
public String save(TbStudent tbStudent,HttpServletRequest request,@RequestParam("fileurl") MultipartFile multipartFile) throws Exception {
String oldname = multipartFile.getOriginalFilename();
/*获取真实路径*/
String basePath = request.getRealPath("/static/upload");
System.out.println("basePath==========="+basePath);
/*创建 file 对象,以 basePath 作为目录,以 oldname 作为文件名,但这是虚拟的,只存在于内存中*/
File file = new File(basePath,oldname);
/*将上传来的图片写入到 file 中*/
multipartFile.transferTo(file); //新增代码
studentService.save(tbStudent);
return "redirect:/student/";
}
@RequestMapping("/modify")
public String modify(TbStudent tbStudent) {
studentService.update(tbStudent);
return "redirect:/student/";
}
@RequestMapping("/delete")
public String delete(Integer stuid) {
studentService.delete(stuid);
return "redirect:/student/";
}
}
输出:经过与上述步骤相同的提交后,图片被成功保存到真实路径之中,但数据库中还是没有图片信息
还存在一个问题,可能会有重名的图片导致之前已保存的图片被覆盖,解决这个问题,修改代码:
新建 UploadUtils.java
package com.neuedu.utils;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
public class UploadUtils {
/**
* 获取文件真实名称
* 由于浏览器的不同获取的名称可能为:c12312231abd:/upload/1.jpg或者1.jpg
* 最终获取的为 1.jpg
* @param name 上传上来的文件名称
* @return 真实名称
*/
public static String getRealName(String name){
//获取最后一个"/"
int index = name.lastIndexOf("\\");
return name.substring(index+1);
}
/**
* 获取随机名称
* @param realName 真实名称
* @return uuid 随机名称
*/
public static String getUUIDName(String realName){
//realname 可能是 1.jpg 也可能是 1
//获取后缀名
int index = realName.lastIndexOf(".");
if(index==-1){
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}else{
return UUID.randomUUID().toString().replace("-", "").toUpperCase()+realName.substring(index);
}
}
}
修改 StudentController.java
package com.neuedu.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.neuedu.po.TbClass;
import com.neuedu.po.TbStudent;
import com.neuedu.service.ClassService;
import com.neuedu.service.StudentService;
import com.neuedu.utils.UploadUtils;
import com.neuedu.vo.StudentVO;
import oracle.net.aso.s;
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private ClassService classService;
@Autowired
private StudentService studentService;
@RequestMapping({"/","/list"})
//查询所有学生信息
public String list(Model model) {
List<StudentVO> list = studentService.getList();
List<TbClass> classes = classService.getList();
model.addAttribute("list",list);
model.addAttribute("classes",classes);
return "admin/studentManager";
}
@RequestMapping("/save")
public String save(TbStudent tbStudent,HttpServletRequest request,@RequestParam("fileurl") MultipartFile multipartFile) throws Exception {
String oldname = multipartFile.getOriginalFilename();
/*为避免重名带来的图片覆盖问题,修改保存图片的名字 */ //新增代码
/*1.去掉文件名中的路径信息*/
String realName = UploadUtils.getRealName(oldname);
/*2.获取一个UUID的名字*/
String uuidName = UploadUtils.getUUIDName(realName);
System.out.println(uuidName);
//新增代码
/*获取真实路径*/
String basePath = request.getRealPath("/static/upload");
/*创建 file 对象,以 basePath 作为目录,以 uuidName 作为文件名,但这是虚拟的,只存在于内存中*/
File file = new File(basePath,uuidName); //修改代码
/*将上传来的图片写入到 file 虚拟路径中*/
multipartFile.transferTo(file);
studentService.save(tbStudent);
return "redirect:/student/";
}
@RequestMapping("/modify")
public String modify(TbStudent tbStudent) {
studentService.update(tbStudent);
return "redirect:/student/";
}
@RequestMapping("/delete")
public String delete(Integer stuid) {
studentService.delete(stuid);
return "redirect:/student/";
}
}
输出:继续新建一个 小E,头像使用和小D同文件名的图片,但在真实路径中,名称会被随机数代替,不会发生覆盖现象
但这样产生的问题是,查找图片会因为随机名称而导致十分困难,继续修改代码
修改 UploadUtils.java
package com.neuedu.utils;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import org.springframework.web.multipart.MultipartFile;
public class UploadUtils {
/**
* 获取文件真实名称
* 由于浏览器的不同获取的名称可能为:c12312231abd:/upload/1.jpg或者1.jpg
* 最终获取的为 1.jpg
* @param name 上传上来的文件名称
* @return 真实名称
*/
public static String getRealName(String name){
//获取最后一个"/"
int index = name.lastIndexOf("\\");
return name.substring(index+1);
}
/**
* 获取随机名称
* @param realName 真实名称
* @return uuid 随机名称
*/
public static String getUUIDName(String realName){
//realname 可能是 1.jpg 也可能是 1
//获取后缀名
int index = realName.lastIndexOf(".");
if(index==-1){
return UUID.randomUUID().toString().replace("-", "").toUpperCase();
}else{
return UUID.randomUUID().toString().replace("-", "").toUpperCase()+realName.substring(index);
}
}
/**
* 获取文件目录,可以获取256个随机目录 //新增代码
* @return 随机目录
*
*
*/
public static String getDir(){
String s="0123456789ABCDEF";
Random r = new Random();
return "/"+s.charAt(r.nextInt(16))+"/"+s.charAt(r.nextInt(16));
}
public static void main(String[] args) {
String realName = getRealName(s);
System.out.println(realName);
String uuidName = getUUIDName(realName);
System.out.println(uuidName);
String dir = getDir();
System.out.println(dir); //新增代码
}
}
修改 StudentController.java
package com.neuedu.controller;
import java.io.File;
import java.io.IOException;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.multipart.MultipartFile;
import com.neuedu.po.TbClass;
import com.neuedu.po.TbStudent;
import com.neuedu.service.ClassService;
import com.neuedu.service.StudentService;
import com.neuedu.utils.UploadUtils;
import com.neuedu.vo.StudentVO;
import oracle.net.aso.s;
@Controller
@RequestMapping("/student")
public class StudentController {
@Autowired
private ClassService classService;
@Autowired
private StudentService studentService;
@RequestMapping({"/","/list"})
//查询所有学生信息
public String list(Model model) {
List<StudentVO> list = studentService.getList();
List<TbClass> classes = classService.getList();
model.addAttribute("list",list);
model.addAttribute("classes",classes);
return "admin/studentManager";
}
@RequestMapping("/save")
public String save(TbStudent tbStudent,HttpServletRequest request,@RequestParam("fileurl") MultipartFile multipartFile) throws Exception {
String oldname = multipartFile.getOriginalFilename();
/*为避免重名带来的图片覆盖问题,修改保存图片的名字 */
/*1.去掉文件名中的路径信息*/
String realName = UploadUtils.getRealName(oldname);
/*2.获取一个UUID的名字*/
String uuidName = UploadUtils.getUUIDName(realName);
System.out.println(uuidName);
/*获取真实路径*/
String basePath = request.getRealPath("/static/upload");
/*获取目录*/
String dir = UploadUtils.getDir(); //新增代码
File filedir = new File(basePath + dir);
if(!filedir.exists()) {
filedir.mkdirs();
} //新增代码
/*创建 file 对象,以 basePath 作为目录,以 uuidName 作为文件名,但这是虚拟的,只存在于内存中*/
File file = new File(filedir,uuidName); //修改代码
/*将上传来的图片写入到 file 虚拟路径中*/
multipartFile.transferTo(file);
studentService.save(tbStudent);
return "redirect:/student/";
}
@RequestMapping("/modify")
public String modify(TbStudent tbStudent) {
studentService.update(tbStudent);
return "redirect:/student/";
}
@RequestMapping("/delete")
public String delete(Integer stuid) {
studentService.delete(stuid);
return "redirect:/student/";
}
}
输出:继续新建一个 小F,头像使用和小D同文件名的图片,但在真实路径中,名称会被随机数代替,不会发生覆盖现象 ,且存放在随机文件夹中