上一期我们已经说了如何通过maven新建一个后端程序,(全程配图超清晰的JAVA后台控制(maven+Tomcat+JDBC)第一期.)并写出了一个简单的Servlet程序然后通过IDEA和Tomcat创建出来了一个简单的网页,这回我们就说说怎么真正的链接数据库,(这里用的是Mysql数据库)并写出一个表单验证网页来实践一下我们的链接是否有问题
..........
javax.servlet
javax.servlet-api
4.0.0
provided
mysql
mysql-connector-java
5.1.44
com.alibaba
druid
1.0.9
com.alexkasko.springjdbc
springjdbc-iterable
1.0.3
org.junit.jupiter
junit-jupiter
RELEASE
compile
org.testng
testng
RELEASE
compile
commons-beanutils
commons-beanutils
1.8.0
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test
username=root #数据库用户名
password=123 #数据库密码
# 初始化连接数量
initialSize=5
# 最大连接数
maxActive=10
# 最大超时时间
maxWait=3000
Hello World!
package util;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;
/**
* JDBC工具类,使用Druid连接池
*/
public class JBDCUtils {
private static DataSource ds;
static{
//1.加载配置文件
Properties pro = new Properties();
try {
//用ClassLoader来加载配置文件,获取字节输入流,键值对集合
pro.load(JBDCUtils.class.getClassLoader().getResourceAsStream("Druid1.properties"));
//初始化连接池对象,返回DataSource资源
ds = DruidDataSourceFactory.createDataSource(pro);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 获取Connection对象
* @return
* @throws SQLException
*/
public static Connection getConnection() throws SQLException {
return ds.getConnection();
}
/**
* 关闭资源的方法
* @param rs
* @param stmt
* @param conn
*/
public static void close(ResultSet rs, Statement stmt, Connection conn){
if(rs != null){
try {
rs.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(stmt != null){
try {
stmt.close();
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
if(conn != null){
try {
conn.close(); //归还链接
} catch (SQLException throwables) {
throwables.printStackTrace();
}
}
}
public static void close1( Statement stmt, Connection conn){
close(null,stmt,conn);
}
/**
* 获取连接池对象
* @return DataSource资源
*/
public static DataSource getdatasourse() {
return ds;
}
}
package doMain;
public class Users {
private Integer userid;
private String userPhone;
private String author;
private Integer count;
public Integer getUserid() {
return userid;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public String getUserPhone() {
return userPhone;
}
public void setUserPhone(String userPhone) {
this.userPhone = userPhone;
}
public String getAuthor() {
return author;
}
public void setAuthor(String author) {
this.author = author;
}
public Integer getCount() {
return count;
}
public void setCount(Integer count) {
this.count = count;
}
@Override
public String toString() {
return "doMain{" +
"userid=" + userid +
", userPhone='" + userPhone + '\'' +
", author='" + author + '\'' +
", count=" + count +
'}';
}
}
package com;
import doMain.Users;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import util.JBDCUtils;
import javax.servlet.RequestDispatcher;
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 java.io.BufferedReader;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import java.util.List;
/**
* 登陆案例,使用JDBCTemplate技术
*/
@WebServlet("/demo1")
public class ServletDemo1 extends HttpServlet {
private final JdbcTemplate template = new JdbcTemplate(JBDCUtils.getdatasourse());
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("doGet成功运行");
String account = req.getParameter("account"); // 从 request 中获取名为 account 的参数的值
String password = req.getParameter("password"); // 从 request 中获取名为 password 的参数的值
System.out.println("account:" + account + "\npassword:" + password); // 打印出来看一看
/**
* 连接数据库,进行登陆操作
*/
String result = "数据库读取异常!";
if (account.isEmpty()){
result = "用户名为空!";
}else if (password.isEmpty()){
result = "密码为空!";
}else{
String sql12 = "select * from users";
List list = template.query(sql12, new BeanPropertyRowMapper(Users.class));
for (Users users : list) {
System.out.println(users.getAuthor()+" "+users.getCount());
if(users.getAuthor().equals(account)&&users.getUserPhone().equals(password)){
result = "已经连接数据库,并且匹配数据成功";
break;
}
result = "输入用户账号密码不正确,请重试";
}
}
resp.setContentType("text/html;charset=utf-8"); // 设置响应报文的编码格式
PrintWriter pw = resp.getWriter(); // 获取 response 的输出流
pw.println(result); // 通过输出流把业务逻辑的结果输出
pw.flush();
/**
* 使用一个一个函数获取表单信息和数据,主要获取表单数据
*/
resp.setContentType("text/html;charset=UTF-8");
String name = req.getParameter("account");
PrintWriter out = resp.getWriter();
String title = "使用 GET 方法读取表单数据";
// 处理中文
String docType = " \n";
out.println(docType +
"\n" +
"" + title + " \n" +
"\n" +
"" + title + "
\n" +
"\n" +
" - 用户名:"
+ name + "\n" +
"
- 密码:"
+ req.getParameter("password") + "\n" +
"
- 请求方法:"
+ req.getMethod()+ "\n" +
"
- Servlet路径:"
+ req.getServletPath()+ "\n" +
"
- URI路径:"
+ req.getRequestURI() + "\n" +
"
- URL路径:"
+ req.getRequestURL() + "\n" +
"
- URL实现协议和版本:"
+ req.getProtocol() + "\n" +
"
- 客户机的IP地址:"
+ req.getRemoteAddr() + "\n" +
"
\n" +
"");
/**
* 使用req.getHeaderNames方法来获取表头数据和信息
*/
Enumeration headerNames = req.getHeaderNames();
resp.setContentType("text/html;charset=UTF-8");
PrintWriter out1 = resp.getWriter();
String title1 = "使用 GET 方法读取表头数据";
String docType1 = " \n";
out1.println(docType1 +
"\n" +
"" + title1 + " \n" +
"\n" +
"" + title1 + "
\n" +
"\n"+
" - 用户名:"
+ req.getParameter("account") + "\n" +
"
- 密码:"
+ req.getParameter("password") + "\n"
);
while (headerNames.hasMoreElements()) { //返回了一个枚举类型,然后用类似迭代器的方法输出
out1.println(
"
- "+headerNames.nextElement()+":"
+ req.getHeader(headerNames.nextElement()) + "\n"
);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
编写完这个Servlet代码之后,直接启动IDEA上面那个绿三角,启动这个服务器,然后就会出现一个表单登录网站,在输入相应数据之后就好了,再点击登录。 这时候我们就能看到如下的这个界面。如果账号或者密码输入错误就会出现密码或账号错误的字样,我这里给的插图是否登陆成功的提示是显示在中间,不过代码写出来的结果可能是在网页的一开头。
这样的话就我们就能够有效的链接数据库了,不过在最后要强调一点就是说这里一定要打开数据库进行操作,要不然就会报错,无法连接数据库。
那么到这里我们就能够制作出简单的表单登录的操作了,下期我们再来说一说如何自制一个能够点击变更的验证码,还有一些有关数据库链接和使用的优化操作。