前情提要
上一篇搭建了基础的架子,这一篇搭建页面架子,主要偏前端一点, 手摸手上一篇地址,点击跳转 这篇不做账号登陆的验证,留到下一篇shiro 的时候一起做了,写到最后几章更像是在写前后端分离, 页面的跳转没有走controller ,因为thymeleaf 模版的原因,要不然每个页面都要写一个跳转的, 后面大部分都在前端解决跳转问题
第二章需要搭建的页面如下:
正文开始
新建以下文件和文件夹
修改application.yml 文件
设置映射路径为:templates 文件夹下
thymeleaf:
cache: false
encoding: utf-8
mode: HTML5
prefix: classpath:/templates/
suffix: .html
resources:
static-locations: classpath:/META-INF/resources/,classpath:/resources/,classpath:/static/,classpath:/public/,classpath:/templates/
详细图片
layui-admin.css
.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.css代码
.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;
}
login.html
<!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/axios@0.21.1/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:{
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;
}
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(){
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 方法
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
ifame的 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/layui@2.6.8/dist/css/layui.css">
<script src="https://unpkg.com/layui@2.6.8/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(){
window.location = "/logout"
}
},
update:function(){
console.log("###");
}
});
$(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>Title</title>
</head>
<body>
你好,我是无术同学!
</body>
</html>
LoginController 类添加logout 接口,可跳转到login.html
@GetMapping("logout")
public String logout(){
return "login";
}
修改login.html
that.$message 是element ui 的弹框,用来提示的
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/axios@0.21.1/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: '<div> <span>{{d.sex == null?"未知":d.sex==0?"男":"女"}}</span> </div>'
}
,{field: 'avatar', title:'头像',
templet: '<div> <img style="height: 30px" src="{{d.avatar}}" > </div>'
}
]]
,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 代码了,一个开发小技巧送给你
@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
List<UserEntity> findByParam(@Param("param")UserParam param);
UserDao.xml 代码
like 模糊查询,防注入
<?xml version="1.0" encoding="UTF-8" ?>
<!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;
}
}
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);
return ROOT + folderName + "/" +filePath;
} catch (IOException e) {
e.printStackTrace();
return null;
}finally {
if(fot != null){
try {
fot.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
private static String getFilePath(MultipartFile file, String path) {
long date = System.currentTimeMillis();
if (!new File(path).isDirectory()) {
new File(path).mkdirs();
}
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) {
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;
@RestController
@RequestMapping("upload")
public class UploadController {
@PostMapping("img")
public Result upload(MultipartFile file){
String imgPath = FileUploadUtil.uploadFile(file, "user");
return Result.success(imgPath);
}
}
文件上传
文件上传只是保存了部分路径,如:upload/user/xxxx.png 无视项目名称的更改和端口的更改,直接可以访问 运行看一下效果,完全没问题
总结
逻辑比较简单,就是代码量比较多,下面这张图大概的意思就是,请求/login 通过controller 跳转到login , 只不过通过thymeleaf 的帮助,去寻找templates 文件夹下的login.html 文件,原本相加info.html , 但是篇幅太长了,留到下一篇吧
源码
在公众号内发送后台 即可获取源码和数据库
|