JavaWeb-03
9、JavaBean
实体类
JavaBean有特定的写法:
- 必须有一个无参构造
- 属性必须私有化
- 必须有对应的get/set方法
一般用来和数据库的字段做映射 ORM;
ORM:对象关系映射
- 表 —> 类
- 字段 —> 属性
- 行记录 —> 对象
people表
id | name | 阿格拉玛 | address |
---|---|---|---|
1 | 王木1号 | 14 | 杭州 |
2 | 王木2号 | 23 | 苏州 |
3 | 王木3号 | 22 | 南京 |
class People {private int id;private String name;private int age;private String address;}
Class A {new People(1,"王木1号",14,"杭州");new People(2,"王木2号",23,"苏州");new People(3,"王木3号",22,"南京");
}
10、MVC三层架构
什么是MVC:Model View Controller 模型、视图、控制器
10.1 早些年
用户直接访问控制层,控制层可以直接操作数据库;
servlet -- CRUD-->数据库
弊端:程序十分臃肿,不利于维护 Servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码架构:没有什么是加一层解决不了的!
程序员调用
|
JDBC
|
MySQL ORacle SQLServer……
10.2 MVC三层架构
Model
- 业务处理:业务逻辑(Service)
- 数据持久层:CRUD (Dao)
View
- 展示数据
- 提供链接发起Servlet请求(a,form,img……)
Controller
接收用户的请求:(req:请求参数、Session信息……)
交给业务层处理相应的代码
控制视图的跳转
登录--->接收用户的登录请求登录--->处理用户的请求(获取用户登录的参数,username,password)--->交给业务层处理登录业务(判断用户名密码是否正确:事务)--->Dao层查询用户名和密码是否正确--->数据库
11、Filter(重点)
Filter:过滤器,用来过滤网站的数据;
- 处理中文乱码
- 登录验证……
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd"><modelVersion>4.0.0</modelVersion><groupId>com.kuang</groupId><artifactId>javaweb-filter</artifactId><version>1.0-SNAPSHOT</version><dependencies><!--Servlet依赖--><dependency><groupId>javax.servlet</groupId><artifactId>servlet-api</artifactId><version>2.5</version></dependency><!--JSP依赖--><dependency><groupId>javax.servlet.jsp</groupId><artifactId>javax.servlet.jsp-api</artifactId><version>2.3.3</version></dependency><!--JSTL表达式依赖--><dependency><groupId>jstl</groupId><artifactId>jstl</artifactId><version>1.2</version></dependency><!--standard标签库--><dependency><groupId>taglibs</groupId><artifactId>standard</artifactId><version>1.1.2</version></dependency><!--连接数据库--><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version></dependency></dependencies>
</project>
Filter开发步骤:
导包
编写过滤器
导包不要导错
实现Filter接口,重写对应的方法即可
public class CharacterEncodingFilter implements Filter {// 初始化:web服务器启动,就已经初始化了,随时等待过滤对象出现public void init(FilterConfig filterConfig) throws ServletException {System.out.println("CharacterEncodingFilter初始化...");}// chain:链/** 1. 过滤中的所有代码,在过滤特定请求的时候都会执行* 2. 必须要让过滤器继续通行* chain.doFilter(request,response);* */public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {request.setCharacterEncoding("utf-8");response.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=UTF-8");System.out.println("CharacterEncodingFilter执行前");chain.doFilter(request,response); // 让我们的请求继续走,如果不写,程序到这里就被拦截停止!System.out.println("CharacterEncodingFilter执行后");}// 销毁:web服务器关闭的时候,过滤器会销毁public void destroy() {System.out.println("CharacterEncodingFilter销毁...");} }
在web.xml中配置Filter
</filter><filter-mapping><filter-name>CharacterEncodingFilter</filter-name><!--只要是/servlet的任何请求,都会经过这个过滤器--><url-pattern>/servlet/*</url-pattern></filter-mapping>
12、监听器
实现一个监听器的接口
编写一个监听器
实现监听器的接口
// 统计网站在线人数:统计session public class OnlineCountListener implements HttpSessionListener {// 创建session监听// 一旦创建session,就会触发一次这个事件public void sessionCreated(HttpSessionEvent se) {ServletContext ctx = se.getSession().getServletContext();System.out.println(se.getSession().getId());Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");if (onlineCount == null) {onlineCount = new Integer(1);} else {int count = onlineCount.intValue();onlineCount = new Integer(count + 1);}ctx.setAttribute("OnlineCount",onlineCount);}// 销毁session监听// 一旦销毁session,就会触发一次这个事件public void sessionDestroyed(HttpSessionEvent se) {ServletContext ctx = se.getSession().getServletContext();Integer onlineCount = (Integer) ctx.getAttribute("OnlineCount");if (onlineCount == null) {onlineCount = new Integer(0);} else {int count = onlineCount.intValue();onlineCount = new Integer(count - 1);}ctx.setAttribute("OnlineCount",onlineCount);}/** session销毁* 1.手动销毁 se.getSession().invalidate();* 2.自动销毁* <session-config><session-timeout>1</session-timeout></session-config>* */ }
web.xml中注册监听器
<!--注册监听器--> <listener><listener-class>com.kuang.listener.OnlineCountListener</listener-class> </listener>
看情况是否使用!
13、 过滤器、监听器常见应用
监听器:GUI编程中经常使用
public class TestPanel {public static void main(String[] args) {Frame frame = new Frame("中国必胜!"); // 新建一个窗体Panel panel = new Panel(null); // 面板frame.setLayout(null); // 设置窗体的布局frame.setBounds(300,300,500,500);frame.setBackground(new Color(0,0,246)); // 设置背景颜色panel.setBounds(50,50,300,300);panel.setBackground(new Color(0,246,0)); // 设置背景颜色frame.add(panel);frame.setVisible(true);// 监听事件,监听关闭事件frame.addWindowListener(new WindowListener() {public void windowOpened(WindowEvent e) {System.out.println("打开");}public void windowClosing(WindowEvent e) {System.out.println("关闭ing");System.exit(0);}public void windowClosed(WindowEvent e) {System.out.println("关闭ed");}public void windowIconified(WindowEvent e) {}public void windowDeiconified(WindowEvent e) {}public void windowActivated(WindowEvent e) {System.out.println("激活");}public void windowDeactivated(WindowEvent e) {System.out.println("未激活");}});}
}
为避免new WindowListener()
要重写大部分放方法,可以使用WindowListener
的实现类WindowAdapter
,选择要重写的方法即可!
// 监听事件,监听关闭事件frame.addWindowListener(new WindowAdapter() {@Overridepublic void windowClosing(WindowEvent e) {super.windowClosing(e);}});
用户登录之后才能进入主页!用户注销后就不能进入主页了!
- 用户登录之后,向Session中放入用户的数据
- 进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现
public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws IOException, ServletException {HttpServletRequest request = (HttpServletRequest) req;HttpServletResponse response = (HttpServletResponse) resp;//Object userSession = request.getSession().getAttribute("USER_SESSION");if (request.getSession().getAttribute(Constant.USER_SESSION) == null) {response.sendRedirect("/error.jsp");}chain.doFilter(request,response);
}
14、JDBC
需要jar包的支持:
- java.sql
- javax.sql
- mysql-connector-java……连接驱动(必须要导入)
实验环境搭建:
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,'jackwon','123456','wonjack@166.com','2020-2-2');
INSERT INTO users(id,`name`,`password`,`email`,`birthday`) VALUES(2,'李四','123456','ls@166.com','2021-1-1');
INSERT INTO users(id,`name`,`password`,`email`,`birthday`) VALUES(3,'张三','123456','zs@166.com','2022-3-3');
导入数据库依赖
<!--mysql的驱动-->
<dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.47</version>
</dependency>
IDEA中连接数据库
JDBC固定步骤
- 加载驱动
- 连接数据库,connection代表数据库
- 向数据库发送SQL的对象Statement:DRUD
- 编写SQL(根据业务,不同的SQL)
- 执行SQL
- 关闭连接
public class TestJdbc {public static void main(String[] args) throws ClassNotFoundException, SQLException {// 配置信息// 解决中文乱码问题String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";String username = "root";String password = "123456";// 1.加载驱动Class.forName("com.mysql.jdbc.Driver");// 2.连接数据库,代表数据库Connection connection = DriverManager.getConnection(url, username, password);// 3.向数据库发送SQL对象 Statement:CRUDStatement statement = connection.createStatement();// 4.编写SQLString sql = "select * from users";/*String sql = "DELETE FROM users WHERE id = 2";// 受影响的行数,增删改都是用executeUpdateint i = statement.executeUpdate(sql);*/// 5.执行查询SQL,返回一个ResultSet:结果集ResultSet rs = statement.executeQuery(sql);while (rs.next()) {System.out.println("id=" + rs.getObject("id") );System.out.println("name=" + rs.getObject("name") );System.out.println("password=" + rs.getObject("password") );System.out.println("email=" + rs.getObject("email") );System.out.println("birthday=" + rs.getObject("birthday") );}// 6.关闭连接,释放资源(一定要做)先开后关rs.close();connection.close();}
}
预编译SQL
public class TestJDBC2 {public static void main(String[] args) throws ClassNotFoundException, SQLException {// 配置信息// 解决中文乱码问题String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";String username = "root";String password = "123456";// 1.加载驱动Class.forName("com.mysql.jdbc.Driver");// 2.连接数据库,代表数据库Connection connection = DriverManager.getConnection(url, username, password);// 3.编写SQLString sql = "insert into users(id, name, password, email, birthday) values(?,?,?,?,?)";// 4.预编译PreparedStatement preparedStatement = connection.prepareStatement(sql);preparedStatement.setInt(1,4); // 给第一个占位符 ? 的值赋值为4;preparedStatement.setString(2,"王老五"); // 给第二个占位符 ? 的值赋值为王老五;preparedStatement.setString(3,"88888888"); // 给第三个占位符 ? 的值赋值为88888888;preparedStatement.setString(4,"8888@88hua.com"); // 给第四个占位符 ? 的值赋值为8888@88hua.com;preparedStatement.setDate(5,new Date(new java.util.Date().getTime())); // 给第五个占位符 ? 的值赋值为new Date(new java.util.Date().getTime());// 5.执行SQLint i = preparedStatement.executeUpdate();if (i > 0) {System.out.println("插入成功!");}// 6.关闭连接,释放资源(一定要做)先开后关preparedStatement.close();connection.close();}
}
事务
要么都成功,要么都失败!
ACID原则:保证数据的安全。
开启事务
事务提交 commit()
事务回滚 rollback()
关闭事务转账:
A:1000
B:1000A(900) --100--> B(1100)
Junit单元测试
依赖:
<!--单元测试-->
<dependency><groupId>junit</groupId><artifactId>junit</artifactId><version>4.12</version>
</dependency>
简单实用
@Test注解只有在方法上有效,只要加了这个注解的方法,就可以直接运行!
@Test
public void test() {System.out.println("Hello");
}
失败的时候是红色的:
搭建一个环境:
public class TestJDBC3 {@Testpublic void test() {Connection connection = null; // 提升作用域try {// 配置信息// 解决中文乱码问题String url = "jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";String username = "root";String password = "123456";// 1.加载驱动Class.forName("com.mysql.jdbc.Driver");// 2.连接数据库,代表数据库connection = DriverManager.getConnection(url, username, password);// 3.通知数据库开启事务connection.setAutoCommit(false);String sql = "update account set money = money-100 where name = 'A'";connection.prepareStatement(sql).executeUpdate();// 制造错误int i = 1/0;String sql2 = "update account set money = money+100 where name = 'B'";connection.prepareStatement(sql2).executeUpdate();connection.commit(); // 以上两条SQL都执行成功了,就提交事务!System.out.println("success");} catch (Exception e) {try {// 如果出现异常,就通知数据库回滚事务connection.rollback();} catch (SQLException ex) {ex.printStackTrace();}e.printStackTrace();} finally {try {connection.close();} catch (SQLException e) {e.printStackTrace();}}}
}
JavaWeb-03相关推荐
- JavaWeb -03 JavaScript基础
提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档 文章目录 1.JavaScript介绍 1.1 JavaScript简介 1.2 JavaScript发展史 1.3 JavaScri ...
- javaweb(03) jQuery学习笔记
javaweb(03) jQuery学习笔记 jQuery介绍 什么是jQuery jQuery,顾名思义,也就是 JavaScript 和查询(Query),它就是辅助 JavaScript 开发的 ...
- docker生成tomcat镜像
应用场景 有时候docker公共镜像库中下载下来的镜像,可能不是自己想要的,没办法,自己也可以制作一个自己想要的镜像,然后发布到公共资源镜像中,也可以保存到私有仓库中,以防后期自己也需要使用. 操作步 ...
- 相关sql语句的练习
第1题 /* 1.数据库操作题 Student(Sno,Sname,Sage,Ssex) 学生表 Sno:学号:Sname:学生姓名:Sage:学生年龄:Ssex:学生性别 Course(Cno,Cn ...
- JavaWeb黑马旅游网-学习笔记03【登陆和退出功能】
Java后端 学习路线 笔记汇总表[黑马程序员] JavaWeb黑马旅游网-学习笔记01[准备工作] JavaWeb黑马旅游网-学习笔记02[注册功能] JavaWeb黑马旅游网-学习笔记03[登陆和 ...
- 崔希凡JavaWeb笔记day28(JavaWeb完毕)(期末,暂停更新)(2016年11月16日12:24:03)
终于在今天把JavaWeb课程学完,下一个目标就是框架了.不过在此之前,有实验,有备考,所以暂停学习框架以及更新. 下面是最后一day的笔记 链接:http://pan.baidu.com/s/1bo ...
- 【JavaWeb】火车票管理系统 (三)用户登录-03
一包烟一瓶酒一个bug改一天 aaaaaaaaaaaaa 改好了呜呜呜好多bug 就是导入jar包的时候要注意和你自己下载的mysql的版本号要一致,6.0以上的要加com.mysql.cj.jdbc ...
- Java-Web总结03
*1 dom4j解析器 1)CRUD的含义:CreateReadUpdateDelete增删查改 2)XML解析器有二类,分别是DOM和SAX. a)DOM一次性将整个XML文件读到内存,形成一个倒状 ...
- 学习笔记(03):JavaWeb基础核心技术-4. 佟刚_JavaWEB_第一个 Servlet 程序
立即学习:https://edu.csdn.net/course/play/1060/15785?utm_source=blogtoedu 1.创建一个java类 2. 写一个实现其中的方法 3.配 ...
- 旺旺老师JavaWeb视频(03) Tomcat
视频地址:http://v.youku.com/v_show/id_XNjcxNzU0MDMy.html?f=21753083 从server.xml中配置服务器端口号 从tomcat-users中配 ...
最新文章
- Oracle常用傻瓜问题1000问
- 下次迟到的借口有了!牛津大学发现时钟越准确,产生的熵越高
- windbg+VM 设置内核调试环境(双机调试)
- 栈 - 关于出栈序列,判断合法的出栈序列
- Appium进行iOS自动化测试时遇到的问题及解决办法
- cad lisp 背景遮罩_给文字批量添加边界偏移因子为1.1(或其他值)的背景遮罩的源程序(有详细注解)...
- 【转】程序员该做的事 - 每天、每周、每月
- POJ3398 Perfect Service
- mysql 代替分号_除了使用分号(;)终止符之外,还有其他可执行MySQL查询的内置命令吗?...
- NodeJS仿WebApi路由
- 微信小程序-强制手机端更新
- python移动文件(非文件夹)
- 浅谈智能客服机器人的产品设计
- 新版win10的恢复语言栏设置
- 共享充电宝之争:胜于专利,败于骂街 | 一点财经
- 最佳免费Android应用程序以及如何自行创建
- python参数内存地址
- 万级送风天花工作原理以及操作方法
- 【翻译】利用加速度求解位置的算法——三轴传感器
- 史上最全Hashmap面试总结,51道附带答案,持续更新中...