1. Java过滤机制-声明周期

images/java-web-filter-01.png

2. 第一个过滤器

1、创建一个过滤器类 ,继承自servlet下的Filter
2、重写三个方法init() doFilter() destroy()方法
(1)init()初始化:这个方法可以读取web.xml文件中的过滤器初始化参数。通过参数FilterConfig arg0可以获取更多参数
(2)doFIlter()核心:完成实际的过滤操作。当用户请求访问与过滤器【关联的URL】时,Web容器将先调用过滤器的doFilter方法,FilterChain arg2参数可以调用chain.doFilter方法,将请求传给下一个过滤器(或目标资源),或利用转发,重定向将请求转发给其他资源。
(3)web容器在消耗过滤器前调用该方法,用于释放过滤器占用的资源。(大多数情况用不到)

2.1 定义Filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
package liulx.FilterDemo;

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

public class FirstFilter implements Filter {
public void destroy() {
System.out.println("Filter Destroy");
}

public void doFilter(ServletRequest req, ServletResponse resp, FilterChain chain) throws ServletException, IOException {
System.out.println("Do filter before request");
chain.doFilter(req, resp);
System.out.println("Do filter after request");
}

public void init(FilterConfig config) throws ServletException {
System.out.println("Init First Filter");
}
}

2.2 Web.xml配置

images/java-web-filter-02.png

过滤器能够改变用户请求的Web资源,也就是能够改变用户请求的路径。
过滤器不能直接返回数据,不能直接处理用户请求。

1
2
3
4
5
6
7
8
<filter>
<filter-name>FirstFilter</filter-name>
<filter-class>liulx.FilterDemo.FirstFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>FirstFilter</filter-name>
<url-pattern>/index.jsp</url-pattern>
</filter-mapping>
Read more »

1. 获取初始化参数

1
2
3
4
5
6
7
8
9
10
<servlet>
<init-param>
<param-name>username</param-name>
<param-value>admin</param-value>
</init-param>
<init-param>
<param-name>password</param-name>
<param-value>123456</param-value>
</init-param>
</servlet>
1
2
3
在servlet的init()方法中获取初始化的值:
this.getInitParameter("username");
this.getInitParameter("password");

1. Servlet概述

jsp前身就是servlet,Servelet是在服务器上运行的小程序。
一个Servlet就是一个Java类,并且可以通过“请求-响应”编程模型来访问的这个驻留在服务器内存里的Servlet程序。

2. Tomcat容器等级

Tomcat在大多数情况下充当servlet的容器,也就是说:在写完JSP代码后进行第一次执行时,tomcat(servlet容器)先将JSP代码翻译成servlet类(java代码),然后实例化该类,再调用该类的init,service,destory等进行生命周期服务。当客户端再进行第二次访问请求时,此时就没有servlet容器的翻译这一步了,因为之前翻译的java代码会一直保存,以便于后面的访问不再进行翻译,可大大提高访问效率。所以,JSP页面在第一次被访问时,其所花费的时间是最长的。
最主要的方法就是init,service和destroy,它们是servlet对象的生存周期,当一个页面被编译成servlet类,再进行实例化后,这个页面就开始了真正的生命周期,servlet容器会先加载init方法进行初始化,初始化后才可进行接收和相应客户端的消息,之后容器会再加载service,这部分就是真正相应客户端请求的实现逻辑,它实现客户端的请求响应,然后动态生成HTML页面显示到客户端;而destory方法则是在servlet生命周期即将结束时进行的清理工作。

java-web-servlet-01

3. 手工编写第一个Servlet

  1. 继承HttpServlet
  2. 重写doGet()或者doPost():右键->source->重写
  3. 在web.xml中注册servlet

问题解析:
1、向页面输出html语言 response.setContentType("text/html;charset=utf-8");
2、在配置web.xml中

1
2
3
4
5
6
7
8
<servlet>
<servlet-name>HelloServlet</servlet-name>
<servlet-class>servlet.helloServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HelloServlet</servlet-name>
<url-pattern>/servlet/HelloServlet</url-pattern>//根目录下的路径信息
</servlet-mapping>

web.xml中Servlet的配置说明:
1、<servlet>标签中
<servlet-name>指定servlet名称,<servlet-class>指定servlet类,需要使用完整类名
2、<servlet-mapping>标签中
<servlet-name>指定servlet名称,需要与<servlet>标签中的相应servlet名称对应;
<url-pattern>指定servlet地址,在Jsp页面中使用的URL需要与相应servlet的地址对应

Read more »

1. JDBC编程步骤

加载驱动程序:

1
2
3
4
5
Class.forName(driverClass)
//加载MySql驱动
Class.forName("com.mysql.jdbc.Driver")
//加载Oracle驱动
Class.forName("oracle.jdbc.driver.OracleDriver")

获得数据库连接:

1
DriverManager.getConnection("jdbc:mysql://127.0.0.1:3306/imooc", "root", "root");

创建Statement\PreparedStatement对象:

1
2
conn.createStatement();
conn.prepareStatement(sql);

例子:

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
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

public class DbUtil {

public static final String URL = "jdbc:mysql://localhost:3306/imooc";
public static final String USER = "liulx";
public static final String PASSWORD = "123456";

public static void main(String[] args) throws Exception {
//1.加载驱动程序
Class.forName("com.mysql.jdbc.Driver");
//2. 获得数据库连接
Connection conn = DriverManager.getConnection(URL, USER, PASSWORD);
//3.操作数据库,实现增删改查
Statement stmt = conn.createStatement();
ResultSet rs = stmt.executeQuery("SELECT user_name, age FROM imooc_goddess");
//如果有数据,rs.next()返回true
while(rs.next()){
System.out.println(rs.getString("user_name")+" 年龄:"+rs.getInt("age"));
}
}
}

2. 增删改查

Read more »

1. JDBC DBHelper

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
50
51
52
53
54
55
56
57
58
59
60
package util;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBHelper {

private static final String driver = "com.mysql.jdbc.Driver"; //数据库驱动
//连接数据库的URL地址
private static final String url="jdbc:mysql://localhost:3306/shopping?useUnicode=true&characterEncoding=UTF-8";
private static final String username="root";//数据库的用户名
private static final String password="";//数据库的密码

private static Connection conn=null;

//静态代码块负责加载驱动
static
{
try
{
Class.forName(driver);
}
catch(Exception ex)
{
ex.printStackTrace();
}
}

//单例模式返回数据库连接对象
public static Connection getConnection() throws Exception
{
if(conn==null)
{
conn = DriverManager.getConnection(url, username, password);
return conn;
}
return conn;
}

public static void main(String[] args) {

try
{
Connection conn = DBHelper.getConnection();
if(conn!=null)
{
System.out.println("数据库连接正常!");
}
else
{
System.out.println("数据库连接异常!");
}
}
catch(Exception ex)
{
ex.printStackTrace();
}

}
}

2. 实体类

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
50
51
52
53
54
55
56
57
58
59
60
61
package entity;

//商品类
public class Items {

private int id; // 商品编号
private String name; // 商品名称
private String city; // 产地
private int price; // 价格
private int number; // 库存
private String picture; // 商品图片

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

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

public String getCity() {
return city;
}

public void setCity(String city) {
this.city = city;
}

public int getPrice() {
return price;
}

public void setPrice(int price) {
this.price = price;
}

public int getNumber() {
return number;
}

public void setNumber(int number) {
this.number = number;
}

public String getPicture() {
return picture;
}

public void setPicture(String picture) {
this.picture = picture;
}

}

3. DAO

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
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
package dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.ArrayList;

import util.DBHelper;

import entity.Items;

//商品的业务逻辑类
public class ItemsDAO {

// 获得所有的商品信息
public ArrayList<Items> getAllItems() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList<Items> list = new ArrayList<Items>(); // 商品集合
try {
conn = DBHelper.getConnection();
String sql = "select * from items;"; // SQL语句
stmt = conn.prepareStatement(sql);
rs = stmt.executeQuery();
while (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
list.add(item);// 把一个商品加入集合
}
return list; // 返回集合。
} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
}

}

// 根据商品编号获得商品资料
public Items getItemsById(int id) {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
conn = DBHelper.getConnection();
String sql = "select * from items where id=?;"; // SQL语句
stmt = conn.prepareStatement(sql);
stmt.setInt(1, id);
rs = stmt.executeQuery();
if (rs.next()) {
Items item = new Items();
item.setId(rs.getInt("id"));
item.setName(rs.getString("name"));
item.setCity(rs.getString("city"));
item.setNumber(rs.getInt("number"));
item.setPrice(rs.getInt("price"));
item.setPicture(rs.getString("picture"));
return item;
} else {
return null;
}

} catch (Exception ex) {
ex.printStackTrace();
return null;
} finally {
// 释放数据集对象
if (rs != null) {
try {
rs.close();
rs = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}
// 释放语句对象
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (Exception ex) {
ex.printStackTrace();
}
}

}
}
//获取最近浏览的前五条商品信息
public ArrayList<Items> getViewList(String list)
{
System.out.println("list:"+list);
ArrayList<Items> itemlist = new ArrayList<Items>();
int iCount=5; //每次返回前五条记录
if(list!=null&&list.length()>0)
{
String[] arr = list.split(",");
System.out.println("arr.length="+arr.length);
//如果商品记录大于等于5条
if(arr.length>=5)
{
for(int i=arr.length-1;i>=arr.length-iCount;i--)
{
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}
else
{
for(int i=arr.length-1;i>=0;i--)
{
itemlist.add(getItemsById(Integer.parseInt(arr[i])));
}
}
return itemlist;
}
else
{
return null;
}

}

}

4. index.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="entity.Items"%>
<%@ page import="dao.ItemsDAO"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'index.jsp' starting page</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
div{
float:left;
margin: 10px;
}
div dd{
margin:0px;
font-size:10pt;
}
div dd.dd_name
{
color:blue;
}
div dd.dd_city
{
color:#000;
}
</style>
</head>

<body>
<h1>商品展示</h1>
<hr>

<center>
<table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
<tr>
<td>

<!-- 商品循环开始 -->
<%
ItemsDAO itemsDao = new ItemsDAO();
ArrayList<Items> list = itemsDao.getAllItems();
if(list!=null&&list.size()>0)
{
for(int i=0;i<list.size();i++)
{
Items item = list.get(i);
%>
<div>
<dl>
<dt>
<a href="details.jsp?id=<%=item.getId()%>"><img src="images/<%=item.getPicture()%>" width="120" height="90" border="1"/></a>
</dt>
<dd class="dd_name"><%=item.getName() %></dd>
<dd class="dd_city">产地:<%=item.getCity() %>&nbsp;&nbsp;价格:¥ <%=item.getPrice() %></dd>
</dl>
</div>
<!-- 商品循环结束 -->

<%
}
}
%>
</td>
</tr>
</table>
</center>
</body>
</html>

5. detail.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
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%@ page import="entity.Items"%>
<%@ page import="dao.ItemsDAO"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">

<title>My JSP 'details.jsp' starting page</title>

<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
<style type="text/css">
div{
float:left;
margin-left: 30px;
margin-right:30px;
margin-top: 5px;
margin-bottom: 5px;
}
div dd{
margin:0px;
font-size:10pt;
}
div dd.dd_name
{
color:blue;
}
div dd.dd_city
{
color:#000;
}
</style>
</head>

<body>
<h1>商品详情</h1>
<hr>
<center>
<table width="750" height="60" cellpadding="0" cellspacing="0" border="0">
<tr>
<!-- 商品详情 -->
<%
ItemsDAO itemDao = new ItemsDAO();
Items item = itemDao.getItemsById(Integer.parseInt(request.getParameter("id")));
if(item!=null)
{
%>
<td width="70%" valign="top">
<table>
<tr>
<td rowspan="4"><img src="images/<%=item.getPicture()%>" width="200" height="160"/></td>
</tr>
<tr>
<td><B><%=item.getName() %></B></td>
</tr>
<tr>
<td>产地:<%=item.getCity()%></td>
</tr>
<tr>
<td>价格:<%=item.getPrice() %>¥</td>
</tr>
</table>
</td>
<%
}
%>
<%
String list ="";
//从客户端获得Cookies集合
Cookie[] cookies = request.getCookies();
//遍历这个Cookies集合
if(cookies!=null&&cookies.length>0)
{
for(Cookie c:cookies)
{
if(c.getName().equals("ListViewCookie"))
{
list = c.getValue();
}
}
}

list+=request.getParameter("id")+",";
//如果浏览记录超过1000条,清零.
String[] arr = list.split(",");
if(arr!=null&&arr.length>0)
{
if(arr.length>=1000)
{
list="";
}
}
Cookie cookie = new Cookie("ListViewCookie",list);
response.addCookie(cookie);

%>
<!-- 浏览过的商品 -->
<td width="30%" bgcolor="#EEE" align="center">
<br>
<b>您浏览过的商品</b><br>
<!-- 循环开始 -->
<%
ArrayList<Items> itemlist = itemDao.getViewList(list);
if(itemlist!=null&&itemlist.size()>0 )
{
System.out.println("itemlist.size="+itemlist.size());
for(Items i:itemlist)
{

%>
<div>
<dl>
<dt>
<a href="details.jsp?id=<%=i.getId()%>"><img src="images/<%=i.getPicture() %>" width="120" height="90" border="1"/></a>
</dt>
<dd class="dd_name"><%=i.getName() %></dd>
<dd class="dd_city">产地:<%=i.getCity() %>&nbsp;&nbsp;价格:<%=i.getPrice() %> ¥ </dd>
</dl>
</div>
<%
}
}
%>
<!-- 循环结束 -->
</td>
</tr>
</table>
</center>
</body>
</html>
Read more »

1. include指令

常用的有page、include、taglib指令这三种指令;
page:位于页面顶端,一个页面可以包含多个page指令
include:将一个外部文件嵌入jsp中,同时解析这个页面中的jsp语句。
taglib:使用标签库,自定义新的标签,在jsp中启动定制行为。

语法 <% include file="地址"%>
案例:显示当前时间的页面。
(1)写一个只输出时间的方法的date.jsp。
(2)用于显示的页面,包含<% include file="date.jsp"%>

2. include动作

  1. 是一个动作标签<jsp:xxx>
  2. 语法:<jsp:include page="URL" flush="true|false">
  • page属性:要包含的页面
  • flush属性:被包含的页面是否从缓冲区里读取

3. include指令和动作的区别

  1. 包含内容: 指令包含的是【源代码】,动作包含的是页面输出的【结果】
  2. 生成的servlet:指令会生成一个整体的Servlet;而动作会分别生成两个,即在一个Servlet中调用另一个Servlet
  3. 其他区别如图:
  4. 使用场合】:页面内容不经常变化使用include指令,页面内容经常变化使用<jsp:include>动作

images/java-web-jsp-04.jpg

4. forward指令

Read more »

1. http协议的无状态性

  1. 无状态是指,当浏览器发送请求给服务器的时候,服务器会响应。但当同一个浏览器再次发送请求时,服务器不会知道是刚才那个浏览器。
  2. 简单说,服务器【不会保存用户状态】,不会记得客户端是否访问过,所以这就是无状态协议。

2. Cookie概述

保存用户的状态的两大机制:session ,cookie

cookie作用:

  1. 对特定对象的追踪
  2. 保存用户网页浏览记录与习惯
  3. 简化登录

安全风险:容易泄露用户信息
典型应用一:判断注册用户是否已经登录网站
典型应用二:“购物车”的处理

3. JSP页面中创建和使用Cookie

  1. 创建Cookie对象:Cookie cookie = new Cookie(String key , Object value);
  2. 写入Cookie对象:response.addCookie(cookie);
  3. 读取Cookie对象:Cookie[] cookies = request.getCookies();

Cookie常用方法:

Read more »

1. jsp内置对象简介

1、JSP内置对象是Web容器创建的一组对象,【不使用new关键字】就可以使用的内置对象。
2、九大内置对象:
out,request,response,session,application(五大常用对象)
Page,pageContext,exception.config(四个不太常用对象)

2. out对象

缓冲区Buffer:就是内存的一块区域涌来保存临时数据。

out是JspWriter 的实例,是向客户端输出内容的常用对象.
常用方法:

  1. void println() 向客户端打印字符串.
  2. void clear() 清除缓冲区,在flush之后调用会抛出异常.
  3. void clearBuffer() 清除缓冲区,在flush之后调用不会抛出异常.
  4. void flush() 将缓冲区内容输出到客户端.
  5. int getBufferSize()
  6. int getRemaining()
  7. boolean isAutoFlush() 返回缓冲区满时,是自动清空还是抛出异常
  8. void close() 关闭输出流

3. Get和Post提交方式的区别

表单有两种提交方式:get与post。定义在<form action="dologin.jsp" name="loginForm" method="提交方式***"></form> 动作/名称等顺序无所谓。
1.get:以【明文】方式,通过URL提交数据,数据在URL中【可以看到】。提交数据最多不超过【2KB】。安全性较低,但效率比post方式高。适合提交数据量不大,且安全要求不高的数据:比如:搜索、查询等功能。
2.post:将用户提交的信息封装在HTML HEADER内。适合提交数据量大,安全性高的用户信息。如:注册、修改、上传等功能。

4. request对象

客户端的请求信息被封装在request对象中,它是HttpServletRequest类的实例。request对象具有请求域,即完成客户端的请求之前,该对象一直有效。常用方法如下:

Read more »

1. JavaBean简介

javaBeans就是符合某种特定的规范的java类。使用JavaBeans的好处是解决代码重复编写,减少代码冗余,功能区分明确,提高了代码的可维护性。

JavaBean的设计原则:

  1. 公有类
  2. 属性私有
  3. 无参的公有构造方法
  4. getter和setter方法

2. JSP动作元素

2.1 什么是JSP动作元素

JSP动作元素(action element),动作元素为请求处理阶段提供信息。动作元素遵循XML语法,有一个包含元素名的开始标签,可以有属性,可选的内容、与开始标签匹配的结束标签。

2.2 JSP动作元素的五大类

第一类是与存取JavaBean有关的,包括:
<jsp:useBean> <jsp:setProperty> <jsp:getProperty>

第二类是JSP1.2就开始有的基本元素,包括6个动作元素:
<jsp:include> <jsp:forward> <jsp:param> <jsp:plugin> <jsp:params> <jsp:fallback>

Read more »

1. JSP简介

JSP页面元素构成:

  1. 静态内容
  2. 注释
  3. 声明
  4. 小脚本
  5. 表达式
  6. 指令

1.1 jsp指令

page指令:通常位于jsp页面的顶端,同一个页面可以有多个page指令。
include指令:将一个外部文件嵌入到当前jsp文件中,同时解析这个页面中的jsp语句。
taglib指令:使用标签库定义心得自定义标签。在jsp页面中启用定制行为

page指令语法:

1
<%@page 属性1="value" 属性2="value1, value2" ... %>
属性 描述 默认值
language 指定jsp页面使用的脚本语言 java
import 通过该属性来引用脚本语言中使用到的类文件
contentType 用来指定jsp页面所采用的编码方式 text/html,ISO-8859-1

1.2 JSP注释

  1. html注释 <!--html注释-->
  2. jsp注释<%--注释--%>
  3. jsp脚本注释 // /**/
Read more »
0%