一、项目搭建
1、在src下创建jdbc.properties
目的:用属性文件保存数据库信息,以后更改项目的数据库时候可以直接在本文件修改,不需要每个方法里都修改
mysql.driver = com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/数据库名?useUnicode=true&characterEncoding=utf-8
mysql.uname=用户
mysql.upwd=密码
2、读取属性文件(测试)
Properties ps = new Properties();
InputStream in = Test.class.getClassLoader().getResourceAsStream("jdbc.properties");
try {
//加载properties配置文件
ps.load(in);
//获取驱动
System.out.println(ps.getProperty("mysql.driver"));
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
3、封装属性文件操作类--PropertyUtil
package com.hqyj.util;
/**
* 数据库属性文件工具类
*/
import java.io.IOException;
import java.io.InputStream;
import java.util.Properties;
public class PropertyUtil {
/**
* 数据库信息常量
*/
//驱动
public static final String DRTVER = "mysql.driver";
//路径
public static final String URL = "mysql.url";
public static final String UNAME = "mysql.uname";
public static final String UPWD = "mysql.upwd";
/**
* 属性文件操作工具
*/
private static Properties ps = new Properties();
/**
* 加载属性文件(类加载时就加载,先执行,只执行一次)
*/
static {
InputStream in = PropertyUtil.class.getClassLoader().getResourceAsStream("jdbc.properties"); //文件名
try {
//加载
ps.load(in);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* 获取属性文件的属性信息
* @param pname 属性名
* @return 属性的值
* 通过其可获得:
* System.out.println(PropertyUtil.getProperty(PropertyUtil.UNAME))
*/
public static String getProperty(String pname) {
return ps.getProperty(pname);
}
}
4、业务层----封装DAO父类,解决获得连接的代码重复问题
目的:封装一些方法,建立连接、关闭连接,事务处理等
package com.hqyj.dao;
/**
* 父类的Dao 封装连接的获取和关闭
* 事务管理
* 实现事务管理机制,保障数据的一致性
* 实现功能的重用(复用)
*/
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import com.hqyj.util.PropertyUtil;
public class BaseDao {
/**
* 数据库连接
*/
//获得链接,封装到父类的方法中
private Connection con;
/**
* 获得数据库连接
* @return connection对象
* @throws Exception
*/
public Connection getCon() throws Exception {
if (con == null) { //获取连接,不需要重复的获取连接
Class.forName(PropertyUtil.getProperty(PropertyUtil.DRTVER));
String url = PropertyUtil.getProperty(PropertyUtil.URL);
String user = PropertyUtil.getProperty(PropertyUtil.UNAME);
String password = PropertyUtil.getProperty(PropertyUtil.UPWD);
con = DriverManager.getConnection(url, user, password);
System.out.println("--con连接成功--");
}
return con;
}
public void setCon(Connection con) {
this.con = con;
}
//关闭连接
public void closeCon() {
try {
this.con.close();
//关闭连接后,把连接设为null,下次会重新开启服务器,重新获得连接
this.con = null;
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/*
* 增加实务操作(保持事物的一致性)
* 实现的必要条件
*/
//开启事务,手动提交
public void beginTran() throws Exception {
this.getCon().setAutoCommit(false);
}
//没有异常,提交事务
public void comiitTran() throws Exception {
this.getCon().commit();
}
//发生异常,回滚事务
public void rollbackTran() throws Exception {
this.getCon().rollback();
}
}
5、实现Dao子类,继承父类Dao
目的:操作数据,不在这里关闭连接
public class StudentDao extends BaseDao {
public void insert(Student s) throws Exception {
// 录入
String sql = "insert into student values(null,?,?,?)";
//预编译SQL语句
PreparedStatement ps = getCon().prepareStatement(sql);
// 赋值替换
ps.setString(1, s.getSname());
ps.setString(2, s.getSpwd());
ps.setString(3, s.getClazz());
//用于执行数据库数据操作语句(DML)和数据定义语句(DDL),返回一个整数
ps.executeUpdate();
}
6、创建servlet
用注解的形式,替换了原始的web.xml配置
注意:采用注解的形式,一定不要创建web.xml文件,否则会报错误(亲身经历):
删除web.xml文件就可以了
创建servlet文件:
@WebServlet("/StudentLogin")
public class StudentLogin extends HttpServlet {
private static final long serialVersionUID = 1L;
7、创建service包和类
业务类---执行1个或多个dao方法,完成一块业务需求,在业务中保障事务的一致性
package com.hqyj.service;
import java.util.ArrayList;
/*
* 和业务相关的操作在这里写
* 执行1个或多个dao方法,完成一块业务的需求
* 在业务中保障事务的一致性
*/
import com.hqyj.dao.StudentDao;
import com.hqyj.pojo.Student;
public class StudentService {
private StudentDao sDao = new StudentDao();
public void insert(Student s) throws Exception {
//开启事务,只有一个指令不用开启事务
// sDao.beginTran();
// sDao.commitTran();
sDao.insert(s);
sDao.closeCon();
}
public void update(Student s) throws Exception{
sDao.update(s);
sDao.closeCon();
}
public void delete(int sid) throws Exception{
sDao.delete(sid);
sDao.closeCon();
}
public Student selectOne(int sid) throws Exception{
Student s = sDao.selectOne(sid);
sDao.selectOne(sid);
sDao.closeCon();
return s;
}
public ArrayList selectList() throws Exception{
ArrayList list = sDao.selectList();
sDao.closeCon();
return list;
}
/**
* 登录业务
* @param sid 学生编号
* @param spwd 学生密码
* @return 学生对象 错误返回null
* @throws Exception
*/
public Student selectLogin(int sid,String spwd) throws Exception {
Student s = sDao.selectOne(sid);
sDao.closeCon();
if (s != null && s.getSpwd().equals(spwd)) {
return s;
}
return null;
}
}
8、用业务类实现登录功能
9、项目设计和命名规则
- pojo---实体类---表 [ entity、model、domain ]
- dao---数据访问层----操作一张表数据 [ mapper ]
- service---业务层---控制dao,实现业务管理及功能的复用
- ctrl---控制层---servlet---数据的传递及流程的控制---调度 [ controller ]
- view---视图层---html、jsp---展示数据
-
类名---帕斯卡命名规则,每个单词首字母大写
dao---实体类Dao
---insert、update、delete、selectOne、selectList、selectXxx
service---实体类Service
---insert、update、delete、selectOne、selectList、selectXxx
ctrl----实体类+功能名称---StudentInsert
---StudenInsert、StudentUpdate、StudentDelete...
view---jsp----全部小写----实体类+功能名称
---studentinsert.jsp、studentupdate.jsp、studentlist.jsp...
---首页index.jsp、主页main.jsp
二、servlet
1、servlet的生命周期
(1)Servlet生命周期是指Servlet实例从创建到响应客户请求,直至销毁的过程。Servlet程序本身不直接在Java虚拟机上运行,由Servlet容器负责管理其整个生命周期。
(2)Servlet生命周期可分为四个阶段:实例化、初始化、处理请求、销毁。
(3)Servlet容器在(在Servlet容器启动后,客户首次向Servlet发出请求,根据客户的请求创建HttpRequest、HttpResponse对象,从而调用Servlet 对象的service方法)(在为Servlet配置了自动装入选项(load-on-startup)时,服务器在启动时会自动装入此Servlet) 加载和实例化一个Servlet
(4)Servlet初始化,Servlet容器将调用Servlet的init方法来对Servlet实例进行初始化
(5)请求处理,创建“请求”对象和“响应”对象,并调用service()方法,service()方法再调用其他方法(doget\dopost)来处理请求
(6)服务终止,调用Servlet的destroy()方法使其释放正在使用的资源
2、servlet运行机制--单例多线程模式
3、init和destroy方法只执行一次
4、servlet创建方式
继承 HttpServlet ----javax.servlet.http包
实现doGet、doPost方法
实现 Servlet接口----javax.servlet包
实现service方法即可
package com.hqyj.ctrl;
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;
/**
* Servlet implementation class test
*/
@WebServlet("/test")
public class test extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public test() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
response.getWriter().append("Served at: ").append(request.getContextPath());
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
5、request应用
(1)request常用方法
***getParameter("元素名")-----返回字符串
***getParameterValues("元素名")-----返回字符串数组---复选框
***setCharacterEncoding("字符集")---设置字符集
// 统一资源标识符
String uri = request.getRequestURI();
//统一资源定位符---完整的路径
***StringBuffer url = request.getRequestURL();
getMethod()---请求的方式get、post
getParameterMap()---获取所有请求信息,键值对
getParameterNames()---获取所有请求元素名
(2)实现数据展示
jsp动态标签和EL表达式
- 保存数据到request中
request.setAttribute("list", list);
//两个WEB间为转发关系时,转发目的WEB可以用getAttribute()方法来和转发源WEB共享request范围内的数据(从1.jsp转发到2.jsp)
RequestDispatcher--------请求转发器
- 转发数据到展示页---请求转发
request.getRequestDispatcher("studentlist.jsp").forward(request, response);
try {
ArrayList list = ss.selectList();
//保存数据到request中
request.setAttribute("list", list);
} catch (Exception e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
//转发数据到展示页
//RequestDispatcher转发器,将request和response带到展示页jsp
request.getRequestDispatcher("studentlist.jsp").forward(request, response);
}
- 展示数据---需要动态标签
jsp编程模式
引入jsp核心标签库
<%http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<c:forEach var="s" items="${list }">
<tr>
<td>${s.sid }</td>
<td><a href="StudentSelectOne?sid=${s.sid }">${s.sname }</a></td>
<td>${s.clazz }</td>
<td><a href="StudentDelete?sid=${s.sid }">删除</a></td>
</tr>
</c:forEach>
6、重定向
原请求地址重新定位到某个新地址,原有的request请求失效,客户端看到的是新的request请求返回的响应结果,客户端浏览器地址栏变为新请求地址
response.sendRedirect("/ServletDemo1/index.jsp");
7、请求转发
请求再转发到其他地址,转发过程中使用的是同一个request请求,转发后浏览器地址栏内容不变
RequestDispatcher dispatcher = request.getRequestDispatcher(String path);
dispatcher.forward(ServletRequest request,ServletResponse response);
简写:
request.getRequestDispatcher("studentlist.jsp").forward(request, response);
8、请求转发与重定向数据传递
对HttpServletRequest对象属性的存取
request.setAttribute("attrobj",“value"); // 将attrobj属性值存储到request对象中
request.getAttribute("attrobj"); // 从request对象中取出attrobj属性值