Login authorization authentication (1) (mybatis)

I have written three articles about login authorization and authentication, which are demos written using mybatis, mybatis+spring, mybatis+spring+springmvc, which are both a sort of ssm process and a foreshadowing of shiro learning

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

Build mybatis environment

mybatis.xml file

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
	<settings>
		<setting name="logImpl" value="LOG4J"/>
	</settings>
	<typeAliases>
		<package name="cn.wit.pojo"/>
	</typeAliases>
	
	<environments default="mysql">
		<environment id="mysql">
			<transactionManager type="JDBC"></transactionManager>
			<dataSource type="POOLED">
				<property name="driver" value="com.mysql.jdbc.Driver"/>
				<property name="url" value="jdbc:mysql://localhost:3306/wit"/>
				<property name="username" value="root"/>
				<property name="password" value="wityy"/>
			</dataSource>
		</environment>
	</environments>
	
	<mappers>
		<package name="cn.wit.mapper"/>
	</mappers>
</configuration>

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

package cn.wit.service;

import java.io.IOException;
import java.util.List;

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

public interface LoginService {
    
    
	Users login(Users users)throws IOException;
	List<Car> getCars(Users users)throws IOException;
}

package cn.wit.serviceImpl;

import java.io.IOException;
import java.io.InputStream;
import java.util.List;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

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;

public class LoginServiceImpl implements LoginService{
    
    
	
	@Override
	public Users login(Users users) throws IOException {
    
    
	//如果登录成功,认证成功,拿到user对象
		InputStream is=Resources.getResourceAsStream("mybatis.xml");
		SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
		SqlSession session=factory.openSession();	
		UsersMapper usersMapper = session.getMapper(UsersMapper.class);
	
		return usersMapper.selUsers(users);
	}

	@Override
	public List<Car> getCars(Users users) throws IOException {
    
    
	//登录成功后调用该方法进行授权,返回car 的list
		InputStream is=Resources.getResourceAsStream("mybatis.xml");
		SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);
		SqlSession session=factory.openSession();	
		CarMapper carMapper = session.getMapper(CarMapper.class);
		
		return carMapper.selCar(users);
		
	}

}

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 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 loginService=new LoginServiceImpl();
	@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");
		System.out.println(username+":"+password);
		Users users=new Users(username,password);
		Users u= loginService.login(users);
		System.out.println(u);
		
		//如果认证成功,则进行授权操作
		//如果认证失败,则 error设为yes回到登录界面弹框密码错误
		if(u!=null){
    
    
			List<Car> cars=loginService.getCars(u);
			System.out.println(cars);
			//登录操作不适合用请求转发,所以用session来传参
			HttpSession session = req.getSession();
			session.setAttribute("cars", cars);
			resp.sendRedirect("/car2/main.jsp");
		}else{
    
    
			resp.sendRedirect("/car2/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>

Next: Login authorization authentication (2) (mybatis+spring)

Guess you like

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