Spring框架三层架构(daoservice和controller)注解注入 实现简易登录功能
Posted 小绵杨Yancy
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Spring框架三层架构(daoservice和controller)注解注入 实现简易登录功能相关的知识,希望对你有一定的参考价值。
三层架构
1、Dao层
全称为Data Access Object
,负责于数据库进行联络,完成增删查改的功能。提供接口给Service层。
2、Service层
调用Dao层提供的接口,业务处理,为Controller层提供接口。
3、Controller层
负责请求转发,接收用户传来的参数,通过调用Service层提供的接口,实现将数据转发给Service层处理。接收Service的返回值,再转发给用户。
简易登录功能
需求:
通过Spring框架,实现与数据库连接,在控制台输入用户名和密码,对用户进行校验、登陆、验证,成功返回“success”,失败返回“error”。
项目整体目录结构
其中libs目录包含了spring框架所需要的jar依赖包和jdbc包
数据库信息
entity实体类User:
package com.yancy.entity;
public class User
private String userName;
private String passWord;
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;
Controller层代码
package com.yancy.controller;
import com.yancy.entity.User;
import com.yancy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
@Controller
public class UserController
@Autowired
UserService userService;
public String userLogin(User user)
Boolean result = userService.userLogin(user);
if(result)
return "success";
else
return "erro";
Srevice层代码
UserService接口
package com.yancy.service;
import com.yancy.entity.User;
public interface UserService
public boolean userLogin(User user);
UserService接口实现类 UserServiceImpl
package com.yancy.service.impl;
import com.yancy.dao.UserDao;
import com.yancy.entity.User;
import com.yancy.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
@Service
public class UserServiceImpl implements UserService
@Autowired
UserDao userDao;
@Override
public boolean userLogin(User user)
User sqlUser = userDao.userLogin(user);
if((sqlUser.getUserName().equals(user.getUserName())) && (sqlUser.getPassWord().equals( user.getPassWord()))) return true;
return false;
Dao层代码
UserDao接口:UserDao
package com.yancy.dao;
import com.yancy.entity.User;
public interface UserDao
public User userLogin(User user);
UserDao接口的实现类:UserDaoImpl
package com.yancy.dao.impl;
import com.yancy.dao.UserDao;
import com.yancy.entity.User;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.RowMapper;
import org.springframework.stereotype.Repository;
@Repository
public class UserDaoImpl implements UserDao
@Autowired
JdbcTemplate jdbcTemplate;
@Override
public User userLogin(User user)
String sql="select * from user where userName=?";
RowMapper<User> rowMapper=new BeanPropertyRowMapper(User.class);
User resUser= jdbcTemplate.queryForObject(sql,rowMapper,user.getUserName());
return resUser;
配置文件bean.xml(在src的目录下,不在com下)
<?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"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">
<!--编写数据库配置-->
<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
<property name="driverClassName" value="com.mysql.cj.jdbc.Driver "/>
<property name="url" value="jdbc:mysql://localhost:3306/students?serverTimezone=Asia/Shanghai"/>
<property name="username" value="root"/>
<property name="password" value="zy20011109"/>
</bean>
<!--编写jdbc模板-->
<bean class="org.springframework.jdbc.core.JdbcTemplate" id="jdbcTemplate">
<property name="dataSource" ref="dataSource"/>
</bean>
<!--扫描注解-->
<context:component-scan base-package="com.*"/>
</beans>
测试类Main
import com.yancy.controller.UserController;
import com.yancy.entity.User;
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.Scanner;
public class Main
public static void main(String[] args)
/* ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
JdbcTemplate jdbcTemplate = (JdbcTemplate) applicationContext.getBean("jdbcTemplate");
System.out.println(jdbcTemplate);*/
ApplicationContext applicationContext = new ClassPathXmlApplicationContext("bean.xml");
UserController userController = (UserController) applicationContext.getBean("userController");
User user = new User();
Scanner in = new Scanner(System.in);
System.out.printf("请输入用户名:");
user.setUserName(in.next());
System.out.printf("请输入密码:");
user.setPassWord(in.next());
System.out.println(userController.userLogin(user));
运行结果
运行Main类中主函数
输入数据库中存在的用户信息:
输入错误信息:
Spring第三课 Spring框架搭建MVC三层架构
概念
本文对Spring框架在项目的实际应用和搭建项目框架中的作用和应用的介绍。
1.搭建项目开发环境
本文连接的数据库是mydb,采用的表是account,银行账户信息的数据表,如果读者对该表的结构不太清楚,可查阅该文【MyBatis】第五课 银行账户管理系统网站开发
创建项目,将所需要的jar包导入lib文件夹中
按照MVC三层架构流程图创建controller层,service层,dao层以及util层,test层,分别对应于控制层,业务逻辑层,数据访问层,工具包和测试包等等。
对应的包名分别为:
com.account.controller , com.account.service, com.account.dao,
com.account.utils, com.account.test
2.创建每层对应的java类
在com.account.utils包中创建DBUtil类,用于采用JDBC连接mysql数据库,其代码如下:
package com.spring.utils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import java.sql.Connection;
import java.sql.DriverManager;
/**
* 连接数据库的工具类
*/
@Component(value = "db")
public class DBUtil
@Value("com.mysql.cj.jdbc.Driver")
private String driver;//连接数据库的驱动程序
@Value("jdbc:mysql://localhost:3306/mydb?useUnicode=true&characterEncoding=UTF-8")
private String url;//访问数据库的地址
@Value("root")
private String username;//登录数据库的用户名
@Value("admin")
private String password;//登录数据库的密码
public Connection connection=null;
@PostConstruct
public void init()
//加载驱动程序
try
Class.forName(driver);
//连接数据库
connection = DriverManager.getConnection(url, username, password);
catch (Exception e)
e.printStackTrace();
在com.account.dao中创建数据访问的接口和实现类:
IAccountDao.java
package com.spring.dao;
import java.util.List;
import java.util.Map;
/**
* 数据访问层接口
*/
public interface IAccountDao
//将数据库中多条数据查询出来
List<Map<String,Object>> getAll();
AccountDaoImp.java
package com.spring.dao;
import com.spring.utils.DBUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* 数据访问层实现类
*/
@Repository(value = "dao" )
public class AccountDaoImp implements IAccountDao
@Autowired
DBUtil db;
@Override
public List<Map<String, Object>> getAll()
List<Map<String,Object>> oList=new ArrayList<>();
//如果connection对象不为空,说明连接数据库成功
if (db.connection!=null)
//执行sql语句
String sql="select * from account";
try
PreparedStatement ps=db.connection.prepareStatement(sql);
ResultSet rs=ps.executeQuery();
while (rs.next())
int id=rs.getInt("id");
String password=rs.getString("password");
String name=rs.getString("name");
String personid=rs.getString("personid");
double balance=rs.getDouble("balance");
String opendate=rs.getString("opendate");
Map<String,Object> oMap=new HashMap<>();
oMap.put("id",id);
oMap.put("password",password);
oMap.put("name",name);
oMap.put("personid",personid);
oMap.put("balance",balance);
oMap.put("opendate",opendate);
oList.add(oMap);
catch (SQLException e)
e.printStackTrace();
return oList;
在 com.account.service中创建业务逻辑层的接口和实现类:
IAccountService.java
package com.spring.service;
import java.util.List;
import java.util.Map;
/**
* 业务逻辑层接口
*/
public interface IAccountService
List<Map<String,Object>> getAll();
AccountServiceImp.java
package com.spring.service;
import com.spring.dao.IAccountDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import java.util.List;
import java.util.Map;
/**
* 业务逻辑层接口实现类
*/
@Service(value = "service")
public class AccountServiceImp implements IAccountService
@Autowired
IAccountDao dao;
@Override
public List<Map<String, Object>> getAll()
return dao.getAll();
在com.account.controller中创建控制层的类:
AccountController.java
package com.spring.controller;
import com.spring.service.IAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import java.util.List;
import java.util.Map;
/**
* 控制层
*/
@Controller(value = "controller")
public class AccountController
@Autowired
IAccountService service;
public List<Map<String,Object>> All()
return service.getAll();
在com.account.utils包中创建Spring框架的主配置文件类:
SpringUtil.java
package com.spring.utils;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
@Configuration
@ComponentScan("com.spring")
public class SpringUtil
在com.account.test中创建测试类:
SpringTest.java
package com.spring.test;
import com.spring.controller.AccountController;
import com.spring.utils.SpringUtil;
import org.junit.Test;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class SpringTest
@Test
public void one()
//先加载Spring框架的主配置文件
ApplicationContext ac=new AnnotationConfigApplicationContext(SpringUtil.class);
AccountController controller = ac.getBean("controller", AccountController.class);
controller.All().forEach(map-> System.out.println(map));
总结
本文对Spring框架的实际的运行,希望对读者学习Spring框架有一定的帮助。
以上是关于Spring框架三层架构(daoservice和controller)注解注入 实现简易登录功能的主要内容,如果未能解决你的问题,请参考以下文章
SpringBoot(入门)三层架构ControllerServiceDao