spring boot+jpa 实现登录注册功能

spring boot+jpa实现登录注册功能

Controller层

IndexController

public class IndexController {

private User user = new User();

@RequestMapping("/register")
public String register(){
    return "register";
}

@RequestMapping("/login")
public String login(){
    String str = "";
    String userName = user.getUserName();
    if(userName!=null){
        str = "index";
    }else{
        str = "login";
    }
    return str;
}

}

LoginController
@Controller
@RequestMapping("/user")
public class LoginController {

@Autowired
private UserRepository userRepository;

private User user = new User();

@RequestMapping("/index")
public String login(HttpServletRequest request, HttpSession session){
    String userName = request.getParameter("userName");
    String pwd = request.getParameter("pwd");
    user = userRepository.findByUserNameAndPwd(userName,pwd);
    String str = "";
    if(user!=null){
        session.setAttribute("userLogin",user);
        str = "index";
    }else{
        str = "login";
    }
    return str;
}

}

RegisterController

@Controller
@RequestMapping(value="/user")
public class RegisterController {

@Autowired
private UserRepository userRepository;

private User user = new User();

@RequestMapping("/uregister")
public String register(HttpServletRequest request) {
    String userName= request.getParameter("userName");
    String pwd = request.getParameter("pwd");
    String repwd = request.getParameter("repwd");
    String str = "";
    if (pwd.equals(repwd)) {
        user = userRepository.findByUserName(userName);
        if (user == null) {
            User user = new User();
            user.setUserName(userName);
            user.setPwd(pwd);
            userRepository.save(user);
            str = "login";
        } else {
            str = "register";
        }
    }else{
        str = "register";
    }
    return str;
}

}

Repository层

public interface UserRepository extends JpaRepository<User,Long>{
/**
* 登录
/
@Query(“select s from User s where s.userName = ?1 and s.pwd = ?2”)
public User findByUserNameAndPwd(String userName,String pwd);
/
*
* 注册
*/
@Query(“select s from User s where s.userName = ?1”)
public User findByUserName(String userName);

}

Entity

@Entity
public class User {
@Id
@GeneratedValue(strategy = GenerationType.AUTO)
private Long id;
private String userName;
private String pwd;

public User(){

}
public User(String userName, String pwd) {
    this.userName = userName;
    this.pwd = pwd;
}

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 getPwd() {
    return pwd;
}

public void setPwd(String pwd) {
    this.pwd = pwd;
}

}

前端代码:应该写在templates下

index.html
在描述
login.html
在这里插入图片描述
register.html
在这里插入图片描述
需要配置,
在这里插入图片描述

©️2020 CSDN 皮肤主题: 大白 设计师:CSDN官方博客 返回首页