JAVA开发笔记

权限管理系统完整教案

一、项目演示

1.1 用户登录

JAVA开发笔记_第1张图片

1.2 登录界面

JAVA开发笔记_第2张图片

1.3 安全退出

JAVA开发笔记_第3张图片

1.4 角色的增删改查

JAVA开发笔记_第4张图片

1.5 角色的权限分配

JAVA开发笔记_第5张图片

1.6 用户管理

JAVA开发笔记_第6张图片

1.7 个人信息

JAVA开发笔记_第7张图片

二、MVC 开发模式

JAVA开发笔记_第8张图片

三、预备知识JDBC完善

3.1 入门案例

JAVA开发笔记_第9张图片

public class Dbutils {
	private static Connection conn;
	private static Properties properties = new Properties();
	//1.获得链接
	static {
		try {
			//1.注册驱动
			Class.forName("com.mysql.jdbc.Driver");
			//2.加载配置文件信息
			//properties.load(new FileInputStream("config/db.properties"));存在硬编码
			properties.load(Dbutils.class.getClassLoader().getResourceAsStream("db.properties"));
			//System.out.println(properties);
			String name = properties.getProperty("jdbc.username");
			String password = properties.getProperty("jdbc.password");
			String url = properties.getProperty("jdbc.url");
			//3.创建链接
			conn = DriverManager.getConnection(url, name, password);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//2.返回链接
	public static Connection getConnection() {
		return conn;
	}

}
public class Money {
	private int id;
	private String name;
	private int money;
	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public int getMoney() {
		return money;
	}
	public void setMoney(int money) {
		this.money = money;
	}
	@Override
	public String toString() {
		return "Money [id=" + id + ", name=" + name + ", money=" + money + "]";
	}
	
}
package com.hckj.privilege.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;

import com.hckj.privilege.model.Money;
import com.hckj.privilege.utils.Dbutils;

public class MoneyDao {
	//1.查询所有
	public List queryAll() {
		Connection conn = null;
		PreparedStatement preparedStatement = null;
		ResultSet resultSet = null;
		List list = new ArrayList<>();
		
		try {
			conn = Dbutils.getConnection();
			String sql = "select * from money";
			preparedStatement = conn.prepareStatement(sql);
			resultSet = preparedStatement.executeQuery();
			while(resultSet.next()) {
				Money money = new Money();
				money.setId(resultSet.getInt("id"));
				money.setName(resultSet.getString("name"));
				money.setMoney(resultSet.getInt("money"));
				list.add(money);
			}
		} catch (SQLException e) {
			
			e.printStackTrace();
		} finally {
			try {resultSet.close();} catch (SQLException e) {e.printStackTrace();}
			try {preparedStatement.close();} catch (SQLException e) {e.printStackTrace();}
			try {conn.close();} catch (SQLException e) {e.printStackTrace();}
		}
		return list;
	}
	public static void main(String[] args) {
		MoneyDao moneyDao = new MoneyDao();
		List list = moneyDao.queryAll();
		System.out.println(list);
		
	}
}

3.2 jdbc提升 dbutils框架1

public class MoneyDao2 {
	private QueryRunner queryRunner = new QueryRunner();
	public List queryAll() throws Exception{
		List list = queryRunner.query(Dbutils.getConnection(), "select * from money",new BeanListHandler(Money.class));
		return list;
	}
	public static void main(String[] args) throws Exception {
		MoneyDao2 moneyDao2 = new MoneyDao2();
		List list = moneyDao2.queryAll();
		System.out.println(list);
	}
}

3.3 jdbc提升连接池2

JAVA开发笔记_第10张图片

JAVA开发笔记_第11张图片

public class Dbutils2 {
	private static DataSource dataSource;
	static {
		try {
			dataSource = new ComboPooledDataSource("hellc3p0");
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	public static Connection getConn() throws Exception {
		return dataSource.getConnection();
	}
}

3.4 jdbc提升3解决事务问题

public class Dbutils2 {
	private static DataSource dataSource;
	//1.将本地正在运行的线程与连接绑定
	private static ThreadLocal threadLocal = new ThreadLocal<>();
	static {
		try {
			//dataSource = new ComboPooledDataSource("hellc3p0");
			dataSource = new ComboPooledDataSource();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//2.获得连接
	public static Connection getConn() throws Exception {
		//2.从本地线程中获取连接
		Connection conn = threadLocal.get();
		if(conn==null) {
			//3.从连接池中取出连接
			conn = dataSource.getConnection();
			//4.将连接绑定到本地线程
			threadLocal.set(conn);
		}
		return conn;
	}
}
public class MoneyServiceImpl implements MoneyService{
	private MoneyDao2 moneyDao2 = new MoneyDao2();
	@Override
	public void zhuanzhang(int userId1, int userId2, int money){
		try {
			//1.开启事务:就是内存的数据不自动刷新到磁盘
			Dbutils2.getConn().setAutoCommit(false);
			moneyDao2.exportMoney(userId1,money);
			//int i= 1/0;
			moneyDao2.importMoney(userId2,money);
			//2.提交事务:把内存上的数据刷到磁盘
			Dbutils2.getConn().commit();
		} catch (Exception e) {
			//1.清空内存的垃圾数据
			try {Dbutils2.getConn().rollback();} catch (Exception e1) {e1.printStackTrace();}
		} 
		
	}
	public static void main(String[] args) throws Exception{
		MoneyService moneyService = new MoneyServiceImpl();
		moneyService.zhuanzhang(1, 2, 10);
	}
	
}
//转出
	public void exportMoney(int userId1, int money) throws Exception {
		queryRunner.update(Dbutils2.getConn(), "update money set money=money-? where id =?", money,userId1);
		
	}
	//转入
	public void importMoney(int userId2, int money) throws Exception {
		queryRunner.update(Dbutils2.getConn(), "update money set money=money+? where id =?", money,userId2);
	}

3.5 jdbc提升4 封装事务

public class Dbutils2 {
	private static DataSource dataSource;
	//1.将本地正在运行的线程与连接绑定
	private static ThreadLocal threadLocal = new ThreadLocal<>();
	static {
		try {
			//dataSource = new ComboPooledDataSource("hellc3p0");
			dataSource = new ComboPooledDataSource();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	//2.获得连接
	public static Connection getConn() throws Exception {
		//2.从本地线程中获取连接
		Connection conn = threadLocal.get();
		if(conn==null) {
			//3.从连接池中取出连接
			conn = dataSource.getConnection();
			//4.将连接绑定到本地线程
			threadLocal.set(conn);
		}
		return conn;
	}
	//3.开启事务
	public static void startTransaction() throws Exception{
		Connection conn = getConn();
		if(conn!=null) {
			conn.setAutoCommit(false);
		}
		
	}
	//4.提交事务
	public static void commit() throws Exception{
		Connection conn = getConn();
		if(conn!=null) {
			conn.commit();
		}
	}
	//5.回滚事务
	public static void rollback() throws Exception{
		Connection conn = getConn();
		if(conn!=null) {
			conn.rollback();
		}
	}
	//6.断开连接
	public static void close() throws Exception{
		Connection conn = getConn();
		if(conn!=null) {
			//从本地线程中移除连接
			threadLocal.remove();
			//将连接还给连接池
			conn.close();
		}
	}
}
@Override
public void zhuanzhang(int userId1, int userId2, int money){
    try {
        //1.开启事务:就是内存的数据不自动刷新到磁盘
        Dbutils2.startTransaction();
        moneyDao2.exportMoney(userId1,money);
        int i= 1/0;
        moneyDao2.importMoney(userId2,money);
        //2.提交事务:把内存上的数据刷到磁盘
        Dbutils2.commit();
    } catch (Exception e) {
        //1.清空内存的垃圾数据
        try {Dbutils2.rollback();} catch (Exception e1) {e1.printStackTrace();}
    } finally {
        try {
            Dbutils2.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
public static void main(String[] args) throws Exception{
    MoneyService moneyService = new MoneyServiceImpl();
    moneyService.zhuanzhang(1, 2, 10);
}

3.6 jdbc 提升5 代理事务

/**
 * 代理服务层的类:生成具有事务的业务类
 *
 */
public class ServiceProxyFactory {
	public static  T getProxy(T target) {
		return (T)Proxy.newProxyInstance
				(target.getClass().getClassLoader(),
				target.getClass().getInterfaces(),
				new TransactionHandler(target)
				);
	}
	private static class TransactionHandler implements InvocationHandler{
		private T target;
		public TransactionHandler(T target) {
			this.target = target;
		}
		@Override
		public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
			//1.开启事务
			Dbutils2.startTransaction();
			//2.执行目标类的方法
			Object result = null;
			try {
				result = method.invoke(target, args);
			} catch (Exception e) {
				Dbutils2.rollback();
			} 
			//3.提交事务
			Dbutils2.commit();
			return result;
		}
		
	}
}
@Override
public void zhuanzhang(int userId1, int userId2, int money) throws Exception{
    moneyDao2.exportMoney(userId1,money);
    int i= 1/0;
    moneyDao2.importMoney(userId2,money);	
}
public static void main(String[] args) throws Exception{
    MoneyService moneyService = ServiceProxyFactory.getProxy(new MoneyServiceImpl());
    moneyService.zhuanzhang(1, 2, 10);
}

四、预备知识servlet的完善

4.1 入门使用

@WebServlet("/userAction.action")
public class UserAction extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		resp.getWriter().print("响应数据");
	}
}

4.2 servlet完善

思考:上面代码出现问题:一个类只能有一个service方法处理业务;但是一个UserAction,可能有登录、退出、添加、删除等多个操作需要多个service方法完成。

@WebServlet("/userAction.action")
public class UserAction extends HttpServlet {
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		resp.setContentType("text/html;charset=utf-8");
		String method = req.getParameter("method");
		if("add".equals(method)) {
			add(req,resp);
		}else if("del".equals(method)) {
			del(req,resp);
		}
	}
	private void del(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("删除业务");
	}
	private void add(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("添加业务");
	}
	
}

4.3提取BasicServlet完善

public class BasicServlet extends HttpServlet{
	@Override
	protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String methodName = req.getParameter("method");
		try {
			resp.setContentType("text/html;charset=utf-8");
			//1.获得提价参数:就是提交参数也是要调用的方法的名字
			
			if(methodName==null) {
				methodName = "listUI";
			}
			//2.获得要执行类的字节码
			Class clazz = this.getClass();
			//3.让clazz执行方法名为methodName的方法
			Method method = clazz.getDeclaredMethod(methodName, HttpServletRequest.class,HttpServletResponse.class);
			method.setAccessible(true);
			method.invoke(this, req,resp);
		} catch (Exception e) {
			throw new RuntimeException("没有提供对应的方法:"+methodName);
		}	
	}
}
@WebServlet("/userAction.action")
public class UserAction extends BasicServlet {
	
	private void del(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("删除业务");
	}
	private void add(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("添加业务");
	}
	private void listUI(HttpServletRequest req, HttpServletResponse resp) {
		System.out.println("查询业务");
	}
}

你可能感兴趣的:(java,笔记,开发语言)