1.创建项目
创建maven项目,如图勾选,点击next
2.填写项目名,项目名随意,点击next
3.如图勾选,点击finish
4.在main下建立src和resources两个directory
5.在Java下建立一个packge,取名为com.lc,在com.lc下建立四个packge,分别为bean,controller,dao,service.
bean:此包下存放实体设计类,如user
controller:此包中的类为前后端连接,执行前端的各种操作
dao:此包中的类与数据库挂钩
service:此包中的类为逻辑执行
6.编写实体user类,user包含三个属性,username,password,id,可以使用快捷键创建get,set方法(alt+insert)
代码如下:
public class User {
private int id;
private String username;
private String password;
public User(){
}
public User(String username, String password){
this.username=username;
this.password=password;
}
public int getId() {
return id;
}
public void setId(int 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;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
7.编写登录功能
7.1在dao中创建UserDao接口,并编写函数接口User findByUserName(String username);如图:
7.2在resources下建立directory,取名mapper,mapper下建立xml文件(注意:后缀名需要自己手动打上),如图:
xml文件中代码:
<?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.lc.dao.UserDao" >
<select id="findByUserName" parameterType="String" resultType="user">
select * from tb_user where username=#{
username}
</select>
</mapper>
其中namespace后为连接的类名,这样Dao中的接口就在此处进行实现
7.3在resources下建立三个文件,如图:
applapplicationContext.xml文件为连接数据库,配置扫描bean,dao包
代码如下:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context
http://www