spring+mybatis (login example)

mybatis review:

  • Entity class pojo
  • Global configuration file mybatis.xml
  • Configured with data sources, mappers, log4j logs for transactions, abbreviations for pojo classes
  • Transaction methods are configured in the data access layer mapper, including interface binding technology
  • MybatisUtil parses the mybatis configuration file, creates a factory, gets the session object, and uses ThreadLocal technology to transfer the session object at the two moments of creation and closing (the scope is within the same thread)
  • OpenSessionView in the filter, filter filter filters the request, when the browser sends a request, the filter calls MybatisUtil to get the Session, let it go, and then pass the filter in response, submit the transaction, and complete the rollback operation when there is an error
  • In serviceImpl, the session is obtained through mybatis. If the interface is bound, getMapper obtains the object of the interface, calls the transaction method, and obtains the data of the database
  • servlet writes normally

mybatis+spring process

  • Spring uses IoC to simplify the process of mybatis
  • There are also entity pojo classes
  • Need to configure web.xml to parse spring configuration files
  • In spring+mybatis, the original mybatis configuration file is removed, and the spring configuration file applicationContext.xml is configured.
  • The applicationContext is configured with three beans: data source (attribute configuration files can be added), factory, and mapper scanner. The transaction manager is based on the aop management transaction method, instead of the submit and rollback functions in the filter.
  • mapper as usual
  • Mapper is injected into serviceImpl (get and set methods should be set to configure bean injection, annotation injection is more convenient), business method call is injected into the transaction method return in Mapper
  • The applicaitonContext object is obtained in the init method of the servlet. Everything in spring exists here. You can get all the objects managed by spring in applicaitonContext. The Impl object is obtained in the servlet, and the rest is the same.

jar包

Insert picture description here

web.xml (used to load 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 is the part that originally connected to the database
  • factory is a factory
  • The scanner scans the mapper package, and the mapper class is created by spring (id is the lowercase interface name)
  • The serviceImpl is managed by spring, and the Impl object is created by spring in the servlet, so that spring can complete the mapper injection work
<?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 type

Users{int id,String userName,String passWord}

Mapper interface

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

Business interface

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

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

}

view

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>

In addition

Impl annotation

Need to add annotation scan

 <context:component-scan base-package="cn.wit.serviceImpl"></context:component-scan>
  • Impl uses the service+Resource annotation, you can remove the bean tag configuration of Impl, and after adding the annotation, it will be injected according to the byName method by default. If the byName is not found, it will be injected according to the byType
@Service
public class LoginServiceImpl implements LoginService{
    
    
	@Resource
	private UsersMapper usersMapper;
	@Override
	public Users login(Users u) {
    
    
		return usersMapper.selByUsers(u);
	}
	
}

Add property profile

Guess you like

Origin blog.csdn.net/WA_MC/article/details/112603900