spring+mybatis(登录示例)

mybatis回顾:

  • 实体类pojo
  • 全局配置文件mybatis.xml
  • 配置了数据源,mappers,针对事务的log4j日志,pojo类的简写
  • 数据访问层mapper中配置了事务方法,包括接口绑定技术
  • MybatisUtil解析mybatis配置文件,创建工厂,拿到session对象,使用ThreadLocal技术进行session对象在创建和关闭两个时刻的传递(范围是同一个线程内)
  • filter中openSessionView,filter过滤器过滤请求,当浏览器发送一个请求,过滤器调用MybatisUtil拿到Session,放行,响应时又经过过滤器,提交事务,有错误时完成回滚操作
  • serviceImpl中通过mybatis拿到session,如果接口绑定,getMapper拿到接口的对象,调用事务方法,拿到数据库的数据
  • servlet正常写

mybatis+spring过程

  • spring利用IoC简化了mybatis的过程
  • 同样是有实体pojo类
  • 需要配置web.xml来解析spring配置文件
  • spring+mybatis时 去掉了原先的mybatis配置文件,配置spring配置文件applicationContext.xml
  • applicationContext中配置了数据源(可以加属性配置文件),工厂,mapper扫描器三个bean,事务 管理器基于aop管理事务方法,代替了filter中的提交、回滚功能
  • mapper照旧
  • serviceImpl中注入Mapper(配置bean注入要设置get、set方法,注解注入更方便),业务方法调用注入Mapper中的事务方法return
  • servlet中init方法中拿到applicaitonContext对象,spring中所有东西都存在这里边,可以applicaitonContext拿到所有spring管理的对象,servlet中就是拿到Impl对象,其他照旧

jar包

在这里插入图片描述

web.xml(用于加载applicationContext.xml)

<?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_3_0.xsd" version="3.0">
</web-app>
  <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>

applicationContext.xml

  • dataSource就是原来连接数据库的部分
  • factory是工厂
  • 扫描器是扫描mapper包的,mapper类由spring创建(id为接口名小写)
  • serviceImpl由spring进行管理,在servlet中利用spring创建Impl对象,这样可以让spring来完成mapper的注入工作
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.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/login"></property>
        	<property name="username" value="root"></property>
        	<property name="password" value="wityy"></property>
        </bean>
        
        <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
        	<property name="dataSource" ref="dataSource"></property>
        	<property name="typeAliasesPackage" value="cn.wit.pojo"></property>
        </bean>
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        	<property name="sqlSessionFactory" ref="factory"></property>
        	<property name="basePackage" value="cn.wit.mapper"></property>
        </bean>
        
        <bean id="loginServiceImpl" class="cn.wit.serviceImpl.LoginServiceImpl">
        	<property name="usersMapper" ref="usersMapper"></property>
        </bean>

		 <!--事务管理器  -->
        <bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        	<property name="dataSource" ref="dataSource"></property>
        </bean>
        <tx:advice id="txAdvice" transaction-manager="txManager">
        	<tx:attributes>
        		<tx:method name="ins*"/>
        		<tx:method name="del*"/>
        		<tx:method name="upd*"/>
        		<tx:method name="*" read-only="true"/>
        	</tx:attributes>
        </tx:advice>
        <!--aop  -->
        <aop:config>
        	<aop:pointcut expression="execution(* cn.wit.serviceImpl.*.*(..))" id="mypoint"/>
        	<aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/>
        </aop:config>
 </beans>

pojo类

Users{int id,String userName,String passWord}

Mapper接口

public interface UsersMapper {
    
    
	Users selByUsers(Users users);
}

业务接口

public interface UsersMapper {
    
    
	@Select("select *from  users where username=#{userName} and password=#{passWord}")
	Users selByUsers(Users u);
}

业务Impl

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);
	}
	

}

servlet

@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    
	private LoginService ls;
	@Override
	public void init() throws ServletException {
    
    
		ApplicationContext ac = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
		ls = ac.getBean("loginServiceImpl",LoginServiceImpl.class);
	}
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    
    
		req.setCharacterEncoding("utf-8");
		resp.setContentType("text/html;charset=utf-8");
		Users u=new Users();
		u.setPassWord(req.getParameter("password"));
		u.setUserName(req.getParameter("username"));
		Users user = ls.login(u);
		if(user!=null){
    
    
			resp.sendRedirect("/login-3/main.jsp");
		}else{
    
    
			resp.sendRedirect("/login-3/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">
	<input type="password" name="password">
	<input type="submit" value="登录">
</form>
</body>
</html>

main.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>
<h1>欢迎回来</h1>
</body>
</html>

另外

Impl注解

需要添加注解扫描

 <context:component-scan base-package="cn.wit.serviceImpl"></context:component-scan>
  • Impl使用service+Resource注解,可以去掉Impl的bean标签配置,添加注解后默认按照byName方式进行注入,如果byName找不到,就按照byType
@Service
public class LoginServiceImpl implements LoginService{
    
    
	@Resource
	private UsersMapper usersMapper;
	@Override
	public Users login(Users u) {
    
    
		return usersMapper.selByUsers(u);
	}
	
}

添加属性配置文件

猜你喜欢

转载自blog.csdn.net/WA_MC/article/details/112603900