上一篇搭建了基础的架子,这一篇搭建页面架子,主要偏前端一点, 手摸手上一篇地址,点击跳转
这篇不做账号登陆的验证,留到下一篇shiro
的时候一起做了,写到最后几章更像是在写前后端分离,
页面的跳转没有走controller
,因为thymeleaf
模版的原因,要不然每个页面都要写一个跳转的,
后面大部分都在前端解决跳转问题
第二章需要搭建的页面如下:
application.yml
文件设置映射路径为:templates
文件夹下
thymeleaf:
cache: false
encoding: utf-8
mode: HTML5
prefix: classpath:/templates/
suffix: .html
# 保证html能直接访问,不需要跳转controller,后期动态管理页面地址
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/
.layui-admin-bg{
background-color: #20222A !important ;
}
.layui-admin-border {
box-shadow: 0 1px 2px 0 rgb(0 0 0 / 5%);
}
.panel {
padding: 15px;
}
.panel-height {
height: 600px;
}
.card-header {
height: 60px;
}
.title {
text-align: center;
}
.layui-layer-title {
background-color: #001529 !important;
color:#fff !important;
}
.layui-layer-close1 {
color:#fff !important;
}
.layui-upload-img {
width: 92px;
height: 92px;
}
.avatar-uploader .el-upload {
border: 1px dashed #d9d9d9;
border-radius: 6px;
cursor: pointer;
position: relative;
overflow: hidden;
width: 98px;
height: 98px;
}
.avatar-uploader .el-upload:hover {
border-color: #409EFF;
}
.avatar-uploader-icon {
font-size: 28px;
color: #8c939d;
width: 178px;
height: 178px;
line-height: 178px;
text-align: center;
}
.avatar {
width: 98px;
height: 98px;
display: block;
}
.el-upload-list--text {
display: none;
}
.el-dialog {
margin-top: 20px !important;
}
.el-dialog > .el-dialog__header {
background-color: #001529 !important;
}
.el-dialog__title {
color: #fff !important;
}
.el-dialog__body {
padding-left: 0px !important;
}
.login-form {
width: 25%;
margin: auto;
margin-top: 120px;
}
.login-title {
text-align: center;
font-size: 30px;
}
.input-div,.input-div2{
display:flex;
border: 1px solid #eee ;
background-color: #fff;
height: 38px;
line-height: 38px;
padding: 0px 10px;
}
.layui-input {
border-style: none;
}
input::-webkit-input-placeholder {
color: #ccc;
}
input:-moz-placeholder {
color: #ccc;
}
input::-moz-placeholder {
color: #ccc;
}
input:-ms-input-placeholder {
color: #ccc;
}
.layui-form {
margin-top: 50px;
}
body {
background-color: #EFEFEF;
}
.layui-icon {
color: #D2D2D2;
}
DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>登陆title>
<link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
<script src="https://www.layuicdn.com/layui/layui.js">script>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js">script>
<script src="http://code.jquery.com/jquery-2.1.1.min.js">script>
<link rel="stylesheet" href="/css/login.css">
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js">script>
<script src="https://unpkg.com/[email protected]/dist/axios.min.js">script>
head>
<body>
<div id="app">
<div class="login-form">
<div class="login-title">后台管理系统div>
<div class="layui-form">
<div class="layui-form-item">
<div class="input-div">
<i class="layui-icon layui-icon-username">i>
<input type="text" name="username" v-model="user.username"
lay-verify="title" @focus="focusCss('input-div')"
@blur="blurCss('input-div')" autocomplete="off"
placeholder="用户名" class="layui-input" >
div>
div>
<div class="layui-form-item">
<div class="input-div2">
<i class="layui-icon layui-icon-password">i>
<input type="password" name="username" v-model="user.password"
lay-verify="title" @focus="focusCss('input-div2')"
@blur="blurCss('input-div2')" autocomplete="off"
placeholder="密码" class="layui-input" >
div>
div>
<div class="layui-form-item">
<button type="button" style="width: 100%;"
class="layui-btn" @click="login">登陆button>
div>
div>
div>
div>
<script>
var vm = new Vue({
el:"#app",
data:{
user:{
username:null,
password:null
}
},
methods:{
//登陆按钮设置了@click=“login”,点击就会调用此方法
login(){
let that = this;
if(vm.user.username == null || vm.user.username == ""){
this.$message.error("请填写用户名");
return;
}
if(vm.user.password == null || vm.user.password == ""){
this.$message.error("请填写密码");
return;
}
//post请求发送账号密码
axios({
url:"user/login",
method: "post",
headers:{
"Content-Type": "application/json"
},
data:JSON.stringify(vm.user)
}).then(res => {
console.log("返回结果",res.data);
})
},
// 聚焦和失焦事件
focusCss(name){
$("."+name).css("border"," 1px solid #D2D2D2 ");
},
blurCss(name){
$("."+name).css("border"," 1px solid #eee ");
}
}
})
script>
body>
html>
请求方式采用了axios
,如果后面要接触了前后端分离项目,可能就会了解到axios
controller
文件夹中编写登陆代码和页面跳转新建一个LoginController
类,跳转到login.html
是依靠yml
中设置thymeleaf
配置
跳转到templates/login.html
页面的
import com.github.pagehelper.util.StringUtil;
import com.macro.entity.UserEntity;
import com.macro.service.UserService;
import com.macro.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
public class LoginController {
@Autowired
private UserService userService;
@GetMapping("login")
public String login(){
//依靠thymeleaf的映射,跳转到templates/login.html
return "login";
}
@PostMapping("user/login")
@ResponseBody
public Result login(@RequestBody UserEntity user){
// 判断传过来是否为空
if(user == null || StringUtil.isEmpty(user.getUsername()) ||
StringUtil.isEmpty(user.getPassword())){
return Result.error("账号或者密码不能为空");
}
//通过用户名查询
UserEntity entity = userService.findByUserName(user.getUsername());
//为空则回到
if(entity == null){
return Result.error("账号不存在!");
}
if(!entity.getPassword().equals(user.getPassword())){
return Result.error("密码错误!");
}
return Result.success();
}
}
UserService
接口添加findByUserName
方法//findByUserName方法,通过用户名近些年刚擦黑讯
UserEntity findByUserName(String username);
UserServiceImpl
实现findByUserName
方法 @Autowired
private UserDao userDao;
@Override
public UserEntity findByUserName(String username) {
QueryWrapper<UserEntity> wrapper = new QueryWrapper<>();
wrapper.eq("username",username);
return userDao.selectOne(wrapper);
}
启动访问:http://127.0.0.1:8086/login
我数据库设置的账号为:macro
密码为:123456
登陆成功code:200
失败为code:400
,工具类Result
中默认设置的成功:200
失败为: 400
index.html
登陆算是做好了,开始弄index.html
默认展示main.html
,data中设置了./main.html
,代码里面一些 注解记得看一下,不能面面俱到,只能通过注解
描述一些关键的东西
index.html
doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>后台管理页面title>
<link rel="stylesheet" href="https://unpkg.com/[email protected]/dist/css/layui.css">
<script src="https://unpkg.com/[email protected]/dist/layui.js">script>
<link rel="stylesheet" type="text/css" href="css/layui-admin.css"/>
<script src="http://code.jquery.com/jquery-2.1.1.min.js">script>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js">script>
head>
<body>
<div id="rapp">
<div class="layui-layout-admin " >
<div class="layui-header layui-admin-border" style="background-color: #ffffff !important;">
<div class="layui-logo" style="background-color: #001529 !important;"><a href="" style="color:#fff">无术同学a>div>
<ul class="layui-nav layui-layout-left" style="line-height: 60px;">
<span class="layui-breadcrumb">
<a href="">设置a>
<a><cite>{
{val}}cite>a>
span>
ul>
<ul class="layui-nav layui-layout-right ">
<li class="layui-nav-item">
<a style="color:black"><img src="http://img.treebreezes.top/macro.jpg" class="layui-nav-img">无术同学a>
<dl class="layui-nav-child">
<dd><a href="info.html">基本资料a>dd>
<dd @click="logout"><a>退出a>dd>
dl>
li>
ul>
div>
<div class="layui-side layui-bg-black" style="background-color: #001529 !important;">
<div class="layui-side-scroll">
<ul class="layui-nav layui-nav-tree" lay-filter="hbkNavbar">
<li class="layui-nav-item" style="background-color: #001529 !important;">
<a href="javascript:;" > <i class="layui-icon layui-icon-set"> 设置i>a>
<dl class="layui-nav-child" >
<dd><a href="./sysUser.html">管理员管理a>dd>
dl>
li>
ul>
div>
div>
<div class="layui-body layui-bg-gray" id="container">
<iframe scrolling="yes"
frameborder="0"
style="width:100%;overflow:visible;background:#fff; z-index: 50;height: 760px;" :src="main">iframe>
div>
<div class="layui-footer">
<center>Springboot + redis + shiro 动态权限管理系统 <font color="red">无术同学font>center>
div>
div>
div>
<script>
var vm = new Vue({
el: '#rapp',
data: {
main:"./main.html",
val:""
},
methods:{
logout(){
//退出接口:访问的是 127.0.0.1/logout
window.location = "/logout"
}
},
update:function(){
console.log("###");
}
});
//iframe自适应
$(window).on('resize', function() {
var $content = $('.content');
$content.height($(this).height() - 154);
$content.find('iframe').each(function() {
$(this).height($content.height());
});
}).resize();
//这块是页面跳转的关键,动态目录时会换掉
$(document).ready(function(){
$("dd>a").click(function (e) {
e.preventDefault();
vm.val = $(this).text();
vm.main = $(this).attr("href")
});
});
script>
body>
html>
main.html
DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Titletitle>
head>
<body>
你好,我是无术同学!
body>
html>
LoginController
类添加logout
接口,可跳转到login.html
@GetMapping("logout")
public String logout(){
//退出跳到login.html页面
return "login";
}
login.html
that.$message
是element ui
的弹框,用来提示的
//请求user/login的方法改成
axios({
url:"user/login",
method: "post",
headers:{
"Content-Type": "application/json" },
data:JSON.stringify(vm.user)
}).then(res => {
//此处为新加代码
if(res.data.code == 200){
that.$message({
message:"登陆成功", type: 'success'});
window.location = "/"
}else {
that.$message.error(res.data.msg);
}
})
访问地址:http://127.0.0.1:8086/login
以上index.html
的配置便好了,可以加入一些模块了,比如管理员模块
sysUser.html
在templates
文件夹下新建sysUser.html
DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<link rel="stylesheet" type="text/css" href="css/layui-admin.css"/>
<link rel="stylesheet" href="https://www.layuicdn.com/layui/css/layui.css">
<link rel="stylesheet" type="text/css" href="css/layui-admin.css"/>
<script src="http://code.jquery.com/jquery-2.1.1.min.js">script>
<script src="https://cdn.bootcss.com/vue/2.5.16/vue.min.js">script>
<script src="https://unpkg.com/[email protected]/dist/axios.min.js">script>
<link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
<script src="https://unpkg.com/element-ui/lib/index.js">script>
<script src="common.js">script>
<style>
tbody > tr {
height: 50px;
}
style>
head>
<body >
<div id="app">
<div class="layui-bg-gray panel" >
<div class="layui-card panel-height">
<div class="layui-card-header card-header" >
<div class="layui-form-item" style="line-height: 60px;">
<div class="layui-inline">
<label class="layui-form-label">昵称 label>
<div class="layui-input-inline">
<input type="text" name="email" class="layui-input" v-model="param.niceName">
div>
div>
<div class="layui-inline">
<label class="layui-form-label">用户名:label>
<div class="layui-input-inline">
<input type="text" name="email" class="layui-input" v-model="param.username">
div>
div>
<div class="layui-inline">
<button type="button" class="layui-btn " @click="reload"><i class="layui-icon layui-icon-search">i>button>
div>
div>
div>
<div class="layui-card-body">
<button type="button" class="layui-btn" @click="add">新增button>
<button type="button" class="layui-btn layui-btn-normal" @click="update">修改button>
<button type="button" class="layui-btn layui-btn-danger" @click="del">删除button>
<table class="layui-hide" id="table">table>
div>
div>
div>
<el-dialog :title="title" :visible.sync="show" width="30%">
<div class="layui-form" lay-filter="sex">
<div class="layui-form-item">
<label class="layui-form-label">昵称label>
<div class="layui-input-inline">
<input type="text" name="title" required placeholder="请输入昵称" v-model="user.niceName" autocomplete="off" class="layui-input"/>
div>
div>
<div class="layui-form-item">
<label class="layui-form-label">账号label>
<div class="layui-input-inline">
<input type="text" name="title" required placeholder="请输入账号" v-model="user.username" autocomplete="off" class="layui-input"/>
div>
div>
<div class="layui-form-item">
<label class="layui-form-label">密码label>
<div class="layui-input-inline">
<input type="password" name="password" required placeholder="请输入密码" v-model="user.password" autocomplete="off" class="layui-input"/>
div>
div>
<div class="layui-form-item">
<label class="layui-form-label">性别 label>
<div class="layui-input-inline">
<el-select v-model="user.sex" placeholder="请选择">
<el-option value="0" key="0" label="男">el-option>
<el-option value="1" key="1" label="女">el-option>
el-select>
div>
div>
<div class="layui-form-item">
<label class="layui-form-label">头像 label>
<div class="layui-input-block">
<el-upload class="avatar-uploader" show-file-list="false" action="upload/img" :on-success="success">
<img v-if="user.avatar" :src="user.avatar" class="avatar">
el-upload>
div>
div>
div>
<div slot="footer" class="dialog-footer" >
<button type="button" class="layui-btn" @click="saveOrUpdate">确定button>
<button type="button" class="layui-btn layui-btn-primary" @click="cannel">取消button>
div>
el-dialog>
div>
<script src="https://www.layuicdn.com/layui/layui.js">script>
<script src="js/sysUser.js">script>
body>
html>
common.js
在static
文件夹下新建common.js
function ids(){
var arr =new Array();
var res = layui.table.checkStatus('table');
if(res.data!= null && res.data.length > 0){
for (let i = 0; i < res.data.length; i++) {
arr[i] = res.data[i].id;
}
}
return arr;
}
function alert(msg){
layer.msg(msg);
}
sysUser.js
在sysUser.html
下方有个引入sysUser.js
的配置,src
设置的为js/sysUser.js
js
前面没有添加/
,这是一个相对路径 ,
<script src="js/sysUser.js">script>
在static
下新建一个js
文件夹,然后再js
文件夹中新建sysUser.js
mounted
在初始化的时候会加载一次,类似$(function(){ })
templet
的写法是可以在Layui中看到答案的,d
相当于当前循环中的一条数据
var vm = new Vue({
el:"#app",
//初始化加载
mounted(){
layui.use('table', function(){
var table = layui.table;
table.render({
elem: '#table'
,cellMinWidth: 80
,url:'sysUser/list'
,cols: [[
{
type:'checkbox'}
,{
field:'id', title: 'id' }
,{
field:'niceName', title: '昵称' }
,{
field:'username', title: '用户名'}
,{
field:'sex', title: '性别',
templet: ' {
{d.sex == null?"未知":d.sex==0?"男":"女"}} '
}
,{
field: 'avatar', title:'头像',
templet: ' '
}
]]
,page: true
});
});
},
data:{
user:{
niceName:null,
username:null,
password:null,
sex:"",
avatar:""
},
show:false,
title:"新增用户",
param:{
niceName:"",
username:""
}
},
methods:{
//查询+重新加载数据
reload(){
layui.use('table', function () {
var table = layui.table;
table.reload('table', {
url: 'sysUser/list'
,where: vm.param
});
});
vm.show = false;
},
add(){
vm.show = true;
//初始化
vm.user = {
niceName:null,
username:null,
password:null,
sex:"0",
avatar:null
};
vm.title= "新增用户";
},
update(){
let data = ids();
if(data == null || data.length == 0 || data.length > 1){
alert("请选择一条数据!")
return;
}
vm.show = true;
vm.user = {
};
vm.info(data[0]);
vm.title= "修改用户";
},
del(){
let that = this;
let data = ids();
if(data == null || data.length == 0){
alert("请选择!")
return;
}
layer.open({
title: '删除'
,content: '是否删除数据',
btn:['确定','取消'],
yes: function(index, layero){
axios({
url:"sysUser/del",
method: "post",
headers:{
"Content-Type": "application/json"
},
data:JSON.stringify(data)
}).then(res =>{
if(res.data.code == 200){
that.$message({
message:"删除成功", type: 'success'});
vm.reload();
}else {
that.$message.error("删除失败");
}
});
layer.close(index)
}
});
},
//保存或者更新
saveOrUpdate(){
let state = vm.user.id == null|| vm.user.id == "";
let url = state ?"sysUser/add":"sysUser/update"
axios({
url:url,
method: "post",
headers:{
"Content-Type": "application/json"
},
data:JSON.stringify(vm.user)
}).then(res =>{
if(res.data.code == 200){
this.$message({
message: state?"添加成功":"修改成功", type: 'success'});
vm.reload();
}else{
this.$message.error(state?'新增失败':"修改失败");
}
});
},
cannel(){
vm.show = false;
},
//查询单条
info(id){
axios({
method:"get",
url: "sysUser/info/" + id
}).then(res =>{
if(res.data.code == 200){
vm.user = res.data.data;
vm.user.sex = vm.user.sex.toString();
}
})
},
success(res, file){
vm.user.avatar = res.data;
}
}
})
我默认在add
或者update
方法中都会去初始化数据为空
,这样重复操作数据就不会造成数据异常
JSON.stringify
这个是将对象转化成json数据
,好方便后端接收
add
和update
中有一个ids()
方法,这个是common.js
中的方法,用户获取table表单
的id值
,后面每个增删改查的页面都有有这个的影子,所有把这个东西抽取出来了,其实head头部
的那些引用也可以
抽取出来,更加的灵活一些
PageEntity
在macro
包下新建一个Vo
包
创建PageEntity
类
import lombok.Data;
//后面带查询的都会用到分页数据
@Data
public class PageEntity {
// 页数
private Integer page;
//每页数量
private Integer limit;
}
Vo
下新建UserParam
类将参数封装起来对以后的开发有好处,只需要改动UserParam
类,然后去xml
添加对应的sql
即可,
无需改动service
和dao
代码了,一个开发小技巧送给你
//继承PageEntity
@Data
public class UserParam extends PageEntity {
//昵称
private String niceName;
//账号
private String username;
}
sysUserController
除了findByParam
方法,其余的新增
、修改
、删除
都是mybatis plus
提供的
import com.macro.Vo.UserParam;
import com.macro.entity.UserEntity;
import com.macro.service.UserService;
import com.macro.utils.Result;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import java.util.Arrays;
@RestController
@RequestMapping("sysUser")
public class sysUserController {
@Autowired
private UserService userService;
@GetMapping("list")
public Result list(UserParam param){
Result result = userService.findByParam(param);
return result;
}
@PostMapping("add")
public Result add(@RequestBody UserEntity user){
//密码加密
boolean save = userService.save(user);
if(save){
return Result.success();
}
return Result.error("添加失败");
}
@GetMapping("info/{id}")
public Result info(@PathVariable("id") Integer id){
UserEntity userEntity = userService.getById(id);
return Result.success(userEntity);
}
@PostMapping("update")
public Result update(@RequestBody UserEntity user){
boolean type = userService.updateById(user);
return type ? Result.success() : Result.error("更新失败");
}
@PostMapping("del")
public Result del(@RequestBody String[] ids){
if(ids.length > 0){
boolean type = userService.removeByIds(Arrays.asList(ids));
return type ? Result.success() : Result.error("删除失败");
}
return Result.success();
}
}
UserService
新增 findByParam
Result findByParam(UserParam param);
UserServiceImpl
新增 findByParam
方法的实现PageHelper
是分页插件工具,舒舒服服写代码!Result.success报错是因为还没改,
后面写了改动
@Override
public Result findByParam(UserParam param) {
PageHelper.startPage(param.getPage(), param.getLimit());
List<UserEntity> list = userDao.findByParam(param);
PageInfo<UserEntity> pageInfo = new PageInfo<>(list);
return Result.success(0,pageInfo.getTotal(),list);
}
UserDao
新增findByParam
//传入param实体类参数
List<UserEntity> findByParam(@Param("param")UserParam param);
UserDao.xml
代码like
模糊查询,防注入
DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.macro.dao.UserDao">
<select id="findByParam" resultType="com.macro.entity.UserEntity">
select * from sys_user
where 1=1
<if test="param.niceName != null and param.niceName != ''">
and nice_name like CONCAT('%',#{param.niceName,jdbcType=VARCHAR},'%')
if>
<if test="param.username != null and param.username != ''">
and username like CONCAT('%',#{param.username,jdbcType=VARCHAR},'%')
if>
select>
mapper>
Result
类改动import lombok.Data;
@Data
public class Result {
private Integer code;
private String msg;
private Object data;
private Long count;
Result(Integer code,String msg,Object data,Long count){
this.code = code;
this.msg = msg;
this.data = data;
this.count = count;
}
public static Result success(Object data){
return new Result(200,"成功",data,null);
}
public static Result success(){
return new Result(200,"成功",null,null);
}
public static Result success(Integer code,Long count,Object data){
return new Result(code,"成功",data,count);
}
public static Result error(Integer code,String msg){
return new Result(code,msg,null,null);
}
public static Result error(String msg){
return new Result(400,msg,null,null);
}
}
启动之后点击管理员管理,出现的页面就是这样了,除了图片上传基本就没问题了
在sysUser.html
头像上传采用了elemen ui
的el-upload
上传控件,action
设置了图片上传的请求地址
sysUser.js
FileUploadUtil
import org.springframework.web.multipart.MultipartFile;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Properties;
public class FileUploadUtil {
public static String BasePath = "";
private static String LINUXPATH = "/classmate/upload/";
private static String MACPATH = "/Users/classmate/upload/";
private static String WINDOWSPATH = "C:/classmate/upload/";
//根目录
private static String ROOT = "upload/";
static {
initBasePath();
}
/**
* 系统初始化上传根目录
*/
public static void initBasePath() {
BasePath = getBasePath();
File BasePathFile = new File(BasePath);
if (!BasePathFile.exists()) {
BasePathFile.mkdirs();
}
}
/**
* 获取当前环境的路径
*/
public static String getBasePath() {
Properties prop = System.getProperties();
String os = prop.getProperty("os.name");
if (os != null && os.toLowerCase().indexOf("linux") > -1) {
return LINUXPATH;
} else if (os != null && os.toLowerCase().indexOf("mac") > -1) {
return MACPATH;
} else {
return WINDOWSPATH;
}
}
/**
*
* @param file 流
* @param folderName 文件夹名称, 如: C:/classmate/upload/ (folderName文件名)
* @return
*/
public static String uploadFile(MultipartFile file, String folderName){
FileOutputStream fot = null;
//获取上传到的路径地址
String path = getBasePath();
path = path + folderName;
//文件名称
String filePath = getFilePath(file,path);
File dest = new File(path + "/" + filePath);
try {
dest.createNewFile();//创建一个文件
fot = new FileOutputStream(dest);
byte[] bytes = file.getBytes();
fot.write(bytes);
//根目录: upload/ + 自定义目录: user/ + 文件名: xxxx.jpg
return ROOT + folderName + "/" +filePath;
} catch (IOException e) {
e.printStackTrace();
return null;
}finally {
if(fot != null){
try {
fot.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
/**
* @param path 文件夹名字
* @param file file文件
* @return
*/
private static String getFilePath(MultipartFile file, String path) {
//生成文件名称(防止重复)
long date = System.currentTimeMillis();
//检测是否创建
if (!new File(path).isDirectory()) {
new File(path).mkdirs();
}
//截取文件后缀 如:xxx.jpg xxx.png
String suffix = file.getOriginalFilename().substring(file.getOriginalFilename().indexOf("."));
//拼接新的文件名称
String name = date + suffix;
//生成路径加上名字
return name;
}
}
WebConfig
import com.macro.utils.FileUploadUtil;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;
@Configuration
public class WebConfig implements WebMvcConfigurer {
@Override
public void addResourceHandlers(ResourceHandlerRegistry registry) {
//设置访问路径为:127.0.0.1:8080/upload/**
//映射路径:FileUploadUtil.getBasePath() 获取的路径
registry.addResourceHandler("/upload/**").addResourceLocations("file:///" + FileUploadUtil.getBasePath());
}
}
UploadController
import com.macro.utils.FileUploadUtil;
import com.macro.utils.Result;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
/**
* 文件上传controller
*/
@RestController
@RequestMapping("upload")
public class UploadController {
//图片上传
@PostMapping("img")
public Result upload(MultipartFile file){
//user:文件加名称,图片或者文件会放在user文件夹
String imgPath = FileUploadUtil.uploadFile(file, "user");
return Result.success(imgPath);
}
}
文件上传只是保存了部分路径,如:upload/user/xxxx.png
无视项目名称的更改和端口的更改,直接可以访问
运行看一下效果,完全没问题
逻辑比较简单,就是代码量比较多,下面这张图大概的意思就是,请求/login
通过controller
跳转到login
,
只不过通过thymeleaf
的帮助,去寻找templates
文件夹下的login.html
文件,原本相加info.html
,
但是篇幅太长了,留到下一篇吧