小言_互联网的博客

Javaweb项目与MySQL的连接

279人阅读  评论(0)

Javaweb项目与MySQL的连接



db.properties


jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/数据库名
jdbc.username=root
jdbc.password=root

ConnectionUtils.java


package com.atguigu.login.utils;
/**
 * 连接的工具类
 */

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;

public class ConnectionUtils {
	
	private static String driver = null;
	private static String url = null;
	private static String username = null;
	private static String password = null;
	private static Properties props = new Properties();
	//ThreadLocal:保证一个线程中只能有一个连接,避免连接的浪费
	private static ThreadLocal<Connection> tl = new ThreadLocal<>();
	
	/**
	 * 静态的代码块读取db.properties
	 */
	static {
		//类加载器读取文件
		try {
			InputStream in = ConnectionUtils.class.getClassLoader().getResourceAsStream("db.properties");
			props.load(in);
			
			driver = props.getProperty("jdbc.driver");
			url = props.getProperty("jdbc.url");
			username = props.getProperty("jdbc.username");
			password = props.getProperty("jdbc.password");
			
			Class.forName(driver);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}
	
	/**
	 * 获取连接的方法
	 */
	public static Connection getConn() throws Exception{
		//先尝试从tl中获取
		Connection conn = tl.get();
		if (conn == null) {
			conn = DriverManager.getConnection(url, username, password);
			tl.set(conn);
		}
		return conn;
	}
	
	/**
	 * 关闭连接的方法
	 */
	public static void closeConn() throws Exception{
		//先尝试从tl中获取
		
		Connection conn = tl.get();
		if (conn != null) {
			conn.close();
		}
		tl.set(null);
	}
}


User.java


package com.atguigu.login.beans;

public class User {
	private Integer id;
	private String username;
	private String password;
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
	}
	
	
}

UserDao.java


package com.atguigu.login.dao;

import com.atguigu.login.beans.User;

public interface UserDao {

	public User getUserByUsernameAndPassword(String username,String password);
}


UserDaoimpl.java


package com.atguigu.login.dao;

import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.Connection;
import com.atguigu.login.beans.User;
import com.atguigu.login.utils.ConnectionUtils;


public class UserDaoImpl implements UserDao{
	
	@Override
	public User getUserByUsernameAndPassword(String username, String password) {
		User u = null;
		try {
			//JDBC:获取连接,编写SQL,预编译SQL,设置参数,执行SQL,封装结果,关闭连接
//			Class.forName("com.mysql.jdbc.Driver");
//			String url = "jdbc:mysql://localhost:3306/webstudy";
//			String user = "root";
//			String pawd = "root";		
//			Connection conn = DriverManager.getConnection(url, user, pawd);
			
			Connection conn = ConnectionUtils.getConn();
			String sql = "select id,username,password from tbl_user where username=? and password=?";
			PreparedStatement ps = conn.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, password);
			
			ResultSet rs = ps.executeQuery();
			
			if(rs.next()) {
				u = new User();
				u.setId(rs.getInt("id"));
				u.setUsername(rs.getString("username"));
				u.setPassword(rs.getString("password"));
			}
			return u;
			
		} catch (Exception e) {
			e.printStackTrace();
		}finally {
			try {
				ConnectionUtils.closeConn();
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
		return null;
	}
}



LoginServlet.hava

package com.atguigu.login.servlet;

import java.io.IOException;
import java.io.PrintWriter;
import java.nio.charset.Charset;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.atguigu.login.beans.User;
import com.atguigu.login.dao.UserDao;
import com.atguigu.login.dao.UserDaoImpl;

public class LoginServlet extends HttpServlet{

	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		doPost(req, resp);
	}
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		System.out.println("请求过来了。。。。");
		//获取到用户输入的用户名和密码,进行登录业务的处理。
		//HttpServletRequest:请求对象。Servlet容器会在请求到达后,创建出一个request对象,将Http请求相关的信息全部都封装到该对象中。
		//在获取数据之前解决乱码问题1
		req.setCharacterEncoding("utf-8");
		//获取用户名
		String username = req.getParameter("username");
		//获取密码
		String password = req.getParameter("password");
		System.out.println(username+","+password);
		//在获取输入流之前解决乱码问题2
		resp.setContentType("text/html;charset=utf-8");
		PrintWriter out = resp.getWriter();
		//验证用户名与密码是否正确
		
		//获取Dao对象
		UserDao userDao = new UserDaoImpl();
		User user = userDao.getUserByUsernameAndPassword(username, password);
		
		if(user == null) {
			out.print("登录失败");
		}else {
			out.print("登陆成功");
		}
		
	}
	
}

转载:https://blog.csdn.net/qq_42145862/article/details/101145570
查看评论
* 以上用户言论只代表其个人观点,不代表本网站的观点或立场