目录
1.Maven
Maven 由于他的约定大于配置,我们之后可以能遇到我们写的配置文件,无法被导出或者生效的问题,解决方案:
<!--在build中配置resources,来防止我们资源导出失败的问题-->
<build>
<resources>
<resource>
<directory>src/main/resources</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
<resource>
<directory>src/main/java</directory>
<includes>
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>true</filtering>
</resource>
</resources>
</build>
2.web.xml中写个servlet-name和映射地址
<servlet-mapping>
<servlet-name>helloServlet</servlet-name>
<url-pattern>/bao</url-pattern>
</servlet-mapping>
3.Maven中添加jsp,servlet依赖
<!--添加Servlet和JSP依赖-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.0.1</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2</version>
</dependency>
4.编写HelloServlet类
public class HelloServlet extends HttpServlet {
//由于get或post只是请求实现的不同方式,可以相互调用,业务逻辑都一样
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("我最帅");
resp.setCharacterEncoding("utf-8");
PrintWriter writer = resp.getWriter();//响应流
writer.print("HelloServlet");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
5.注册servlet以及映射地址
<!--注册servlet-->
<servlet>
<servlet-name>hello</servlet-name>
<servlet-class>com.bao.servlet.HelloServlet</servlet-class>
</servlet>
<!--servlet的请求路径-->
<servlet-mapping>
<servlet-name>hello</servlet-name>
<url-pattern>/hello</url-pattern>
</servlet-mapping>
6.servletcontext
public class HelloServlet extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
String username = "鲍星博";
context.setAttribute("username",username);
}
@Override
protected void doPut(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
public class GetServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
String username =(String)context.getAttribute("username");
resp.getWriter().print("名字:"+username);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
7.获取默认配置的参数
<context-param>
<param-name>url</param-name>
<param-value>jdbc:mysql://localhost:3306/mybatis</param-value>
</context-param>
public class ServletDemo03 extends HttpServlet{
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
String url = context.getInitParameter("url");
resp.getWriter().print(url);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
8.请求转发
public class ServletDemo04 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
ServletContext context = this.getServletContext();
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
context.getRequestDispatcher("/gp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
9.读取配置文件中信息
public class ServletDemo05 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
InputStream is = this.getServletContext().getResourceAsStream("/WEB-INF/classes/dp.properties");
Properties prop = new Properties();
prop.load(is);
String username = prop.getProperty("username");
String pwd = prop.getProperty("password");
resp.getWriter().print(username+":"+pwd);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
10.文件下载
public class FileServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1.要获取下载文件的路径
String realPath = "F:\\idea-work\\MavenTest\\javaweb-02-servlet\\response-01\\target\\response-01\\WEB-INF\\classes\\1.jpg";
//2.下载的文件名
String filename = realPath.substring(realPath.lastIndexOf("\\") + 1);
//3.让浏览器支持下载我们需要的东西
resp.setHeader("Content-Disposition","attachment;filename="+filename);
//4.获取下载文件的输入流
FileInputStream in = new FileInputStream(realPath);
//5.创建缓冲区
int len = 0;
byte[] buffer = new byte[1024];
//6.获取OutputStream对象
ServletOutputStream out = resp.getOutputStream();
//7.将fileOutStream流写入到buffer缓冲区,使用OutputStream将缓冲区中数据输出到客户端
while ((len=in.read(buffer))>0){
out.write(buffer,0,len);
}
in.close();
out.close();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
11.验证码功能的实现
public class ImageServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//让浏览器三秒刷新一次
resp.setHeader("refresh","3");
//在内存中创建一个图片
BufferedImage image = new BufferedImage(80, 30, BufferedImage.TYPE_INT_RGB);
//得到图片
Graphics2D g = (Graphics2D) image.getGraphics();//笔
//设置图片背景颜色
g.setColor(Color.white);
g.fillRect(0,0,80,20);
//给图片写数据
g.setColor(Color.blue);
g.setFont(new Font(null,Font.BOLD,20));
g.drawString(makeNum(),0,20);
//告诉浏览器这个请求用图片的方式打开
resp.setContentType("image/jpeg");
//设置不让浏览器缓存
resp.setDateHeader("expries",-1);
resp.setHeader("Cache-Control","no-cache");
resp.setHeader("Pragma","no-cache");
//把图片写给浏览器
ImageIO.write(image,"jpg",resp.getOutputStream());
}
//生成随机数
private String makeNum() {
Random random = new Random();
String num = random.nextInt(999999)+"";
StringBuffer sb = new StringBuffer();
for (int i = 0; i < 6-num.length() ; i++) {
sb.append("0");
}
num = num + sb.toString();
return num;
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
12.response重定向
public class RedirectServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//重定向
resp.sendRedirect("/image");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
13.从表单读取参数,进行处理,并重定向
<html>
<body>
<h2>Hello World!</h2>
<%--${pageContext.request.contextPath} 代表当前的项目--%>
<form action="${pageContext.request.contextPath}/requ" method="get">
name:<input type="text" name="username"><br>
pwd:<input type="password" name="password"><br>
<input type="submit">
</form>
</body>
</html>
进行处理,并使用response重定向
public class RequestTest extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//处理请求
String username = req.getParameter("username");
String password = req.getParameter("password");
System.out.println(username+":"+password);
System.out.println("进入这个请求了");
resp.sendRedirect("success.jsp");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
成功后的界面
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>Success</h1>
</body>
</html>
13.request重定向
登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<div>
<form action="${pageContext.request.contextPath}/login" method="post">
用户名:<input type="text" name="username" ><br>
密码:<input type="text" name="password"><br>
爱好:
<input type="checkbox" name="hobbys" value="女孩">女孩
<input type="checkbox" name="hobbys" value="代码">代码
<input type="checkbox" name="hobbys" value="唱歌">唱歌
<input type="checkbox" name="hobbys" value="跳舞">跳舞
<br>
<input type="submit">
</form>
</div>
</body>
</html>
获得参数以及转发
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
String username = req.getParameter("username");
String password = req.getParameter("password");
String[] hobbys = req.getParameterValues("hobbys");
//通过请求转发
req.getRequestDispatcher("success.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
成功跳转页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录成功</title>
</head>
<body>
<h1>登录成功</h1>
</body>
</html>
14.JSP
jsp基本使用
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--JSP表达式
用来将程序的输出输出到客户端
<% 变量或表达式%>
--%>
<%= new java.util.Date()%>
<hr>
<%--JSP脚本片段--%>
<%
int sum = 0;
for (int i = 0; i <= 100 ; i++) {
sum += i;
}
out.println("<h1>Sum="+sum+"</h1>");
%>
<hr>
<%--在代码中嵌入HTML元素--%>
<%
for (int i = 0; i < 5 ; i++){
%>
<h1>Hello,bxb <%=i%></h1>
<%
}
%>
<%--在代码中嵌入HTML元素--%>
</body>
</html>
定制错误界面:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%--定制错误页面--%>
<%--<%@page errorPage="error/500.jsp" %>--%>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
int x = 1/0;
%>
</body>
</html>
404:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<img src="../img/404.jfif" alt="404">
</body>
</html>
500:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<img src="../img/500.jfif" alt="500">
</body>
</html>
在web.xml中定制错误界面:
<error-page>
<error-code>404</error-code>
<location>/error/404.jsp</location>
</error-page>
<error-page>
<error-code>500</error-code>
<location>/error/500.jsp</location>
</error-page>
15.JSP作用域
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%--内置对象--%>
<%
pageContext.setAttribute("name1","鲍星博1号");//保存的数据只在一个页面中有效
request.setAttribute("name2","鲍星博2号");//保存的数据只在一个请求中有效,请求转发会携带这个数据
session.setAttribute("name3","鲍星博3号");//保存的数据只在一个会话中有效,从打开浏览器到关闭浏览器
application.setAttribute("name4","鲍星博4号");//保存的数据只在服务器中有效,从打开服务器到关闭服务器
//先运行01,再运行02,可以取出3 4;
%>
<%--脚本片段中的代码必须严格按照java规范来--%>
<%
//从pagecontext取出,通过寻找的方式来
//从底层到高层
String name1 = (String) pageContext.findAttribute("name1");
String name2 = (String) pageContext.findAttribute("name2");
String name3 = (String) pageContext.findAttribute("name3");
String name4 = (String) pageContext.findAttribute("name4");
String name5 = (String) pageContext.findAttribute("name5");//不存在
pageContext.forward("/pageDemo02.jsp");
%>
<%--使用EL表达式输出 ${} --%>
<h1>取出的值为:</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<h3>${name5}</h3>
</body>
</html>
上面的都可以取到
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page isELIgnored="false" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
//从pagecontext取出,通过寻找的方式来
//从底层到高层
String name1 = (String) pageContext.findAttribute("name1");
String name2 = (String) pageContext.findAttribute("name2");
String name3 = (String) pageContext.findAttribute("name3");
String name4 = (String) pageContext.findAttribute("name4");
String name5 = (String) pageContext.findAttribute("name5");//不存在
%>
<%--使用EL表达式输出 ${} --%>
<h1>取出的值为:</h1>
<h3>${name1}</h3>
<h3>${name2}</h3>
<h3>${name3}</h3>
<h3>${name4}</h3>
<h3>${name5}</h3>
</body>
</html>
以上代码先运行第一个后运行第二个,可以取到3,4
请求转发
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
pageContext.forward("/index.jsp");
%>
</body>
</html>
16JSP转发
<%--JSP标签--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>1</h1>
<%--实现转发功能--%>
<jsp:forward page="jsptag2.jsp">
<jsp:param name="name" value="bxb"></jsp:param>
<jsp:param name="age" value="21"></jsp:param>
</jsp:forward>
</body>
</html>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>2</h1>
<%--取出参数--%>
名字:<%=request.getParameter("name")%><br>
年龄:<%=request.getParameter("age")%>
</body>
</html>
17.JSP Cif
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%--<%@page isELIgnored="false" %>--%>
<html>
<head>
<title>Title</title>
</head>
<body>
<h4>if测试</h4>
<hr>
<form action="coreif.jsp" method="get">
<%--
EL表达式获取表单中的数据
${param.参数名}
--%>
<input type="text" name="username" value="${param.username}">
<input type="submit" value="登录">
</form>
<c:if test="${param.username=='admin'}" var="isAdmin">
<c:out value="管理员你好!"/>
</c:if>
<c:out value="${isAdmin}"/>
</body>
</html>
18.JSP c:when
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<c:set var="score" value="85"/>
<c:choose>
<c:when test="${score>=90}">
你的成绩为优秀
</c:when>
<c:when test="${score>=80}">
你的成绩为良好
</c:when>
<c:when test="${score>=70}">
你的成绩为一般
</c:when>
<c:when test="${score<=60}">
你的成绩为糟糕
</c:when>
</c:choose>
</body>
</html>
19.JSP c:foreach
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ page import="java.util.ArrayList" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<%
ArrayList<String> people = new ArrayList<>();
people.add(0,"张三");
people.add(1,"李四");
people.add(2,"王五");
people.add(3,"赵六");
request.setAttribute("list",people);
%>
<%--
var:每一次遍历出来的变量
items:要遍历的对象
--%>
<c:forEach var="people" items="${list}">
<c:out value="${people}"/><br>
</c:forEach>
<hr>
<c:forEach var="people" items="${list}" begin="1" end="3" step="2">
<c:out value="${people}"/><br>
</c:forEach>
</body>
</html>
20.javaBean
java的实体类(pojo,entity)
--必须有一个无参构造函数
--属性必须私有化
--必须有对应的get/set方法
一般用来和数据库的字段做映射 ORM
21.MVC三层架构
Model:
业务处理:业务逻辑(service)
数据持久层:CRUD(DAO)
View:
展示数据
提供链接发起Servlet请求(a,from,img...)
Controller(Servlet)
接受用户请求:(req:请求参数)
交给业务层处理对应的代码
控制视图的跳转
总体流程:
登录-->接收用户登录请求-->处理用户请求(获取用户登录的参数,username,password)-->交给业务层处理登录业务(判断用户密码是否正确:事务)-->Dao层查询用户名和密码是否正确-->数据库
22.过滤器
作用:
处理中文乱码
登录验证
1.创建servlet类其中包含中文
public class ShowServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().print("你好呀,鲍星博!");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
2.创建过滤器类进行处理
public class CharacterEncodingFilter implements Filter{
//初始化
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("CharacterEncodingFilter初始化");
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
servletRequest.setCharacterEncoding("utf-8");
servletResponse.setCharacterEncoding("utf-8");
servletResponse.setContentType("text/html;charset=UTF-8");
System.out.println("CharacterEncodingFilter执行前");
filterChain.doFilter(servletRequest, servletResponse);//让请求继续走,如果不写,程序到这里就会被拦截
System.out.println("CharacterEncodingFilter执行后");
}
//销毁
@Override
public void destroy() {
System.out.println("CharacterEncodingFilter销毁");
}
}
3.配置web.xml
<servlet>
<servlet-name>ShowSerlvet</servlet-name>
<servlet-class>com.bxb.servlet.ShowServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>ShowSerlvet</servlet-name>
<url-pattern>/show</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>ShowSerlvet</servlet-name>
<url-pattern>/servlet/show</url-pattern>
</servlet-mapping>
<filter>
<filter-name>CharacterEncodingFilter</filter-name>
<filter-class>com.bxb.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!--只要是/servlet的任何请求都会经过这个过滤器-->
<url-pattern>/servlet/*</url-pattern>
</filter-mapping>
23.监听器
1.写一个监听器类,监听网络在线人数
//统计网站在线人数,统计session
public class OnlineCountListener implements HttpSessionListener {
//创建session监听,看你的一举一动
//一旦创建session就会触发一次这个事件
public void sessionCreated(HttpSessionEvent httpSessionEvent) {
ServletContext ctx = httpSessionEvent.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if(onlineCount==null){
onlineCount = new Integer(1);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count++);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
//销毁session监听
//销毁session会触发这个事件
public void sessionDestroyed(HttpSessionEvent httpSessionEvent) {
ServletContext ctx = httpSessionEvent.getSession().getServletContext();
Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");
if(onlineCount==null){
onlineCount = new Integer(0);
}else {
int count = onlineCount.intValue();
onlineCount = new Integer(count--);
}
ctx.setAttribute("OnlineCount",onlineCount);
}
}
2.写个html界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<body>
<h2>Hello World!</h2>
<h1>当前有 <span><%=this.getServletConfig().getServletContext().getAttribute("OnlineCount")%></span>人在线</h1>
</body>
</html>
3.注册监听器
<!--注册监听器-->
<listener>
<listener-class>com.bxb.listener.OnlineCountListener</listener-class>
</listener>
24.过滤器实现登录权限的判断与拦截
1.创建一个常量对象
public class Constant {
public static String USER_SESSION = "USER_SESSION";
}
2.登录页面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<form action="/servlet/login" method="post">
<input type="text" name="username">
<input type="submit">
</form>
</body>
</html>
3.错误界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>错误</h1>
<h3>没有权限,用户名错误</h3>
<a href="/login.jsp">返回登录页面</a>
</body>
</html>
4.登录成功界面
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1>主页</h1>
<p><a href="/servlet/logout">注销</a></p>
</body>
</html>
5.登录的servlet
public class loginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取前端请求的参数
String username = req.getParameter("username");
if(username.equals("admin")){//登录成功
req.getSession().setAttribute("USER_SESSION",req.getSession().getId());
resp.sendRedirect("/sys/success.jsp");
}else {//登陆失败
resp.sendRedirect("/error.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
6.注销的servlet
public class LogoutServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
Object user_session = req.getSession().getAttribute("USER_SESSION");
if(user_session!=null){
req.getSession().removeAttribute("USER_SESSION");
resp.sendRedirect("/login.jsp");
}else {
resp.sendRedirect("/login.jsp");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
7.过滤器的类
public class SysFilter implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
}
@Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse;
if(request.getSession().getAttribute("USER_SESSION")==null){
response.sendRedirect("/error.jsp");
}
filterChain.doFilter(request,response);
}
@Override
public void destroy() {
}
}
8.web.xml配置
<servlet>
<servlet-name>loginServlet</servlet-name>
<servlet-class>com.bxb.servlet.loginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>loginServlet</servlet-name>
<url-pattern>/servlet/login</url-pattern>
</servlet-mapping>
<servlet>
<servlet-name>LogoutServlet</servlet-name>
<servlet-class>com.bxb.servlet.LogoutServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LogoutServlet</servlet-name>
<url-pattern>/servlet/logout</url-pattern>
</servlet-mapping>
<filter>
<filter-name>SysFilter</filter-name>
<filter-class>com.bxb.listener.SysFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>SysFilter</filter-name>
<url-pattern>/sys/*</url-pattern>
</filter-mapping>
25.JDBC
1.建数据库表
CREATE TABLE users(
id INT PRIMARY KEY,
`name` VARCHAR(40),
`password` VARCHAR(40),
email VARCHAR(60),
birthday DATE
);
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(1,'张三','123456','zs@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(2,'李四','123456','ls@qq.com','2000-01-01');
INSERT INTO users(id,`name`,`password`,email,birthday)
VALUES(3,'王五','123456','ww@qq.com','2000-01-01');
SELECT * FROM users;
2.导数据库依赖
<!--mysql的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
3.IDEA中连数据库
4.编写测试类
JDBC 固定步骤:
- 加载驱动
- 连接数据库,代表数据库
- 向数据库发送SQL的对象Statement : CRUD
- 编写SQL (根据业务,不同的SQL)
- 执行SQL
- 关闭连接(先开的后关)
public class TsetJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//用户信息和url
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode = true&characterEncoding = utf-8& useSSL=true";
String username = "root";
String password = "root";
//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库对象
Connection connection = DriverManager.getConnection(url, username, password);
//3.执行sql的对象Statement
Statement statement = connection.createStatement();
//4.sql语句
String sql = "select * from users";
//5.执行sql对象,返回结果集
ResultSet resultSet = statement.executeQuery(sql);
while (resultSet.next()){
System.out.println("id="+resultSet.getObject("id"));
System.out.println("name="+resultSet.getObject("NAME"));
System.out.println("pwd="+resultSet.getObject("PASSWORD"));
System.out.println("email="+resultSet.getObject("email"));
System.out.println("birth="+resultSet.getObject("birthday"));
System.out.println("===============================================");
}
//关闭资源,先开的后关
resultSet.close();
statement.close();
connection.close();
}
}
26.Junit单元测试
1.先导包
<!--单元测试-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
2.编写代码
import org.junit.Test;
public class TestJdbc3 {
@Test
public void test(){
System.out.println("Hello!");
}
}
27.JDBC事务
1.数据库中的事务操作
START TRANSACTION ;#开启事务
UPDATE jdbc.account SET money = money - 100 WHERE name = 'A';
UPDATE jdbc.account SET money = money + 100 WHERE name = 'B';
ROLLBACK ;
COMMIT ;
2.java代码中的事务操作
public class TestJdbc3 {
@Test
public void test() throws SQLException {
//用户信息和url
String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode = true&characterEncoding = utf-8& useSSL=true";
String username = "root";
String password = "root";
Connection connection = null;
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库对象
connection = DriverManager.getConnection(url, username, password);
//3.通知数据库开启事务
connection.setAutoCommit(false);
String sql = "UPDATE jdbc.account SET money = money - 100 WHERE name = 'A';";
connection.prepareStatement(sql).executeUpdate();
String sql2 = "UPDATE jdbc.account SET money = money + 100 WHERE name = 'B';";
connection.prepareStatement(sql2).executeUpdate();
connection.commit();
System.out.println("success");
} catch (Exception e) {
try {
connection.rollback();
} catch (SQLException e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
connection.close();
}
}
}
28.