Login authorization authentication (2) (mybatis+spring)

mybatis+spring environment construction

web.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">
  <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

A transaction manager is added inside, and if the transaction goes wrong, operations such as rollback are performed (this method is integrated by spring, filters can be used to manage transactions in mybatis, and there are interceptors in springmvc that have similar functions)

<?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"
     xmlns:context="http://www.springframework.org/schema/context"
     xmlns:tx="http://www.springframework.org/schema/tx"
    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
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd
         http://www.springframework.org/schema/tx
        http://www.springframework.org/schema/tx/spring-tx.xsd" default-autowire="byName">
		       
		       
		 <!--Impl包注解扫描  -->      
        <context:component-scan base-package="cn.wit.serviceImpl"></context:component-scan>
        
        
       <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/wit"></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">
        <!--扫描mapper包  -->
        	<property name="basePackage" value="cn.wit.mapper" ></property>
        	<property name="sqlSessionFactoryBeanName" value="factory"></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="sel*"/>
        		<tx:method name="upd*"/>
        	</tx:attributes>
        </tx:advice>
        
        <aop:config>
        	<aop:pointcut expression="execution(* cn.wit.serviceImpl.*.*(..))" id="mypoint"/>
        	<aop:advisor advice-ref="txAdvice" pointcut-ref="mypoint"/>
        </aop:config>
        
        
        <aop:aspectj-autoproxy  proxy-target-class="true"/>
        
</beans>  

Database Design

Use the rbac idea to design the database, that is, user-role-function. The car table below is the function. Here, users and roles adopt a one-to-one design. In addition to the id login name and password, there is a foreign key rid in the users table (the user's corresponding Role id), the role is unique and does not directly relate to other tables. The role id and the role name name, the car has its own attributes (id name price slogan), role_car associates the car with the role, and the id rid cid
Insert picture description here
uses the above This kind of design, when you need to get all the cars of the logged-in user, query the role_car table through the rid after logging in to find the corresponding car, and then combine the role_car and car tables to get all the cars of the user data

mapper transaction

Login authentication transaction (solved directly with annotations)

package cn.wit.mapper;

import org.apache.ibatis.annotations.Select;

import cn.wit.pojo.Users;

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

Authorized transaction (use mapper.xml file needs to import dtd)

package cn.wit.mapper;

import java.util.List;

import cn.wit.pojo.Car;
import cn.wit.pojo.Users;

public interface CarMapper {
    
    
	List<Car> selCar(Users 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="cn.wit.mapper.CarMapper">
  	<select id="selCar" parameterType="users" resultType="car">
  		select c.*,rc.rid from role_car rc
  		join car c on rc.cid=c.id 
  		where rid=#{
    
    rid}
  	</select>
  </mapper>

Service

Inject mapper through Resource annotation

package cn.wit.serviceImpl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.wit.mapper.CarMapper;
import cn.wit.mapper.UsersMapper;
import cn.wit.pojo.Car;
import cn.wit.pojo.Users;
import cn.wit.service.LoginService;

@Service
public class LoginServiceImpl implements LoginService{
    
    
	
	@Resource
	UsersMapper usersMapper;
	@Resource
	CarMapper carMapper;
	
	@Override
	public Users login(Users users) {
    
    
		return usersMapper.selByUsers(users);
	}

	@Override
	public List<Car> getCars(int rid) {
    
    
		return carMapper.selCars(rid);
	}
	
}

Servlet

package cn.wit.servlet;

import java.io.IOException;

import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import cn.wit.pojo.Car;
import cn.wit.pojo.Users;
import cn.wit.service.LoginService;
import cn.wit.serviceImpl.LoginServiceImpl;

/**
 * Servlet implementation class LoginServlet
 */
@WebServlet("/login")
public class LoginServlet extends HttpServlet {
    
    
	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");
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		Users users=new Users(username,password);
		Users login = ls.login(users);
		if(login!=null){
    
    
			List<Car> cars = ls.getCars(login.getRid());
			System.out.println(cars);
			HttpSession session = req.getSession();
			session.setAttribute("cars", cars);
			resp.sendRedirect("/car3/main.jsp");
		}else{
    
    
			resp.sendRedirect("/car3/login.jsp?error=yes");
		}
		
		
		
		
	}

}

view

Login 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>
<script type="text/javascript">
	var errori ='<%=request.getParameter("error")%>';
	if(errori=='yes'){
     
     
	 alert("账号或密码错误!");
	}
</script>
<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="text" name="password"> <br>
	<input type="submit" value="登陆">
</form>
</body>

</html>

Homepage main.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>
<table border="1px">
	<tr>
		<th>名字</th>
		<th>价格</th>
		<th>宣传语</th>
	</tr>
	<c:forEach items="${cars}" var="car">
		<tr>
			<td>${car.name }</td>
			<td>${car.price }</td>
			<td>${car.slogan }</td>
		</tr>
	</c:forEach>
	

</table>
</body>
</html>

Previous: Login authorization authentication (1) (mybatis)

Next: Login authentication authorization (3) (mybatis+spring+springmvc)

Guess you like

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