Spring前端样式bug
判定是否等于空
if (email=='')// 单引号即可
获取对应id的值
var email = document.getElementById("id").value;
var email = $("#id").val();
按钮不可点击
// 不可点击
$("#id").attr("disabled",true);
// 更改背景颜色
$("#id").css("background",'#5FB878');
赋值
$("#id").val("发现错误");
$("#id").html("发现错误");
CSS样式定义
<style type="text/css">
input#id
{
border:2px solid #f1f1f1;
outline:none;
line-height: 16px;
font-family: "微软雅黑", "宋体", Arial;
font-size: 16px;
width: 130px;
height: 30px;
padding: 6px 10px;
margin-top:20px;
transition:border 0.2s ease-in 0s;
}
</style>
普通Ajax请求
$.ajax({
url:"/czp/sendEmail/"+email,
contentType:"application/json;charset=UTF-8",
dataType:"json",
async:true,
type:"GET",
success:function () {
// 解析json
},
error:function () {
console.log("data------->出错啦");
}
});
Ajax提交form表单
$.ajax({
url: "${basePath}lsx/register",
type: 'POST',
cache: false, //不缓存
data: new FormData($('#loginForm')[0]), //将整个表单的数据封装到FormData对象中
processData: false, //传输的数据是文件
contentType: false, //false代表文件上传
dataType: "json",
success:function (data) {
}
});
绑定点击事件
$("#id").click(function () {
}
Ajax后端数据处理
- 返回json化字符串
<!-- fastjson阿里巴巴jSON处理器 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.13</version>
</dependency>
// 代码部分
JSONObject jsonObject = new JSONObject();
jsonObject.fluentPut("msg","验证码错误");
jsonObject.fluentPut("code",-1);
return jsonObject.toJSONString();
邮箱验证
// 1、生成6位数字验证码code
String code = (int)((Math.random()*9+1)*100000)+"";
// 2、开始调用邮件发送业务
SendEmail1.sendemail(email,code);
// 3、存到Redis缓存中(设置5分钟有效期)
template.opsForValue().set(email,code,5, TimeUnit.MINUTES);
// 4、json返回,因为前端是json,防止报错
jsonObject.fluentPut("code",1);
return jsonObject.toJSONString();
- 邮箱发送验证码方法
public static void sendemail(String receiveEmailAccount, String code) throws IOException, MessagingException {
//3、进入要发邮件的邮箱,打开三方协议POP3/SMPT/IMAP
//4、设置授权码,该密码为代码中使用的密码,与登录密码不一样
//0.1 设置基本参数
Properties props = new Properties();
// 设置主机
props.setProperty("mail.host", "smtp.qq.com");
// 确定使用权限验证
props.setProperty("mail.smtp.auth", "true");
//0.2 确定账号与密码
Authenticator authenticator = new Authenticator() {
@Override
protected PasswordAuthentication getPasswordAuthentication() {
//return new PasswordAuthentication("设置将要登陆邮箱的账号(必须写上@后面的东西)", "设置授权码");
return new PasswordAuthentication("1518284345@qq.com", "teorcnjqzmrvhija");
}
};
//1获得连接
Session session = Session.getInstance(props, authenticator);
//2 编写消息
Message message = new MimeMessage(session);
// 2.1 发件人
//message.setFrom(new InternetAddress("设置发件人的邮箱","设置发件人的姓名,自己写"));
message.setFrom(new InternetAddress("1518284345@qq.com", "lm"));
// 2.2 收件人 , to:收件人 cc:抄送 bcc:暗送
message.setRecipient(RecipientType.TO, new InternetAddress(receiveEmailAccount));
//设置多个收件人地址
//message.addRecipient(RecipientType.TO,new InternetAddress("设置收件人的邮箱"));
// 2.3 主题
message.setSubject("唯才网注册用户验证码");
// 2.4 正文,直接html代码的
//message.setContent(sbd.toString(), "text/html;charset=UTF-8");
message.setContent(code, "text/html;charset=UTF-8");
//3发送消息
Transport.send(message);
}
页面刷新的同时,调用查询所有信息的方法
/**
* 跳到主页面
* @return 页面url地址
*/
@RequestMapping("/index.html")
public String Index(Model model){
// 调用首页职位信息查询方法
List<PositionPageBean> positionPageBeans = queryAllCompanyPosition();
model.addAttribute("positionPageBeans",positionPageBeans);
return "/czp/index";
}
/**
* 首页职位信息查询方法
*/
public List<PositionPageBean> queryAllCompanyPosition(){
// 1.查询所有posstion+company
List<PositionPageBean> positionPageBeans = companyPositionService.queryAllCompanyPosition();
for (PositionPageBean positionPageBean : positionPageBeans) {
// 2.查询对应的标签
List<WeicaiLable> weicaiLables = companyPositionService.queryLabels(positionPageBean.getCompanyUserId());
positionPageBean.setWeicaiLableList(weicaiLables);
}
return positionPageBeans;
}
- 前端取值
<c:forEach items="${positionPageBeans}" var="pageBeans" varStatus="pageBeanIndex">
<!--判断奇偶性,使用varStatus-->
<c:if test="${pageBeanIndex.count%2!='0'}">
<li class="clearfix">
</c:if>
<c:if test="${pageBeanIndex.count%2=='0'}">
<li class="odd clearfix">
</c:if>
<!--EL表达式取值-->
<span>${pageBeans.companyField}</span>
<!--对象中包含了List集合-->
<c:forEach items="${pageBeans.weicaiLableList}" var="labelList">
<li>${labelList.label}</li>
</c:forEach>
</c:forEach>
回到顶部滚动样式
<script>
var timer = null;
backtop.onclick = function(){
cancelAnimationFrame(timer);
timer = requestAnimationFrame(function fn(){
var oTop = document.body.scrollTop || document.documentElement.scrollTop;
if(oTop > 0){
scrollTo(0,oTop-50);
timer = requestAnimationFrame(fn);
}else{
cancelAnimationFrame(timer);
}
});
}
</script>
将scrollTo(x,y)中的y参数通过scrollTop值获取,每次减少50,直到减少到0,则动画完毕
A标签class移除
<a href="#" class="btn_choice_on" id="{$v[itemid]}"> </a>
$('.btn_choice_on').click(function(){
$(this).toggleClass(function(){
if($(this).hasClass('btn_choice_on')){
$(this).removeClass('btn_choice_on');
return 'btn_choice_up';
}else{
$(this).removeClass('btn_choice_up');
return 'btn_choice_on';
}
})
});
jquery 设置a标签不可用,不可点击
html源码:
<a href=“#” id=“gotoPage”>链接<a>
js源码:
$(“#gotoPage”).attr("disabled",true); //设置成灰色不可点击
$("#gotoPage").css("pointer-events","none"); //设置鼠标事件不可用
JS文件上传的文件名获取+form表单的提交判定
- let(局部变量),var(全局变量)
<script type="text/javascript">
function showInfo() {
// 获取上传文件的路径
let obj = document.getElementById("file").value;
//获取最后一个.的位置
let index= obj.lastIndexOf(".");
// 获取后缀
let ext = obj.substr(index+1);
//判断是否是图片
let flag = isAssetTypeAnImage(ext);
return flag;// 如果是false,form表单将不能提交
}
// 进行后缀判定
function isAssetTypeAnImage(ext) {
return ['png', 'jpg', 'jpeg', 'bmp'].indexOf(ext.toLowerCase()) !== -1;
}
</script>
<div style="text-align: center;">
<form onsubmit="return showInfo()" action="/upload" method="post" enctype="multipart/form-data">
上传excel文件
<input type="file" name="file" id="file">
<input type="submit" value="上传">
</form>
</div>
方法延时执行
setTimeout(function () {
$.getJSON("/user/sendMessage",{"username":username},function (data) {
$("#example-text-input").val(data.tel_code);
});
},2000);//2秒钟后执行ajax请求
thymeleaf前端for循环
<li th:each="num:${#numbers.sequence(beginPage,endPage)}">//num是下标 #numbersthymeleaf中的方法
<a class="active" href="#1" th:text="${num}">num</a>
</li>
thymeleaf前端herf参数拼接
th:href="@{/index(currPage=${num})}"
th:href="@{'/index?currPage='+${num}}"
前端鼠标悬浮事件禁用
style="cursor: not-allowed;opacity: 0.5"
cursor:光标 not-allowed禁止
opacity:不透明度50%
thymleaf绑定onclick
th:onclick="|changeStatus(${product.status},${product.id})|"
thymeleaf将超链接–>POST请求
超链接
<a class="btn btn-warning m-r-5" th:href="|javascript:void(0)|" th:οnclick="|doPost('/product/queryProduct',1,1)|"><i class="mdi mdi-block-helper">未上架商品</i></a>
doPost方法
function doPost(to, currPage,statusId) { // to:提交动作(action),p:参数
let myForm = document.createElement("form");
myForm.method = "post";
myForm.action = to;
let myInput = document.createElement("input");
myInput.setAttribute("name", "currPage"); // 为input对象设置name
myInput.setAttribute("value", currPage); // 为input对象设置value
myForm.appendChild(myInput);
myInput.setAttribute("name", "statusId"); // 为input对象设置name
myInput.setAttribute("value", statusId); // 为input对象设置value
myForm.appendChild(myInput);
document.body.appendChild(myForm);
myForm.submit();
document.body.removeChild(myForm); // 提交后移除创建的form
}
sql的升降序排列
按product_sales降序,其次product_price降序
select * from product WHERE product_status = 1 order by product_sales desc,product_price desc
按product_sales降序,其次product_price升序
select * from product WHERE product_status = 1 order by product_sales desc,product_price asc
按product_sales升序,其次product_price升序
select * from product WHERE product_status = 1 order by product_sales,product_price
sql字段除主键外的唯一设置
ALTER TABLE user ADD unique(user_username)
显示图片后端
//图片显示
@RequestMapping(path = {"/showPicture"})
public void showPicture(String path,HttpServletResponse response) throws IOException {
System.out.println("path------>"+path);
if (path==""){
System.out.println("图片你好坏");
return;
}
System.out.println("显示图片方法--------------->");
InputStream in =new FileInputStream(path);
OutputStream out = response.getOutputStream();
int len = 0;
byte[] b = new byte[1024];
while ((len=in.read(b))!=-1){
out.write(b,0,len);
}
out.flush();
out.close();
in.close();
// 刷新一下响应的缓存
response.flushBuffer();
}
前端点击事件更改name,ID,Value值
获取
var val=$(this).attr("id");
更改name值
$("#wer input").attr("name","123");
更改placeholder值
$("#input-search-text").attr("placeholder","请输入商品价格");
input输入框的值清除
$("#input-search-text").val("");//清空输入框的值
$("#input-search-text").css("border","");//边框无颜色
input边框无颜色
$("#input-search-text").css("border","");//边框无颜色
SpringSercurity授权
表达式 | 备注 |
---|---|
hasRole | 用户具备某个角色即可访问资源 |
hasAnyRole | 用户具备多个角色中的任意一个即可访问资源 |
hasAuthority | 类似于 hasRole |
hasAnyAuthority | 类似于 hasAnyRole |
permitAll | 统统允许访问 |
denyAll | 统统拒绝访问 |
isAnonymous | 判断是否匿名用户 |
isAuthenticated | 判断是否认证成功 |
isRememberMe | 判断是否通过记住我登录的 |
isFullyAuthenticated | 判断是否用户名/密码登录的 |
principle | 当前用户 |
authentication | 从 SecurityContext 中提取出来的用户对象 |
图片显示功能
@RequestMapping("/showPicture")//加载图片方法
public void showPicture(String path, HttpServletResponse response) throws IOException {
File file = new File("");
if (path==""){
System.out.println("图片你好坏");
return;
}
path = file.getCanonicalPath()+path;//项目路径+文件所在路径
System.out.println(path);
InputStream in =new FileInputStream(path);
OutputStream out = response.getOutputStream();
int len = 0;
byte[] b = new byte[1024];
while ((len=in.read(b))!=-1){
out.write(b,0,len);
}
out.flush();
out.close();
in.close();
// 刷新一下响应的缓存
response.flushBuffer();
}
Feign超时处理
#第一次调用超时处理
feign:
client:
config:
default:
connectTimeout: 10000 #毫秒
readTimeout: 10000
Java删除指定目录下所有空文件夹
package com.carter.test;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
/**
* 删除指定目录下的所有空文件夹
*
* @author zdw
*
*/
public class FileUtils
{
List<File> list = new ArrayList<File>();
// 得到某一目录下的所有文件夹
public List<File> visitAll(File root)
{
File[] dirs = root.listFiles();
if (dirs != null)
{
for (int i = 0; i < dirs.length; i++)
{
if (dirs[i].isDirectory())
{
System.out.println("name:" + dirs[i].getPath());
list.add(dirs[i]);
}
visitAll(dirs[i]);
}
}
return list;
}
/**
* 删除空的文件夹
* @param list
*/
public int removeNullFile(List<File> list)
{
int num = 0;//表示没有可删除文件夹
for (int i = 0; i < list.size(); i++)
{
File temp = list.get(i);
// 是目录且为空
if (temp.isDirectory() && temp.listFiles().length <= 0)
{
temp.delete();
num++;//本次有可以删除的空文件夹
}
}
return num;
}
/**
* @param args
*/
public static void main(String[] args)
{
FileUtils m = new FileUtils();
int deleteNum = 0;//可删除数目
do {
List<File> list = m.visitAll(new File("C:\\Users\\海角天涯S\\Desktop\\springcloud-shop\\新建文件夹"));
System.out.println("=================================================================================");
deleteNum = m.removeNullFile(list);
if (deleteNum==0){
System.out.println("删除完毕....");
}
}while (deleteNum!=0);
}
}
代码生成器依赖
步骤1:使用代码生成器快速开始
接口实现步骤2
RestController接口返回统一的数据格式
-
放入公共模块中
package com.carter.utils public interface ResultCode{ public static Integer SUCCESS = 20000;//成功 public static Integer ERROR = 20001;//失败 }
-
定义具体的返回格式类R
@Data//lombok注解
接口中使用
第一种方法:
return R.ok().data("currPage",currPage).data("productList",productList)
第二种方法:
Map map = new HashMap();
map.put("currPage",currPage);
map.put("productList",productList);
return R.ok().data(map);
多条件组合查询带分页
数据库创建、修改时间自动填充
@TableField(fill = FieldFill.INSERT)//创建时间的自动填充
@TableField(fill = FieldFill.INSERT_UPDATE)//修改时间的自动填充
前端过来不需要传递创建、修改时间了,也不要id
全局异常处理
- 创建统一异常处理器GlobalExceptionHandler.java
@ControllerAdvice
public class GlobalExceptionHandler{
//全局异常
@ExceptionHandler(Exception.class)//所有异常执行此方法
@ResponseBody//为了能够返回数据
public R error(Exception e){
e.printStackTrace();
return R.error().massage("执行了全局异常处理...");
}
//特定异常
@ExceptionHandler(ArithemticException.class)//所有异常执行此方法
@ResponseBody//为了能够返回数据
public R error(ArithemticException e){
e.printStackTrace();
return R.error().massage("执行了ArithemticException异常处理...");
}
}
先查找特定异常
VSCode的使用
<h1 style="color: rebeccapurple;">hello vsCode!</h1>
<script>
{
var a = "a";//全局变量
let b = "b";//局部变量
const FNAIL_STATIC = 3;//不可更改
}
alert(a);
alert(b); //Uncaught ReferenceError: b is not defined
</script>
<script>
//传统的数组写法
let x=1,y=2;
console.log(x,y);
let [i,j] = [10,20];
console.log(i,j);
</script>
<script>
let user = {"name":"lsx","age":18};//对象
let {name,age}=user;//es6对象赋值
console.log(name,age);//name市user中的值
</script>
<script>
const name = "lsx"
const age = 18
//传统的方式
const person = {name:name,age:age}
console.log(person)
//ES6方式
const peopel = {name,age}
console.log(peopel)
</script>
<script>
//传统的方法
const p1 ={
sayHi:function(){
console.log("p1,Hi~")
}
}
p1.sayHi()//方法调用
//es6方法
const p2 = {
sayHi(){
console.log("p2,Hi~")
}
}
p2.sayHi()//方法调用
</script>
thymeleaf/tomcat找不到资源路径
- thymeleaf模板和其他的都OK
- 可能是Tomcat无法加载路径
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<filtering>true</filtering>
<excludes>
<exclude>static/**/*</exclude>
</excludes>
</resource>
<resource>
<directory>src/main/resources</directory>
<filtering>false</filtering>
<includes>
<include>static/**/*</include>
</includes>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.xml</include>
</includes>
</resource>
</resources>
</build>