美文网首页
Spring 分层注入--登陆例子

Spring 分层注入--登陆例子

作者: 两分与桥 | 来源:发表于2018-09-01 20:56 被阅读15次

Spring分层

系统分层(扩展)
表示层:数据展现和控制逻辑(请求分发)
业务层:业务逻辑的处理
持久层:数据访问

a.上一层通过接口调用下一层提供的服务。
    比如,业务层调用持久层提供的借口。
b.下一层发生改变,不影响上一层,方便代码的维护。

Spring分层写一个登陆验证的例子,所有的关系都是用依赖注入来写的,记得开启数据库啊

整个逻辑图


123.png

所有文件的存放位置



下面就是实现了





web.xml文件,使得tomcat可以启动并调用spring容器
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" version="2.5">
  <display-name>springmvc02</display-name>
  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>
        org.springframework.web.servlet.DispatcherServlet
    </servlet-class>
    <init-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:springmvc.xml</param-value>
    </init-param>
    <load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>
</web-app>

配置文件,数据库连接参数

jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost/test
jdbc.username=root
jdbc.password=root

initialSize=2
maxActive=2

springmvc.xml配置文件,除了spring配置外,还配置了连接池参数

<?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:beans="http://www.springframework.org/schema/beans" 
    xmlns:context="http://www.springframework.org/schema/context" 
    xmlns:jdbc="http://www.springframework.org/schema/jdbc"  
    xmlns:jee="http://www.springframework.org/schema/jee" 
    xmlns:jms="http://www.springframework.org/schema/jms"
    xmlns:lang="http://www.springframework.org/schema/lang"
    xmlns:mvc="http://www.springframework.org/schema/mvc"
    xmlns:tx="http://www.springframework.org/schema/tx"
    xmlns:util="http://www.springframework.org/schema/util"
    xsi:schemaLocation="
        http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
        http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-3.2.xsd
        http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc-3.2.xsd
        http://www.springframework.org/schema/jee http://www.springframework.org/schema/jee/spring-jee-3.2.xsd
        http://www.springframework.org/schema/jms http://www.springframework.org/schema/tx/spring-jms-3.2.xsd
        http://www.springframework.org/schema/lang http://www.springframework.org/schema/tx/spring-lang-3.2.xsd
        http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
        http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd
        http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-3.2.xsd">
    <!-- 配置组件扫描 -->
    <context:component-scan base-package="controller"/>
    <context:component-scan base-package="dao"/>
    <context:component-scan base-package="service"/>
    
    <!-- 配置mvc注解扫描 -->
    <mvc:annotation-driven/>
    
    <!-- 配置视图解析器 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
    
    <!-- 配置连接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
        destroy-method="close">
        <property name="driverClassName" value="#{config['jdbc.driver']}"/>
        <property name="url" value="#{config['jdbc.url']}"/>
        <property name="username" value="#{config['jdbc.username']}"/>
        <property name="password" value="#{config['jdbc.password']}"/>
    </bean>
    
    <util:properties id="config" location="classpath:db.properties">
    </util:properties>
</beans>

首先是一个最基本,简单的实体类,用来做数据接口,传递参数

package entity;

public class Admin {
    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;
    }
    @Override
    public String toString() {
        return "Admin [username=" + username + ", password=" + password + "]";
    }
}

定义持久层接口dao

package dao;
import entity.Admin;

 * 持久层接口
public interface AdminDAO {
    Admin findByAdminUsername(String username);
}

实现dao层接口,注入了在springmvc.xml文件中配置的数据库连接池,并查询用户名和密码,生成一个Admin对象,并返回。

package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import javax.annotation.Resource;
import javax.sql.DataSource;

import org.springframework.stereotype.Repository;
import entity.Admin;

@Repository("adminDAO")
public class AdminDAOJdbcImpl implements AdminDAO{

     * 注入连接池
    @Resource(name="dataSource")
    private DataSource ds;
    
    public Admin findByAdminUsername(String username) {
        Admin admin = null;
        Connection conn = null;
        try {
            conn = ds.getConnection();
            String sql = "select * from admin where username=?";
            PreparedStatement ps = conn.prepareStatement(sql);
            ps.setString(1, username);
            ResultSet result = ps.executeQuery();
            if(result.next()) {
                admin = new Admin();
                admin.setUsername(result.getString("username"));
                admin.setPassword(result.getString("password"));
            }
        } catch (Exception e) {
            //记录日志
            e.printStackTrace();
            //看异常能否恢复,能解决则解决,不能解决则提示用户
            throw new RuntimeException(e);
        } finally {
            if(conn != null) {
                try {
                    conn.close();
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
        }
        return admin;
    }
}

定义业务层接口service,

package service;
import entity.Admin;

 * 业务层接口
public interface LoginService {
    public Admin checkLogin(String username, String password);
}

实现业务层接口,注入Dao,并调用其检测登陆,该类被Controller控制器调用

package service;

import javax.annotation.Resource;
import org.springframework.stereotype.Service;

import dao.AdminDAO;
import entity.Admin;

@Service("loginService")
public class LoginServiceImpl implements LoginService{
    @Resource(name="adminDAO")
    private AdminDAO dao;
    
    public Admin checkLogin(String username, String password) { 
        Admin admin = dao.findByAdminUsername(username);
        if(admin == null) {
             * 账号不存在,抛出一个应用异常(用户操作引起的异常)
            throw new ApplicationException("账号不存在");
        }
        if(!admin.getPassword().equals(password)) {
             * 账号存在,密码错误
            throw new ApplicationException("密码错误");
        }
         * 登陆成功
        return admin;
    }
}

上面实现业务层service代码中抛出了一个应用异常ApplicationException,如下

package service;

 * 应用异常
public class ApplicationException extends RuntimeException {

    private static final long serialVersionUID = 1L;

    public ApplicationException() {
        
    }

    public ApplicationException(String message) {
        super(message);
    }
}

最后的是控制器了,调用业务层的service检测登陆,对登陆逻辑处理,验证账号和密码,错误给出提示文本显示在视图中,正确的话跳转到index,其他错误跳转到error页面
(jsp页面在下面)

package controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import entity.Admin;
import service.ApplicationException;
import service.LoginService;

@Controller
public class LoginController {
    
    @Resource(name="loginService")
    private LoginService service;
    
    @RequestMapping("/tologin.do")
    public String toLogin() {
        System.out.println("toLogin()");
        return "login";
    }
    
    @RequestMapping("/login.do")
    public String login(HttpServletRequest request) {
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        System.out.println("username = " + username + ", password = " + password);
        try {
            Admin admin = service.checkLogin(username, password);
            return "index";
        } catch (Exception e) {
            e.printStackTrace();
             * 应用异常,应采取明确提示用户
            if(e instanceof ApplicationException) {
                request.setAttribute("username", username);
                request.setAttribute("password", password);
                request.setAttribute("login_fail", e.getMessage());
                return "login";
            }

             * 系统异常,提示用户稍后再试
            return "error";
        }
    }
}

login.jsp文件,提供登陆页面,登陆异常有错误提示

<%@ page contentType="text/html" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登陆</title>
</head>
<body style="font-size:30px;">
    <form action="login.do" method="post">
        <p>账号:<input type="text" name="username" value="${username}"></p>
        <p>密码:<input type="password" name="password" value="${password}"/></p>
        <p><input type="submit" value="提交"/></p>
    </form>
    <p style="color:red;">${login_fail}</p>
</body>
</html>

登陆成功跳转页面

<%@ page contentType="text/html" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>登陆成功</title>
</head>
<body>
    <h2>登陆成功</h2>
</body>
</html>

错误跳转页面(跟成功页面差不多的)

<%@ page contentType="text/html" pageEncoding="utf-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>错误页面</title>
</head>
<body>
    <h2>错误页面</h2>
</body>
</html>

相关文章

网友评论

      本文标题:Spring 分层注入--登陆例子

      本文链接:https://www.haomeiwen.com/subject/agguwftx.html