一. 要求:
学生在控制台输入用户名密码,如果用户账号密码正确则显示用户所属班级,如果登录失败则显示登录失败。
二. 显示效果如下:
三. 步骤
1.创建数据库:在MySQL中的spring数据库中创建一个名为student的表。
2.编写实体类:创建Student类,在该类中定义id、username、password和course属性,以及属性对应的getter/setter方法。
public class Student {
private Integer id;
private String username;
private String password;
private String course;
public Integer getId() {
return id;
}
public void setId(Integer 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;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
}
3.编写配置文件:创建配置文件applicationContext.xml,在该文件中配置id为dataSource的数据源Bean和id为jdbcTemplate的JDBC模板Bean,并将数据源注入到JDBC模板中。
4.编写Dao层方法:创建StudentDao接口,在StudentDao接口中声明查询所有用户信息的方法。
public interface StudentDao {
public List findAllStudent();
}
5.实现Dao层方法:创建StudentDaoImpl实现类,在StudentDaoImpl类中实现StudentDao接口中的findAllStudent()方法。
public class StudentDaoimgl implements StudentDao {
private JdbcTemplate jdbcTemplate;
public JdbcTemplate getJdbcTemplate() {
return jdbcTemplate;
}
public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
this.jdbcTemplate = jdbcTemplate;
}
public List findAllStudent() {
String sql = "select * from student";
RowMapper rowMapper = new BeanPropertyRowMapper(Student.class);
return this.jdbcTemplate.query(sql, rowMapper);
}
}
6.编写Controller层:创建StudentController类,用于实现用户登录操作。
public class StudentController {
public static void main(String[] args) {
Boolean aBoolean = false;
String course = null;
Scanner sa = new Scanner(System.in);
System.out.println("欢迎来到学生管理系统");
System.out.println("请输入用户:");
String username = sa.nextLine();
System.out.println("请输入" + username + "的密码:");
String password = sa.nextLine();
ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
StudentDao studentDao = (StudentDao) context.getBean("StudentDao");
List students = studentDao.findAllStudent();
for (Student student : students) {
if (verification(student.getUsername(), student.getPassword(), username, password) == true) {
aBoolean = true;
course = student.getCourse();
break;
}
;
}
if (aBoolean == true) {
System.out.println("用户登入成功!n" + username + "是" + course + "班的");
} else {
System.out.println("用户登入失败!");
}
}
public static Boolean verification(String Username, String Password, String username, String password) {
Boolean bBoolean = null;
if (Username.equals(username) && Password.equals(password)) {
bBoolean = true;
} else {
bBoolean = false;
}
return bBoolean;
}
}
四. 注意:
1.提前在pom.xml中配置好(spring-core,spring-context,spring-beans,spring-expression,spring-jdbc,spring-tx,commons-logging,mysql-connector-java)。
2.老版本数据库驱动"com.mysql.jdbc.Driver",新的驱动"com.mysql.cj.jdbc.Driver"。
五. 代码:
链接:https://pan.baidu.com/s/1yKZUC2_6p4jpR_F23q4v8Q
邀请码:mmmm



