这里连接的是oracle数据库。
JDBC是什么:JDBC是java数据库连接技术的简称,提供连接各种常用数据库的能力。
客户端发送请求给应用服务器,应用服务器通过JDBC连接到数据库服务器,查询数据库中的数据,返回一个结果集,再把结果集转换成实体类传递给客户端。
JDBC连接数据库的步骤:加载驱动、建立连接、执行SQL语句、返回结果集
下图主要详细描述了客户端是如何连接到数据库的:
访问数据库的代码一般都放在DAO(Data Assess Object 数据库存取对象)层,DAO层位于业务逻辑和持久化数据之间,实现对持久化数据的访问。DAO层起着转换器的作用,把实体类转换为数据库中的记录,或者把数据库中的记录转换成实体类。
利用JDBC实现登录功能(代码):
登录页面:login.jsp
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
登录
没有账号,立即注册
建立一个实体类:User.java
package com.jredu.entity;
/**
* 实体类
* @author Administrator
*
*/
public class User {
private int id;
private String uname;
private String pwd;
public User() {
super();
}
public User(String uname, String pwd) {
super();
this.uname = uname;
this.pwd = pwd;
}
public User(int id, String uname, String pwd) {
super();
this.id = id;
this.uname = uname;
this.pwd = pwd;
}
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUname() {
return uname;
}
public void setUname(String uname) {
this.uname = uname;
}
public String getPwd() {
return pwd;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
LoginServlet.java
package com.jredu.controller;
import java.io.IOException;
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 com.jredu.entity.User;
import com.jredu.service.LoginService;
import com.jredu.service.impl.LoginServiceImpl;
@WebServlet(value="/login.action")
public class LoginServlet extends HttpServlet {
private LoginService service;
/**
* The doGet method of the servlet.
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doPost(request, response);
}
/**
* The doPost method of the servlet.
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
String uname=request.getParameter("uname");
String pwd=request.getParameter("pwd");
//调用javabean
service=new LoginServiceImpl();
User user=service.login(uname, pwd);
//跳转jsp
if(user!=null) {
request.getSession().setAttribute("user", user);
response.sendRedirect("index.jsp");
} else {
request.setAttribute("error", "登录失败请重新输入");
request.getRequestDispatcher("login.jsp").forward(request, response);
}
}
}
LoginService.java
package com.jredu.service;
import com.jredu.entity.User;
public interface LoginService {
/**
* 登录功能
* @param uname
* @param pwd
* @return
*/
User login(String uname, String pwd);
}
LoginServiceImpl.java
package com.jredu.service.impl;
import com.jredu.dao.UserDao;
import com.jredu.dao.impl.UserDaoImpl;
import com.jredu.entity.User;
import com.jredu.service.LoginService;
public class LoginServiceImpl implements LoginService {
private UserDao ud=new UserDaoImpl();
@Override
public User login(String uname, String pwd) {
// TODO Auto-generated method stub
//下面是业务处理,访问数据库在UserDaoImpl类中
User user = new User(uname,pwd);
return ud.findUser(user);
}
}
UserDao.java
package com.jredu.dao;
import java.util.List;
import com.jredu.entity.User;
/**
* 数据库访问的接口。
* @author jiaxutianhuo
*
*/
public interface UserDao {
//登录
User findUser(User user);
//查询
public List query(String sql,String sex) throws Exception;
}
UserDaoImpl.java
package com.jredu.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.jredu.dao.UserDao;
import com.jredu.entity.User;
import com.jredu.util.BaseDao;
public class UserDaoImpl extends BaseDao implements UserDao {
@Override
public User findUser(User user) {
// TODO Auto-generated method stub
//3.执行sql语句
//4.获取结果集
ResultSet rs=executeQuery("select * from users where username=? and userpwd=?", user.getUname(),user.getPwd());
//访问数据库查询是否存在该用户
try {
//登录成功
if(rs.next()) {
//把结果集转换成实体类
user.setUname(rs.getString("username"));
user.setPwd(rs.getString("userpwd"));
user.setId(rs.getInt("userid"));
return user;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeAll();
}
//不存在该用户
return null;
}
//查询
@Override
public List query(String sql, String sex) throws Exception {
// TODO Auto-generated method stub
List list = new ArrayList();
ResultSet rs = new BaseDao().executeQuery(sql, sex);
while (rs.next()) {
User us = new User();
us.setUname(rs.getString("name"));
list.add(us);
}
return list;
}
}
BaseDao.java
package com.jredu.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.jredu.dao.UserDao;
import com.jredu.entity.User;
import com.jredu.util.BaseDao;
public class UserDaoImpl extends BaseDao implements UserDao {
@Override
public User findUser(User user) {
// TODO Auto-generated method stub
//3.执行sql语句
//4.获取结果集
ResultSet rs=executeQuery("select * from users where username=? and userpwd=?", user.getUname(),user.getPwd());
//访问数据库查询是否存在该用户
try {
//登录成功
if(rs.next()) {
//把结果集转换成实体类
user.setUname(rs.getString("username"));
user.setPwd(rs.getString("userpwd"));
user.setId(rs.getInt("userid"));
return user;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeAll();
}
//不存在该用户
return null;
}
//查询
@Override
public List query(String sql, String sex) throws Exception {
// TODO Auto-generated method stub
List list = new ArrayList();
ResultSet rs = new BaseDao().executeQuery(sql, sex);
while (rs.next()) {
User us = new User();
us.setUname(rs.getString("name"));
list.add(us);
}
return list;
}
}
CharacterFilter.java
package com.jredu.filter;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;
/**
* 编码过滤器
* @author Administrator
*
*/
@WebFilter(value="/*",initParams={@WebInitParam(name="encoding",value="utf-8")})
public class CharacterFilter implements Filter {
private String encoding;
/**
* 初始化
*/
@Override
public void init(FilterConfig filterConfig) throws ServletException {
// TODO Auto-generated method stub
System.out.println("字符编码过滤器启动...");
encoding=filterConfig.getInitParameter("encoding");
}
/**
* 过滤功能
*/
@Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain chain) throws IOException, ServletException {
// TODO Auto-generated method stub
//设置请求编码格式
request.setCharacterEncoding(encoding);
//设置响应编码格式
response.setContentType("text/html;charset="+encoding);
response.setCharacterEncoding(encoding);
chain.doFilter(request, response);
}
/**
* 销毁
*/
@Override
public void destroy() {
// TODO Auto-generated method stub
System.out.println("字符编码过滤器结束...");
}
}
index.jsp
<%@ page language="java"
import="java.util.*,com.jredu.util.BaseDao,java.sql.Connection,java.sql.ResultSet"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
My JSP 'index.jsp' starting page
<%
ResultSet rs = new BaseDao()
.executeQuery("select * from users");
while (rs.next()) {
%>
<%=rs.getString("USERNAME")%>
<%
}
%>
什么是JNDI:JNDI(Java Naming and Directory Interface,java命名和目录接口),是一组在Java应用中访问命名和目录服务的API,通过名称将资源与服务进行关联。
使用连接池的好处:
1、可以弥补传统数据库连接方式的不足。传统数据库每一次请求时均需要连接数据库,资源占用较多;当并发访问
数据量较大时,网站速度受到极大的影响;在访问结束后必须要关闭连接释放资源;系统的安全性和稳定性相对较差。
2、企业级开发需要稳健和高效的数据访问层。使用连接池可以完成对数据库的CRUD操作,能够处理数据库发生的各种错误,可以灵活的修改配置,提供方便使用的工具,具有的性能较高。
什么是连接池技术:
利用连接池实现登录:
在上述代码的基础上稍加修改,下面是修改了的代码:
UserDaoImpl.java
package com.jredu.dao.impl;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;
import com.jredu.dao.UserDao;
import com.jredu.entity.User;
import com.jredu.util.BaseDao;
import com.jredu.util.JNDIBaseDao;
public class UserDaoImpl extends JNDIBaseDao implements UserDao {
@Override
public User findUser(User user) {
// TODO Auto-generated method stub
//3.执行sql语句
//4.获取结果集
ResultSet rs=executeQuery("select * from users where username=? and userpwd=?", user.getUname(),user.getPwd());
//访问数据库查询是否存在该用户
try {
//登录成功
if(rs.next()) {
//把结果集转换成实体类
user.setUname(rs.getString("username"));
user.setPwd(rs.getString("userpwd"));
user.setId(rs.getInt("userid"));
return user;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} finally {
closeAll();
}
//不存在该用户
return null;
}
//查询
@Override
public List query(String sql, String sex) throws Exception {
// TODO Auto-generated method stub
List list = new ArrayList();
ResultSet rs = new BaseDao().executeQuery(sql, sex);
while (rs.next()) {
User us = new User();
us.setUname(rs.getString("name"));
list.add(us);
}
return list;
}
}
JNDIBaseDao.java
package com.jredu.util;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.naming.Context;
import javax.naming.InitialContext;
import javax.naming.NamingException;
import javax.sql.DataSource;
public class JNDIBaseDao {
private DataSource source; //数据源
private Connection connection;
private PreparedStatement ps;
private ResultSet rs;
{
try {
Context ic = new InitialContext();//初始化
source = (DataSource)ic.lookup("java:comp/env/jdbc/orcl");//在tomcat中配置
} catch (NamingException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void getConnection() {
try {
connection=source.getConnection();//数据源创建connection
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 增删改操作
* @param sql
* @param objs
* @return 影响行数
*/
public int executeUpdate(String sql,Object... objs) {
if(connection==null) {
getConnection();
}
int res=-1;
try {
//设置手动提交事务
connection.setAutoCommit(false);
connection.setTransactionIsolation(Connection.TRANSACTION_READ_COMMITTED);
ps=connection.prepareStatement(sql);
if(objs!=null) {
for(int i=0;i
<%@ page language="java"
import="java.util.*,com.jredu.util.JNDIBaseDao,java.sql.Connection,java.sql.ResultSet"
pageEncoding="UTF-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme() + "://"
+ request.getServerName() + ":" + request.getServerPort()
+ path + "/";
%>
My JSP 'index.jsp' starting page
<%
ResultSet rs = new JNDIBaseDao()
.executeQuery("select * from users");
while (rs.next()) {
%>
<%=rs.getString("USERNAME")%>
<%
}
%>