javaWeb随笔(2)

前言

javaWeb基础学习

正文

Demo1

Demo1

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
package com.c0okb.test2;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.xml.crypto.Data;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;

public class CookieDemo extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
PrintWriter out = resp.getWriter();
Cookie[] cookies = req.getCookies();//获取该请求的cookie

if(cookies != null){
out.write("你上一次访问的时间是:");
for (int i = 0; i < cookies.length; i++) {//遍历cookie
Cookie cookie = cookies[i];
if(cookie.getName().equals("lastLoginTime")){
long LT = Long.parseLong(cookie.getValue());//读取cookie的值
Date date = new Date(LT);
out.write(date.toString());
}
}
}else{
out.write("这是第一次访问本站");
}

Cookie cookie = new Cookie("lastLoginTime", System.currentTimeMillis()+"");//设置cookie
cookie.setMaxAge(24*60*60);//设置cookie的最大存活时间

resp.addCookie(cookie);//添加cookie
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doPost(req, resp);
}
}

通过cookie获取上一次访问该网页的时间

Demo2

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
package com.c0okb.test2;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class CookieDemo2 extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
Cookie cookie1 = new Cookie("lastLoginTime", System.currentTimeMillis() + "");
cookie1.setMaxAge(0);
resp.addCookie(cookie1);

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

设置存活时间为0,可以用于刷新cookie

Demo3

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
package com.c0okb.test2;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.Date;

public class CookieDemo3 extends HttpServlet {

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
System.out.println("进入该方法");
resp.setContentType("text/html");
resp.setCharacterEncoding("utf-8");
Cookie cookie1 = new Cookie("name", URLEncoder.encode("饼干屑","utf-8"));
cookie1.setMaxAge(24*60*60);
resp.addCookie(cookie1);
PrintWriter out = resp.getWriter();
Cookie[] cookies = req.getCookies();
for (int i = 0; i < cookies.length; i++) {
Cookie cookie = cookies[i];
System.out.println(cookie.getName());
if(cookie.getName().equals("name")){
out.write(URLDecoder.decode(cookie.getValue()));
}
}

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

当cookie的值为中文时,使用

1
2
URLEncoder.encode("饼干屑","utf-8")
URLDecoder.decode(cookie.getValue())

进行合理编码

SESSION(重点)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
//Person类
package com.c0okb.test2;

public class Person {
private String name;
private int age;

public Person(String name) {
this.name = name;
System.out.println(name);
}

public Person() {
}

public int getAge() {
return age;
}

public void setAge(int age) {
this.age = age;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name;
}
}

对Session进行操作

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
package com.c0okb.test2;

import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class SessionTest extends HttpServlet {


@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.setCharacterEncoding("utf-8");
resp.setContentType("text/html");
req.setCharacterEncoding("utf-8");

//获取Session
HttpSession session = req.getSession();

//给Session存东西
session.setAttribute("name",new Person("c0okb"));

//获取Session的ID
String sessionId = session.getId();

//判断Session是否已经创建
if(session.isNew()){
resp.getWriter().write("session创建成功,ID:"+sessionId);
}else{
resp.getWriter().write("session已经在服务器中存在. ID:"+sessionId);
}

}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

删除Session

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
package com.c0okb.test2;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

public class SessionDelete extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
HttpSession session = req.getSession();
session.removeAttribute("name");
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

JSP原理

image-20201222103702852

1
2
3
4
5
1.JSP(Java Server Page): Java的服务页面,Java动态网页.
JSP本质就是Servlet
服务器会解析请求中是否含有.jsp文件
如果有,则将其编译为java文件
再将java文件编译为class文件,供浏览器访问

maven需要安装的依赖

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
<!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>4.0.1</version>
<scope>provided</scope>
</dependency>
<!-- 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>
<scope>provided</scope>
</dependency>
<!-- 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>
<!-- https://mvnrepository.com/artifact/taglibs/standard -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>

JSP的基础语法与指令

JSP的基本语法

1
2
3
4
5
6
7
8
9
10
JSP语法:
1.JSP的注释:注释Java脚本代码
<%--注释--%>
2.JSP的Java脚本表达式:输出数据到页面上
<%=代买%> (实际上就是调用输出流打印到页面上) out.print(表达式);
3.JSP中的Java脚本片段:(实际开发中,应做到JSP中不能出现一行Java脚本片段):书写Java代码逻辑
<%代码%>
原理:其中的语句会原封不动的被服务器翻译到对应的Servlet的_jspService方法中。
4.JSP的声明::定义类的成员
<%!代码%>

JSP三大指令

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
1.特点
1.并不向客户端产生任何输出,
2.指令在JSP整个文件范围内有效
3.为翻译阶段提供了全局信息
2.指令语法格式: <%指令名称 属性名='属性值' 属性名='属性值'....%>
3.page指令:表示JSP的相关配置
<%page contentType='text/html' charset='UTF-8' language='java'%>
contentType:表示文件的MIME类型
charset:表示文档的字符集
language:表示JSP文档编写的脚本语言
import:用于导入JSP脚本中使用到的类,等价于Java代码中的: import 类的全限定名;
errorPage:如果服务器发生错误,会自动跳转到指定页面
isErrorPage:判断页面是否为错误页面,
true:是,则可以判断内置对象为Exception
false:不是,默认值,不可以使用

4.include指令:
1.静态包含:使用JSP的include指令
<%@include file='被包含的文件'%>
特点:
在编译阶段就将多个JSP文件,合并成一个java类
2.动态包含:使用JSP的动作指令
<%jsp: include='被包含的文件'%>
特点:
把每一个JSP编译成Servlet类,在编译过程中,动态的合并在一起,最终得到多个java类(动态包含会包含多个java类)

3.动态包含和静态包含的选择:
如果在包含的时候,需要传递数据,此时只能使用动态包含.(
如果被包含的页面如果是静态页面,那么使用静态包含
如果被包含的如果是动态页面,那么使用动态包含
4.注意:在实际开始中通常将被包含的jsp页面的后缀名设置为jspf

JSP九大内置对象

1
2
3
4
5
6
7
8
9
PageContext //保存东西
Request //保存东西
Response
Session //保存东西
Application [ServletContext] //保存东西
config [ServletConfig]
out
page
exception

image-20201223210220838

Filter 过滤器

原理图:

image-20201226210439851

PS:导包的时候一定不能导错包 java.servelt.Filter

编写一个过滤器用于解决中文乱码问题

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
package com.c0okb.filter;

import javax.servlet.*;
import java.io.IOException;

public class Encoding implements Filter {
@Override
public void init(FilterConfig filterConfig) throws ServletException {
System.out.println("过滤器启动中..............");
}

@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html");

System.out.println("过滤器运行中.....");
chain.doFilter(request,response);//链
System.out.println("过滤器结束运行");

}

@Override
public void destroy() {
System.out.println("过滤器销毁中..............");
}
}

其中很重要的代码

1
chain.doFilter(request,response);//链

image-20201226215332953

编写一个测试类

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
package com.c0okb.show;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class show extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
resp.getWriter().write("我是小吴");
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req, resp);
}
}

注册Servlet

1
2
3
4
5
6
7
8
<filter>
<filter-name>Encoding</filter-name>
<filter-class>com.c0okb.filter.Encoding</filter-class>
</filter>
<filter-mapping>
<filter-name>Encoding</filter-name>
<url-pattern>/ServletShow/*</url-pattern>
</filter-mapping>

这时注册的Servlet说明该过滤器适用于/ServletShow下的文件

image-20201226213838017

对比测试

image-20201226214710714

Listener 监听器

编写监听器-用于记录网站在线人数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
package com.c0okb.filter;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.*;
import java.io.IOException;

public class OnlineAccount extends HttpServlet implements HttpSessionListener {

@Override
public void sessionCreated(HttpSessionEvent se) {
ServletContext servletContext = se.getSession().getServletContext();
Integer onlineAccount = (Integer) servletContext.getAttribute("OnlineAccount");
if(onlineAccount == null){
onlineAccount = new Integer(1);
}else {
int account = onlineAccount.intValue();
onlineAccount = new Integer(account+1);
}
servletContext.setAttribute("OnlineAccount",onlineAccount);
}



@Override
public void sessionDestroyed(HttpSessionEvent se) {
ServletContext servletContext = se.getSession().getServletContext();
Integer onlineAccount = (Integer) servletContext.getAttribute("OnlineAccount");
if(onlineAccount == null){
onlineAccount = new Integer(0);
}else {
int account = onlineAccount.intValue();
onlineAccount = new Integer(account-1);
}
servletContext.setAttribute("OnlineAccount",onlineAccount);
}
}

index.jsp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<%--
Created by IntelliJ IDEA.
User: cookie
Date: 2020/12/26
Time: 21:09
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>$Title$</title>
</head>
<body>
<h1>
当前在线的人数是:<%=this.getServletConfig().getServletContext().getAttribute("OnlineAccount")%>
</h1>
</body>
</html>

注册servlet

1
2
3
<listener>
<listener-class>com.c0okb.filter.OnlineAccount</listener-class>
</listener>

image-20201226225635587

用户登陆与用户注销-Filter拦截判断

用户登录后才能进入主页,用户注销后就不能进入主页

JDBC事务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.Sql.Demo;

import java.sql.*;



public class JDBCTest {

public static void main(String[] args) throws ClassNotFoundException, SQLException {
String url = "jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=UTF8";
String username = "root";
String password = "root";

//1.加载驱动
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);

String sql = "SELECT username\n" +
"FROM\n" +
"users\n" +
"where id=?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);

preparedStatement.setString(1,"1");

ResultSet rs = preparedStatement.executeQuery();


while (rs.next()){
System.out.println(rs.getString("username"));
}

//关闭数据库池,先开后关
rs.close();
preparedStatement.close();
connection.close();
}

}

InnoDB的存储引擎才支持JDBC事务

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
package com.Sql.Demo;

import java.sql.*;


public class Test {

@org.junit.Test
public void test() throws SQLException, ClassNotFoundException {
String url = "jdbc:mysql://localhost:3306/security?useUnicode=true&characterEncoding=UTF8";
String username = "root";
String password = "root";
Class.forName("com.mysql.jdbc.Driver");
Connection connection = DriverManager.getConnection(url, username, password);

//1.加载驱动
try {

//2.连接数据库

//3.通知数据开启事务
connection.setAutoCommit(false);

String sql1 = "update account set money=money+10 where name='A'";

connection.prepareStatement(sql1).executeUpdate();

//int i = 1/0;

String sql2 = "update account set money=money-10 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();
}

}

}
Author: 我是小吴啦
Link: http://yoursite.com/2020/12/20/javaWeb%E9%9A%8F%E7%AC%94-2/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.