文章目录
Cookie,Session,JSP
会话
会话:打开一个浏览器,点击了很多超链接,访问多个web资源,关闭浏览器,这个过程可称之为会话
有会话状态:一个同学来过教室,下次再来教室,我们会自动这个同学,曾经来过,称之为有会话状态。
客户端
服务器
1.服务器给客户端一个信件,客户端下次访问服务器带上信件就可以了;cookie
2.服务器登记你来过了,下次你来的时候我来匹配你;seesion
保存会话的两种技术
- cookie
- 客户端技术(响应,请求)
- session
- 服务器技术,利用这个技术,可以保存用户的会话信息?我们可以把信息或者数据放在Session中!
- 常见:网站登录之后,你下次不用再登录了,第二次访问直接就上去了!
- 以后遇到乱码问题
编码:URLEncoder.encode(“某某”,“utf-8”);
解码:URLDecoder.encode(cookie.getValue(),“utf-8”); - 请求响应信息
req.setCharacterEncoding(“utf-8”);
resp.setCharacterEncoding(“utf-8”);
Cookie
1.从请求中拿到cookie信息
2.服务器响应给客户端cookie
Cookie[] cookies = req.getCookies();//返回数组可能有多个数组
cookie.getName()//获得cookie中的key
cookie.getValue()//获得cookie中的值
new Cookie(“lastLoginTime”,System.currentTimeMillis()+“”);//新建一个cookie
cookie.setMaxAge(246060);//设置cookie的有效期,一天
resp.addCookie(cookie);//响应给客户端
cookie:一般会保存在本地的用户目录下appdate
- 一个Cookie只能保存一个信息
- 一个web站点可以给浏览器发送多个cookie,最多存放20个cookie;
- Cookie大小有限制4kb
- 300个cookie浏览器上限
删除Cookie - 不设置有效期,关闭浏览器,自动失效
- 设置有效期时间为0;
cookie.setMaxAge(0);
public class CookieDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
PrintWriter out = resp.getWriter();
//Cookie,服务器端从客户端获取;
Cookie[] cookies = req.getCookies();//返回数组可能有多个数组
if (cookies!=null){
out.write("你上一次访问的时间是");
for (int i=0;i<cookies.length;i++)
{
Cookie cookie = cookies[i];
if (cookie.getName().equals("lastLoginTime")){
long l = Long.parseLong(cookie.getValue());
Date data = new Date(l);
out.write(data.toLocaleString());
}
}
}else {
out.write("你是第一次访问本站");
}
//服务器给客户端响应一个cookie
Cookie cookie = new Cookie("lastLoginTime",System.currentTimeMillis()+"");
cookie.setMaxAge(24*60*60);//设置cookie的有效期,一天
resp.addCookie(cookie);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
Session(重点)
- 服务器会给每一个用户(浏览器)创建一个Session对象;
- 一个Session独占一个浏览器,只要浏览器没有关闭,这个Session就存在;
- 用户登录以后,整个浏览器它都可以访问;
- 保存用户的信息,保存购物车的信息…
Session和Cookie的区别
- Cookie是把用户的数据写给用户浏览器,浏览器保存(可以保存多个)
- Session把用户的数据写到用户独占Session中,服务器端保存(保存重要的信息,减少服务器资源的浪费)
- Session对象由服务器创建;
使用场景:
- 保存一个登陆用户的信息;
- 购物车信息;
- 在整个网站中经常会使用的数据,我们将它保存在Session中;
使用Session:
写入Session的信息
public class SessionDemo01 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
//给Session中存点东西
session.setAttribute("name",new Students(123456,"启田","信管182"));//存入一个对象
//获取Session的ID
String id = session.getId();
//判断Session是不是新建的
if(session.isNew()){
resp.getWriter().write("session创建成功,ID"+id);
}else {
resp.getWriter().write("session在服务器中已经存在了,ID"+id);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
读取写入Session的信息
public class SessionDemo02 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//解决乱码问题
req.setCharacterEncoding("utf-8");
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html;charset=utf-8");
//得到Session
HttpSession session = req.getSession();
Students name = (Students)session.getAttribute("name");
resp.getWriter().write(name.toString());
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
手动注销Session
public class SessionDemo03 extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("name");
//手动注销Session
session.invalidate();
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}
web.xml配置里设置Session过期信息
<!--设置session失效时间-->
<session-config>
<!--设置15分钟后自动失效,以分钟为单位-->
<session-timeout>15</session-timeout>
</session-config>
JSP(java Server Pages)
Java Server Pages :java服务器端页面,也和Servlet一样,用于动态Web技术!
我的电脑路径:
C:\Users\AV\AppData\Local\JetBrains\IntelliJIdea2020.3\tomcat\59b8af8f-1f8b-4bab-a032-7feff1668832\work\Catalina\localhost\ROOT\org\apache\jsp
发现页面变成了java程序!
浏览器向服务器发送请求,不管访问什么资源,其实都是在访问Servlet!
JSP最终也会被转换成为一个JAVA类!;
JSP本质上就是一个Servlet
JSP原理
:出自 狂神说 的javaWeb视频
在JSP页面中;
只要是JAVA代码就会原封不动的输出;
如果是HTML代码,就会被转换为
out.write(“name:”);
这样的格式输出到前端!
JSP基础语法
Maven导入依赖
<dependencies>
<!--servlet依赖-->
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!--JSP依赖-->
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp/javax.servlet.jsp-api -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
</dependency>
<!--JSTL表达式的依赖-->
<!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl-api -->
<dependency>
<groupId>javax.servlet.jsp.jstl</groupId>
<artifactId>jstl-api</artifactId>
<version>1.2</version>
</dependency>
<!--standard标签库-->
<!-- https://mvnrepository.com/artifact/org.apache.taglibs/taglibs-standard-impl -->
<dependency>
<groupId>org.apache.taglibs</groupId>
<artifactId>taglibs-standard-impl</artifactId>
<version>1.2.5</version>
<scope>runtime</scope>
</dependency>
</dependencies>
语法
JSP作为java技术的一种应用,它拥有一些自己扩充的语法(了解,知道即可!),java所有的语法都支持!
JSP表达式
<%= 变量或者表达式%>输出到客户端
<%= new java.util.Date()%>
JSP脚本片段
<%
int sum=0;
for (int i=1;i<=100;i++){
sum+=i;
}
out.print("<h1>Sum="+sum+"</h1>");
%>
套娃
可以相互嵌套:例子
<body>
<%
int sum=0;
for (int i=1;i<=100;i++){
%>
<h1>Hellojava <%=i%> </h1>
<%
sum+=i;
}
out.print("<p>Sum="+sum+"</p>");
%>
</body>
JSP声明
<%!
static {
System.out.println("声明");
}
private int a=0;
public void tian(){
System.out.println("进入了tian方法");
}
%>
JSP声明:会被编译到生成JSP的java类中!其他的,就会被生成到_jspService方法中!
在JSP中嵌入java代码即可!
EL表达式
用法:${java代码}
JSP指令
<%--定制错误页面--%>
<%@ page errorPage="error.jsp"%>
<%@ include file="相同元素的路径"%>
web.xml
<error-page>
<error-code>500</error-code>
<location>/error.jsp</location>//这个路径相对于生成war包的路径决定的
</error-page>
JSP标签
<jsp:include page=“error.jsp”></jsp:include>
九大内置对象
- PageContext 存东西
- Request 存东西
- Response
- Session 存东西
- Application(ServletContext) 存东西
- config(ServletConfig)
- out
- page
- excepetion
JSP标签,JSTL标签,EL标签
JSTL表达式:菜鸟教程里有使用方法
重要:
JavaBean
AJAX请求:
MVC三层架构
- 什么是MVC: Model view Controller 模型、视图、控制器
早些年的:
用户直接访问控制层,控制层就可以直接操作数据库;
servlet–CRUD–>数据库
弊端:程序十分臃肿,不利于维护
servlet的代码中:处理请求、响应、视图跳转、处理JDBC、处理业务代码、处理逻辑代码
架构:没有什么是加一层解决不了的!
程序猿调用
↑
JDBC (实现该接口)
↑
Mysql Oracle SqlServer …(不同厂商)
MVC三层架构
Model
- 业务处理 :业务逻辑(Service)
- 数据持久层:CRUD (Dao - 数据持久化对象)
View
- 展示数据
- 提供链接发起Servlet请求 (a,form,img…)
Controller (Servlet)
-
接收用户的请求 :(req:请求参数、Session信息….)
-
交给业务层处理对应的代码
-
控制视图的跳转
登录—>接收用户的登录请求—>处理用户的请求(获取用户登录的参数,username,password)---->交给业务层处理登录业务(判断用户名密码是否正确:事务)—>Dao层查询用户名和密码是否正确–>数据库
Filter
比如 Shiro安全框架技术就是用Filter来实现的
Filter:过滤器 ,用来过滤网站的数据;
- 处理中文乱码
- 登录验证….
(比如用来过滤网上骂人的话)
Filter开发步骤:
1.导包
2.编写过滤器
1.导包不要错 (注意)
实现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-name>CharacterEncodingFilter</filter-name>
<filter-class>com.kuang.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<!--只要是 /servlet的任何请求,会经过这个过滤器-->
<url-pattern>/servlet/*</url-pattern>
<!--<url-pattern>/*</url-pattern>-->
<!-- 别偷懒写个 /* -->
</filter-mapping>
监听器(listener)
实现一个监听器的接口;(有n种监听器)
- 编写一个监听器
实现监听器的接口…
依赖的jar包
//统计网站在线人数 : 统计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. 手动销毁 getSession().invalidate();
2. 自动销毁
*/
}
web.xml中注册监听器
<!--注册监听器-->
<listener>
<listener-class>com.kuang.listener.OnlineCountListener</listener-class>
</listener>
看情况是否使用!
过滤器、监听器常见应用
监听器: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,255)); //设置背景颜色
panel.setBounds(50,50,300,300);
panel.setBackground(new Color(0,255,0)); //设置背景颜色
frame.add(panel);
frame.setVisible(true);
//监听事件,监听关闭事件
frame.addWindowListener(new WindowAdapter() {
@Override
public void windowClosing(WindowEvent e) {
super.windowClosing(e);
}
});
}
}
用户登录之后才能进入主页!用户注销后就不能进入主页了!
-
用户登录之后,向Sesison中放入用户的数据
-
进入主页的时候要判断用户是否已经登录;要求:在过滤器中实现!
HttpServletRequest request = (HttpServletRequest) req;
HttpServletResponse response = (HttpServletResponse) resp;
if (request.getSession().getAttribute(Constant.USER_SESSION)==null){
response.sendRedirect("/error.jsp");
}
chain.doFilter(request,response);
JDBC
什么是JDBC : Java连接数据库!
需要jar包的支持:
- java.sql
- javax.sql
- mysql-conneter-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,'张三','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;
导入数据库依赖
<!--mysql的驱动-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.47</version>
</dependency>
IDEA中连接数据库:
JDBC 固定步骤:
加载驱动
1.连接数据库,代表数据库
2.向数据库发送SQL的对象Statement : CRUD
3.编写SQL (根据业务,不同的SQL)
4.执行SQL
5.关闭连接(先开的后关)
public class TestJdbc {
public static void main(String[] args) throws ClassNotFoundException, SQLException {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
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,PreparedStatement : CRUD
Statement statement = connection.createStatement();
//4.编写SQL
String sql = "select * from users";
//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();
statement.close();
connection.close();
}
}
预编译SQL
public class TestJDBC2 {
public static void main(String[] args) throws Exception {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
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
String sql = "insert into users(id, name, password, email, birthday) values (?,?,?,?,?);";
//4.预编译
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setInt(1,2);//给第一个占位符? 的值赋值为1;
preparedStatement.setString(2,"狂神说Java");//给第二个占位符? 的值赋值为狂神说Java;
preparedStatement.setString(3,"123456");//给第三个占位符? 的值赋值为123456;
preparedStatement.setString(4,"24736743@qq.com");//给第四个占位符? 的值赋值为1;
preparedStatement.setDate(5,new Date(new java.util.Date().getTime()));//给第五个占位符? 的值赋值为new Date(new java.util.Date().getTime());
//5.执行SQL
int i = preparedStatement.executeUpdate();
if (i>0){
System.out.println("插入成功@");
}
//6.关闭连接,释放资源(一定要做) 先开后关
preparedStatement.close();
connection.close();
}
}
事务
要么都成功,要么都失败!
ACID原则:保证数据的安全。
开启事务
事务提交 commit()
事务回滚 rollback()
关闭事务
转账:
A:1000
B:1000
A(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");
}
失败的时候是红色:
搭建一个环境
CREATE TABLE account(
id INT PRIMARY KEY AUTO_INCREMENT,
`name` VARCHAR(40),
money FLOAT
);
INSERT INTO account(`name`,money) VALUES('A',1000);
INSERT INTO account(`name`,money) VALUES('B',1000);
INSERT INTO account(`name`,money) VALUES('C',1000);
@Test
public void test() {
//配置信息
//useUnicode=true&characterEncoding=utf-8 解决中文乱码
String url="jdbc:mysql://localhost:3306/jdbc?useUnicode=true&characterEncoding=utf-8";
String username = "root";
String password = "123456";
Connection connection = null;
//1.加载驱动
try {
Class.forName("com.mysql.jdbc.Driver");
//2.连接数据库,代表数据库
connection = DriverManager.getConnection(url, username, password);
//3.通知数据库开启事务,false 开启
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 e1) {
e1.printStackTrace();
}
e.printStackTrace();
}finally {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}