登录用户

93 阅读2分钟

登录用户

在session中绑定共享对象

//获取当前登录用户
req.getSession().setAttribute("loginUser", userBean);

获取当前登录对象

@RequestMapping("getLoginUser")
public UserBean getLoginUser(HttpServletRequest req) {
    UserBean userBean = (UserBean) req.getSession().getAttribute("loginUser");
    return userBean;
}

创建一个登录拦截器的类LoginInterceptor

实现接口HandlerInterceptor

重写preHandle()方法

request.getSession().getAttribute()得到登录用户

package com.project.interceptor;
​
import org.springframework.web.servlet.HandlerInterceptor;
​
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
​
/**
 * 登录拦截器
 */public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
//        得到登录用户
        Object obj=request.getSession().getAttribute("loginUser");
        if (obj==null){//没有登录,回到登录页面
            response.sendRedirect("/login.html?errorInfo=noland");
            return false;
        }
        return true;
    }
}

声明一个配置类WebConFig

重写方法addInterceptors(),注册拦截器,定义拦截范围

package com.project.config;
​
import com.project.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
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 addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new LoginInterceptor())//注册拦截器
                .addPathPatterns("/class/class.html")//定义拦截范围(受限资源)
                .addPathPatterns("/room/room.html")
                .addPathPatterns("/student/student.html")
                .addPathPatterns("/user/user.html")
                .addPathPatterns("/index.html");
    }
}

getQuery()获取跳转页面时的errorInfo错误信息

window.onload=function (){
    var info=getQuery("errorInfo");
    if (info=="noland" && info!=null){
        Dreamer.error("对不起,请先登录");
    }
}

添加上传图片操作

文件上传控制器

package com.project.controller;
​
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
​
import java.io.File;
import java.io.IOException;
​
/**
 * 文件上传控制器
 */
@RestController
public class UploadController {
    @RequestMapping("upload")
    public String upload(@RequestParam("uploadImg") MultipartFile mf) throws IOException {
        //得到上传文件的名称
        var fileName=mf.getOriginalFilename();
        //以时间毫秒数,重命名上传文件,防止因上传文件同名而导致的覆盖
        fileName=System.currentTimeMillis()+fileName.substring(fileName.lastIndexOf("."));
        //将上传文件的二进制数据写入指定文件
        mf.transferTo(new File("E:\program\javaPhaseTwo\week06\roomProject\src\main\resources\static\image\"+fileName));
​
        return fileName;
    }
​
}

声明一个配置类,实现WebMvcConfigurer接口,重写addResourceHandlers()方法

package com.project.config;
​
import com.project.interceptor.LoginInterceptor;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
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("/reFace/**")                                               .addResourceLocations("file:E:\program\javaPhaseTwo\week06
        \roomProject\src\main\resources\static\image\");
    }
​
}

在js里面上传文件

var formObj = new FormData;
formObj.append("uploadImg", $("fileTxt").files[0]);
​
let config = {
    headers: {'Content-Type': 'multipart/form-data'}
}
var uploadeFileName;
//向服务器上传文件,得到上传文件名
await axios.post("/upload", formObj, config).then(resp => {
    uploadeFileName = resp.data;
})

服务器的校验

导入依赖

</dependency>
    <dependency>
        <groupId>org.hibernate.validator</groupId>
        <artifactId>hibernate-validator</artifactId>
        <version>6.1.5.Final</version>
    </dependency>
    <dependency>
        <groupId>org.glassfish</groupId>
        <artifactId>javax.el</artifactId>
        <version>3.0.1-b11</version>
    </dependency>

添加用户的代码

@RequestMapping("add")
public String add(@Valid StudentBean studentBean,BindingResult br, Integer classId, Integer roomId) throws JsonProcessingException {
    if (br.hasErrors()){
        List<FieldError> errorList=br.getFieldErrors();
        ObjectMapper om=new ObjectMapper();
        String errorInfo=om.writeValueAsString(errorList);
        return errorInfo;
    }
    ClassBean classBean=new ClassBean();
    classBean.setId(classId);
    studentBean.setClassBean(classBean);
    RoomBean roomBean=new RoomBean();
    roomBean.setId(roomId);
    studentBean.setRoomBean(roomBean);
    service.add(studentBean);
    return "ok";
}