springboot实现简单的登录注册

1.项目主要结构

springboot实现简单的登录注册_第1张图片

2.application.yml文件内容

server:
  port:8080
spring:
  profiles:
    active: prod //spring默认配置
  datasource:
    driver-class-name: com.mysql.jdbc.Driver
    url: jdbc:mysql://localhost:3306/order
    username: root
    password: 123

  resources:
    static-locations: classpath:/templates  #访问静态页面

3.login.html和register.html页面





    
    用户登录


用户名:
密码:
跳转

(2)regist.html





    
    用户注册


用户名:
密码:

3.Result和User实体类

(1)

public class Result {
    //返回信息
    private String msg;
    //数据是否正常请求
    private boolean success;
    //具体返回的数据
    private T detail;
    //... getter and setter

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public boolean isSuccess() {
        return success;
    }

    public void setSuccess(boolean success) {
        this.success = success;
    }

    public T getDetail() {
        return detail;
    }

    public void setDetail(T detail) {
        this.detail = detail;
    }
}

(2)

public class User {
    private Long id;
    private String username;
    private String password;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }
}

4.LoginHandlerInterceptor

@Controller
@Component
public class LoginHandlerInterceptor implements HandlerInterceptor {
    //目标方法执行之前
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        Object user = request.getSession().getAttribute("loginUser");
        if (user == null) {
            //未登陆,返回登陆页面
            request.setAttribute("msg", "没有权限请先登陆");
            request.getRequestDispatcher("/login.html").forward(request, response);
            return false;
        } else {
            //已登陆,放行请求
            return true;
        }

    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }
}

5.MyMvcConfig

@Configuration
public class MyMvcConfig extends WebMvcConfigurerAdapter {

    @Autowired
    LoginHandlerInterceptor loginHandlerInterceptor;
    @Override
    public void addViewControllers(ViewControllerRegistry registry) {
        // super.addViewControllers(registry);视图映射
        //浏览器发送 /atguigu 请求来到 success
        registry.addViewController("/atguigu").setViewName("success");
    }
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        //添加对用户是否登录的拦截器,并添加过滤项、排除项
        registry.addInterceptor(loginHandlerInterceptor).addPathPatterns("/**")
                .excludePathPatterns("/css/**","/js/**","/images/**")//排除样式、脚本、图片等资源文件
                .excludePathPatterns("/login.html")//排除登录页面
               .excludePathPatterns("/user/login");//排除验证码
//                .excludePathPatterns("/wechatplatformuser/loginRBAC");//排除用户点击登录按钮

    }

6.UserController

@Controller    //相当于@Controller+@RequestBody
//@RequestMapping("/user")
public class UserController {

    @Autowired
    private UserService userService;
    /**
     * 注册
     * @param user 参数封装
     * @return Result
     */
    @PostMapping("/user/regist")
    public String regist(User user, HttpServletRequest request, HttpServletResponse response){
        Result result =new Result();
        result = userService.regist(user);
        System.out.println(result.getMsg());
       // request.getRequestDispatcher("/emp/list.heml").forward(request,response);
        return "login";
    }
    @RequestMapping("/user/test")
    public String test(){
        return "index";
    }



    @RequestMapping(value = {"/","/index.html"})
    public String toLogin(){
        return "login";
    }
    /**
     * 登录
     * @param user 参数封装
     * @return Result
     */

    @PostMapping(value = "/user/login")
    public String login(User user, HttpSession session){
        Result result = new Result();
        System.out.println(user.getUsername());
        session.setAttribute("loginUser",user.getUsername());
        result=userService.login(user);
        return "/emp/success";
    }

7.UserMapper

@Repository
@Mapper
public interface UserMapper {

    /**
     * 查询用户名是否存在,若存在,不允许注册
     * 注解@Param(value) 若value与可变参数相同,注解可省略
     * 注解@Results  列名和字段名相同,注解可省略
     * @param username
     * @return
     */
    @Select(value = "select u.username,u.password from user u where u.username=#{username}")
    @Results
            ({@Result(property = "username",column = "username"),
                    @Result(property = "password",column = "password")})
    User findUserByName(@Param("username") String username);

    /**
     * 注册  插入一条user记录
     * @param user
     * @return
     */
    @Insert("insert into user values(#{id},#{username},#{password})")
    //加入该注解可以保存对象后,查看对象插入id
    @Options(useGeneratedKeys = true,keyProperty = "id",keyColumn = "id")
    void regist(User user);

    /**
     * 登录
     * @param user
     * @return
     */
    @Select("select u.id from user u where u.username = #{username} and password = #{password}")
    Long login(User user);
}

8.UserService

@Service
@Transactional(rollbackFor = RuntimeException.class)
public class UserService {

    @Autowired
    private UserMapper userMapper;
    /**
     * 注册
     * @param user 参数封装
     * @return Result
     */
    public Result regist(User user) {
        Result result = new Result();
        result.setSuccess(false);
        result.setDetail(null);
        try {
            User existUser = userMapper.findUserByName(user.getUsername());
            if(existUser != null){
                //如果用户名已存在
                result.setMsg("用户名已存在");

            }else{
                userMapper.regist(user);
                //System.out.println(user.getId());
                result.setMsg("注册成功");
                result.setSuccess(true);
                result.setDetail(user);
            }
        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
    /**
     * 登录
     * @param user 用户名和密码
     * @return Result
     */
    public Result login(User user) {
        Result result = new Result();
        result.setSuccess(false);
        result.setDetail(null);
        try {
            Long userId= userMapper.login(user);
            if(userId == null){
                result.setMsg("用户名或密码错误");
            }else{
                result.setMsg("登录成功");
                result.setSuccess(true);
                user.setId(userId);
                result.setDetail(user);
            }
        } catch (Exception e) {
            result.setMsg(e.getMessage());
            e.printStackTrace();
        }
        return result;
    }
}

 

你可能感兴趣的:(java,spring,boot)