一,先写一个Druid的连接池
public class DruidUtil {
static DruidDataSource dataSource;
static{
Properties properties = new Properties();
try {
properties.load(DruidUtil.class.getClassLoader().getResourceAsStream("alibaba.properties"));
dataSource = (DruidDataSource)DruidDataSourceFactory.createDataSource(properties);
} catch (IOException e) {
e.printStackTrace();
}catch (Exception e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
try {
return dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return null;
}
public static void colse(){
dataSource.close();
}
}
二:进行查询,增,删,改,查
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String username = request.getParameter("username");
String pwd = request.getParameter("password");
String sql ="select * from users where name=? and password = ?";
Connection connection = DruidUtil.getConnection();
try {
PreparedStatement prepareStatement = connection.prepareStatement(sql);
prepareStatement.setString(1, username);
prepareStatement.setString(2, pwd);
ResultSet resultSet = prepareStatement.executeQuery();
if ( resultSet.next()) {
System.out.println("11");
request.setAttribute("username", username);
request.getRequestDispatcher("/welcome").forward(request, response);
}
else{
System.out.println("aaaaa");
}
} catch (SQLException e) {
e.printStackTrace();
}
}
三:输出结果
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
PrintWriter writer = response.getWriter();
writer.println("<html>");
writer.println("<body>");
writer.println("<span style='color:red'>"+request.getAttribute("username")+"</span>");
writer.println("</body>");
writer.println("</html>
四:index.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"><br>
密码:<input type="text" name="password">
<input type="submit" value="登录">
</form>
</body>
</html>
五:结果
运行。