Spring的登陆小项目

项目目的

  1. 练习AOP
  2. 感受service中业务明确,登录就是登录其他功交给AOP
  3. 体现扩展功能
    如果之前先写的只有登录,现在需求又添加功能,添加记录日志

注意点

  1. 使用AOP任何一种方式(3种中任选一种)
  2. 在用户需要进行登录时记录,谁要进行登录,把信息记录到Log文件中
    格式:xxx在哪年哪月那日几点几分几秒进行登录
  3. 在用户登录后记录使用是否登录成功
    格式:xxx登录xxx
  4. 切点:
    设计成service的方法

项目开始设计

1.设计数据库

create table users(
id int(10) primary key auto_increment,
username varchar(20) unique,
password varchar(20)
);

insert into users values(default,'张三','123');

2.搭建spring环境

  1. 导入jar包
  2. 配置web.xml
    ①需要配置监听器——管理spring容器
    监听器类是spring整合web的内容,
    那么在spring-web.jar中的web.context包下,有一个ContextLoaderListener类
    ②管理spring容器需要传递spring的配置文件
    参数名是固定的叫做——contextConfigLocation
    配置文件所在路径是——classpath:applicationContext.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee                       
	http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
	<context-param>
		<param-name>contextConfigLocation</param-name>
		<param-value>classpath:applicationContext.xml</param-value>
	</context-param>
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
</web-app>

3.编写spring配置文件applicationContext.xml

  1. 获取数据源(数据库连接的相关信息)
    连接数据库的包是spring-jdbc.jar中的datasource包下,有一个DriverManagerDataSource类
  2. 产生SqlSessinFactory对象
    id任意取名,class在整合的包mybatis-spring.jar中的batis.spring包下,有一个SqlSessionFactoryBean类
    目的是负责创建对象,给入数据库信息
    name是确定的dataSoure,ref引入上面数据源的id
  3. 配置一个扫描器
    扫描器是内部代码,不被引用,所以用class,不用写id属性
    class在整合的包mybatis-spring.jar中的batis.spring.mapper包下,有一个MapperScannerConfigurer类
    其中name是确定值basePackage,sqlSessionFactory
    value引用的是自己写的mapper包,ref是上面创建的SqlSessionFactory对象的id
<?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:aop="http://www.springframework.org/schema/aop"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd
                http://www.springframework.org/schema/aop
        http://www.springframework.org/schema/aop/spring-aop.xsd
       ">
    <!-- 数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
    	<property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
    	<property name="url" value="jdbc:mysql://localhost:3306/sum"></property>
    	<property name="username" value="root"></property>
    	<property name="password" value="root"></property>
    </bean>
    <!-- SqlSessinFactory对象 -->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- 扫描器 -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
    	<property name="basePackage" value="com.youdian.mapper"></property>
    	<property name="sqlSessionFactory" ref="factory"></property>
    </bean>

4.写实体类pojo

加入set()和get()方法

public class Users {
	private int id;
	private String username;
	private String password;
}

5.mapper层

  1. 新建接口
public interface UsersMapper {
	Users selByUsers(Users users);
}
  1. 该小项目用配置文件,不用注解(前面的文章有注解的)
    UsersMapper.xml
    ①把接口的完整全限定路径放到namespace中,遵循接口绑定原则
    ②id需要与方法名相同
    ③在该方法中,参数和返回值都是对象Users
<?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.youdian.mapper.UsersMapper">
	<select id="selByUsers" parameterType="users" resultType="users">
		select * from users where username=#{username} and password=#{password}
	</select>
</mapper>

注:用spring整合mybatis后,没有别名,是因为导入的整合的包mybatis-spring.jar中的batis.spring包下,
有一个SqlSessionFactoryBean类.它把整个mybatis配置文件封装好了
在该类中有一个方法叫typeAliasesPackage,把哪个包下的类起别名
进行设值注入,在applicationContext.xml中的SqlSessionFactory下加入property标签

 <!-- SqlSessinFactory对象 -->
    <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
    	<property name="dataSource" ref="dataSource"></property>
    	<property name="typeAliasesPackage" value="com.youdian.pojo"></property>
    </bean>

6.service层

接口

public interface UsersService {
	Users login(Users users);
}

实现类
需要设值注入一个UsersMapper,并生成get和set方法

public class UsersServiceImpl implements UsersService {
	private UsersMapper usersMapper;
	public UsersMapper getUsersMapper() {
		return usersMapper;
	}
	public void setUsersMapper(UsersMapper usersMapper) {
		this.usersMapper = usersMapper;
	}
	@Override
	public Users login(Users users) {
		return usersMapper.selByUsers(users);
	}

}

在applicationContext.xml文件中进行注入
ref引用的对象是service的实现类中的对象

    <!-- 注入 -->
    <bean id="usersService" class="com.youdian.service.impl.UsersServiceImpl">
    	<property name="usersMapper" ref="usersMapper"></property>
    </bean>
    

7.servlet层

添加init方法,作用是对UsersService对象进行注入
而代理和实现类都实现了该接口,把代理强转为实现类会报错

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
	private UsersService usersService;
	@Override
	public void init() throws ServletException {
		WebApplicationContext wac = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());
		usersService = wac.getBean("usersService",UsersServiceImpl.class);
	}
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		req.setCharacterEncoding("utf-8");
		Users users = new Users();
		users.setUsername(req.getParameter("username"));
		users.setPassword(req.getParameter("password"));
		Users user = usersService.login(users);
		if(user!=null){
			resp.sendRedirect("main.jsp");
		}else{
			resp.sendRedirect("login.jsp");
		}
	}
}

login.jsp:

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<form action="login" method="post">
用户名:<input type="text" name="username"/><br/>
密码:<Input type="password" name="password"/><br/>
<input type="submit" value="登录"/>
</form>
</body>
</html>

AOP和Filter的不同

AOP——拦截的是类的方法
Filter——拦截请求

8.对login方法形成切面

applicationContext.xml中引入xmlns:aop

 <!-- aop -->
    
    <aop:config>
    	<aop:pointcut expression="execution(* com.youdian.service.impl.UsersServiceImpl.login(..))" id="mypoint"/>
    	<aop:advisor advice-ref="mybefore" pointcut-ref="mypoint"/>
    	<aop:advisor advice-ref="myafter" pointcut-ref="mypoint"/>
    </aop:config>

advice-ref需要有前置通知和后置通知,新建一个advice包:
需要导入aopalliance和aspectjweaver.jar
需要导入log4j的jar包和配置文件

log4j.rootCategory=INFO, CONSOLE ,LOGFILE

log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%m %n

log4j.appender.LOGFILE=org.apache.log4j.FileAppender
log4j.appender.LOGFILE.File=D:/MY/place2/login2/my.log
log4j.appender.LOGFILE.Append=true
log4j.appender.LOGFILE.layout=org.apache.log4j.PatternLayout
log4j.appender.LOGFILE.layout.ConversionPattern=%m %n

public class MyBefore implements MethodBeforeAdvice {

	@Override
	public void before(Method arg0, Object[] arg1, Object arg2) throws Throwable {
		Users users = (Users) arg1[0];
		Logger logger = Logger.getLogger(MyBefore.class);
		logger.info(users.getUsername()+"在"+new Date().toLocaleString()+"进行登录");}

}
public class MyAfter implements AfterReturningAdvice{

	@Override
	public void afterReturning(Object arg0, Method arg1, Object[] arg2, Object arg3) throws Throwable {
		Logger logger = Logger.getLogger(MyAfter.class);
		Users users = (Users) arg2[0];
		if(arg0!=null){
			logger.info(users.getUsername()+"登录成功!");
		}else{
			logger.info(users.getUsername()+"登录失败!");
		}
	}

}

类写完后需要在配置文件中让通知生效
id是方法名小写(无所谓)

	<bean id="mybefore" class="com.youdian.advice.MyBefore"></bean>
    <bean id="myafter" class="com.youdian.advice.MyAfter"></bean>

注:默认使用的是JDK动态代理,需要手动转成cglib

	<aop:aspectj-autoproxy proxy-target-class="true"></aop:aspectj-autoproxy>
	<bean id="mybefore" class="com.youdian.advice.MyBefore"></bean>
    <bean id="myafter" class="com.youdian.advice.MyAfter"></bean>   
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值