tips: This article is compiled based on ppt and is not original. If you have any questions, please feel free to communicate via private message. For
related exercises, please check the article: JSP final exam review exercises and answers.
I wish all my friends good luck in the exam!
Attached are related original articles:
JSP basic tutorial
HTML
JDBC
JDBC custom tool class
JDBC connection pool
servlet working principle and life cycle
servlet request and response
realize login based on JSP and EL expressions, and use filters and listeners
Article directory
- 1. JSP syntax basics
- 2. JSP built-in objects
- 3. JavaBean
- 4. The problem of Chinese garbled characters
- 5. Cookies
- 六、 Mysql & JDBC
- 7. servlet
- 8. MVC
1. JSP syntax basics
1.1 JSP file structure
The JSP original code contains two categories : JSP elements and Template (template) data.
-
Template data : The part not processed by the JSP engine, that is, the part other than the tag <%...%>,
such as the HTML content in the code, etc. These data will be sent directly to the client's browser. -
JSP element : The part directly processed by the JSP engine. This part must conform to JSP syntax, otherwise it will cause compilation errors.
1.2 JSP operating principle
1.3 JSP syntax basics
Script syntax
-
HTML comments: <!— comments -->
are not displayed when sent to the client , but can be seen when viewing the source code -
JSP hidden comments: <%-- comments --%>
are not sent to the client, that is, not displayed , and can only be seen in the compiler -
JSP statement:<%! declaration; [ declaration; ] … %>
1) The declaration takes effect when the web page is initialized and is valid within this web page.
2) The declaration is a global variable
. Tips: The declaration can be a variable or a method.
example:
- JSP expression: <%= expression %>
example:
- JSP script segment: <% code%>
example:
compiler directives
include include directive
Insert the content of a static file into the current page
- JSP syntax format:
<%@ include file="relativeURL" %>
<%@ include file="relative position" %>
example:
page command
Used to define global properties in JSP files
- Syntax format:
JSP syntax format is as follows:
<%@ page
[ language=“java” ] [ extends=“package.class” ]
[import="{package.class | package.*},…" ]
[ session=“true | false” ] [ buffer=“none | 8kb | sizekb” ]
[ autoFlush=“true | false” ]
[ isThreadSafe=“true | false” ] [ info=“text” ]
[ errorPage=“relativeURL” ]
[ contentType=“mimeType [;charset=characterSet]” |
“text/html; charset=ISO-8859-1” ]
[ isErrorPage=“true | false” ]
%>
example:
Tag library taglib directive
Prefix used to specify the tag library and custom tag library used in the page
See JSTL for details
action grammar
forward
Jump from the current file to another file under program control
- Syntax format
1.<jsp:forward page={
"relativeURL" | "<%= expression %>"} />
2.<jsp:forward page={
"relativeURL" | "<%= expression %>"} >
<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />
</jsp:forward>
page="{relativeURL | <%= expression %>}"
这里是一个表达式或是一个字符串用于说明你将要定向的文件或URL。这个文件可以是JSP、程序段或者其它能够处理request对象的文件(如asp,cgi,php)。
<jsp:param name="parameterName" value="{parameterValue | <%= expression %>}" />
向一个动态文件发送一个或多个参数,这个文件必须是动态文件。如果想传递多个参数,可以在一个JSP文件中使用多个“<jsp:param>”;“name”指定参数名,“value”指定参数值。
<jsp:forward>从一个JSP文件向另一个文件传递一个包含用户请求的request对象“<jsp:forward>”标签以后的代码,将不能执行。
example:
include
Used to include a static or dynamic file
- grammar
1.<jsp:include page="{relativeURL | <%=expression%>}" flush="true" />
2.<jsp:include page="{relativeURL | <%=expression %>}" flush="true" >
<jsp:param name="parameterName" rameterValue | <%= expression %>}"/>
[<jsp:param …/>]
</jsp:include>
page="{relativeURL | <%=expression %>}"
参数为一相对路径,或者是代表相对路径的表达式。
<jsp:param name="parameterName" value="{parameterValue | <%= expression %> }" />
“<jsp:param>”用来传递一个或多个参数到指定的动态文件,能在一个页面中使用多个“<jsp:param>”来传递多个参数。
example:
usebean
javabean content
2. JSP built-in objects
Member variables that can be used directly in JSP page scripts (Java program slices and Java expressions) without declaration and creation.
Built-in objects must be created by a container that supports JSP
- Nine built-in objects:
request request object (emphasis)
response response object (emphasis)
session session object (emphasis)
out output object (emphasis)
page page object
application application object
pageContext surface context object
config configuration object
exception exception object
2.1 Built-in object –request
The client's request information is encapsulated in the request object
Only through requests can we understand the needs of customers and then respond.
Common methods:
method | describe |
---|---|
getParmeter(String name) | Get the information submitted by the form and return the value of a request parameter in the form of a string; when there is no corresponding parameter, return null |
getParameterNames() | Gets all parameters passed by the client to the server. The result is an Enumeration instance. |
getCharacterEncoding() | Returns the encoding method in the client request |
getContentLength() | Returns the size of the client's request in bytes |
getHeader(String name) | The user obtains the value of the name specified in the HTTP protocol file header information |
getHeaderNames() | Returns all file header information of the HTTP protocol, and the result is an Enumeration instance. |
getMethod() | Returns the method requested by the client (get or post) |
getProtocal() | Get the protocol used by the client to transmit to the server |
getRequestURL() | User obtains client URL address |
getRemoteAddr() | Get client IP address |
getRemoteHost() | Get the client host name |
getServerName() | Get the name of the server host |
getServerPort() | Get server port number |
removeAttribute(String name) | Delete an attribute of the request |
setAttribute(String name,Object object) | Set properties for the request object |
getAttribute(String name) | Get the value of the request object attribute name |
getAttributeNames() | Returns all attribute values of the request object. The result is an Enumeration instance. |
2.2 Built-in object –response
Used to dynamically respond to client requests, control the information sent to users, and dynamically generate responses
Common methods:
method | describe |
---|---|
addCookie(Cookie cook) | The user adds a cookie to the user to save client-related information |
addHeader(String name, String value) | Add HTTP header information with the specified name and string |
getCharacterEncoding() | Returns the string encoding of the response |
sendError() | Send error message to client |
sendRedirect() | Redirect client requests |
setCharacterEncoding() | Set the response string encoding |
forward and redirect
forward: forward
redirect: redirect
example:
2.3 Built-in object –session
JSP uses the HttpSession interface provided by servlet to identify a user and store all access information of this user
By default, JSP allows session tracking, and a new HttpSession object will be automatically instantiated for new clients.
Common methods:
type | method | describe |
---|---|---|
public Object | getAttribute(String name) | Returns the object bound to the specified name in the session object, or null if it does not exist. |
public Enumeration | getAttributeNames() | Returns all object names in the session object, the result is an Enumeration instance |
public long | getCreationTime() | Returns the time when the session object was created, in milliseconds, starting from the early morning of January 1, 1970 |
public String | getId() | Returns the ID of the session object |
public long | getLastAccessedTime() | Returns the last access time of the client, in milliseconds, starting from the early morning of January 1, 1970 |
public int | getMaxInactiveInterval() | Returns the maximum time interval, in seconds, during which the servlet container will keep a session open |
public void | invalidate() | Invalidate session |
public void | removeAttribute(String name) | Remove the object with the specified name in the session |
public void | setAttribute(String name, Object value) | Generate an object using the specified name and value and bind it to the session |
public void | setMaxInactiveInterval(int interval) | Used to specify the time, in seconds, during which the servlet container will keep the session valid; |
2.4 Built-in object –out
Output content on the browser client (page buffer input, when the buffer is full or the page execution ends, the buffer content is output)
Common methods:
type | method | describe |
---|---|---|
void | println() | Print string to client |
void | flush() | Output buffer contents to client |
void | clear() | Clear the buffer. Calling it after the flush() method will cause an exception. |
void | clearBuffer() | Clear the buffer and there will be no exception when calling after flush() |
int | getBufferSize() | Returns the size of the buffer in bytes |
The difference between JspWriter(out) and PrintWriter(response.Writer)
-
1) All page output is finally out output (JSPWriter);
response.Writer output is PriterWriter output; -
2) Out output is written to the page buffer first. The buffer is full or the page execution ends,
and then output;
response.Writer is output directly.
2.5 Built-in object – application
Achieve data sharing between users as global variables
Tomcat服务器的启动和关闭决定了application的生命周期
常见方法:
类型 | 方法 | 描述 |
---|---|---|
public Object | getAttribute(String name) | 返回applicaltion对象中与指定名称绑定的对象,如果不存在则返回null |
public Enumeration | getAttributeNames() | 返回applicaltion对象中所有的对象名称,其结果是一个Enumeration(枚举)实例 |
public void | setAttribute(String name ,Object value) | 设置application属性及其值 |
public void | removeAttribute(String name) | 删除applicaltion对象中属性及其对应的值 |
public String | getServerInfo() | 返回Servet编译器版本信息 |
2.6 内置对象–pageContext
实现获得当前JSP页面所有对象和命名空间的访问
常见方法:
方法 | 描述 |
---|---|
getRequest() | 返回当前的request对象 |
getResponese() | 返回当前的response对象 |
getSession() | 返回当前的session对象 |
getOut() | 返回当前的out对象 |
2.7 内置对象–page、config、exception
-
page对象
指向当前JSP页面本身(有点像类中的this指针),它是java.lang.Object类的实例 -
config对象
代表当前JSP 配置信息
但JSP 页面通常无须配置,因此也就不存在配置信息 -
exception对象
Throwable实例,代表JSP脚本中产生的错误和异常,是JSP页面机制的一部分(见编译器语法介绍)
2.8 内置对象生命周期
三、 JavaBean
JavaBean是特殊的Java类,使用Java语言书写,并且遵守JavaBean API规范
- Javabean和普通Java类特殊性:
1)提供一个默认的无参构造函数
2)可能有一系列私有可读写属性
3)可能有一系列的"get"或"set"方法
3.1 JSP中使用JavaBean
useBean
创建一个Bean实例并指定它的名字和作用范围
语法格式:
<jsp:useBean id="beanInstanceName"
scope="page | request | session | application"
{
class="package.class" | type="package.class" |
class="package.class" type="package.class" |
beanName="{package.class | <%= expression %>}"
type="package.class"
}
{
/>
| > other elements </jsp:useBean>
}
id="beanInstanceName":
这个变量名对大小写敏感
在所定义的范围中确认Bean的变量,id使之能在后面的程序中使用此变量名来分辨不同的Bean
如果Bean已经在别的“<jsp:useBean>”标记中创建,则当使用这个已经创建过Bean时,id的值必须与原来的那个id值一致;否则则意味着创建了同一个类的两个不同的对象
scope="page | request | session | application" :
Bean存在的范围以及id变量名的有效范围,缺省值是page
- page:能在包含“<jsp:useBean>”元素的JSP文件以及此文件中的所有静态包含文件中使用这个Bean,直到页面执行完毕向客户端发回响应或转到另一个文件为止
- request:在任何执行相同请求的Jsp文件中使用这个Bean,直到页面执行完毕向客户端发回响应或转到另一个文件为止。能够使用Request对象访问这个Bean
- session:从创建Bean开始,就能在任何使用相同session的jsp文件中使用这个Bean
- application :从创建Bean开始,就能在任何使用相同application的jsp文件中使用Bean
class="package.class" :
(类)使用new关键字及class构造器从一个class中实例化一个bean
通过类创建实例,这个class不能是抽象的,必须有一个公用的,没有参数的构造器。
type="package.class":
(引用)引用该对象的变量类型,可以是Bean类的名字、超类名字、该类接口名字之一等
如果使用type属性的同时没有使用class或beanName,Bean将不会被实例化,抛出异常
- jsp:useBean执行顺序
步骤1: 在scope属性作用域使用你指定的名称(id属性值)定位Bean对象;
步骤2: 使用id属性值定义一个引用类型变量;
步骤3: 假如找到Bean对象,将其引用给步骤2定义的变量。假如你指定类型(type属性),赋予该Bean对象该类型;
步骤4: 假如没找到,则实例化一个新的Bean对象,并将其引用给步骤2定义的变量。假如该类名(由beanName属性指定的类名)代表的是一个序列化模板(serialized template),该Bean对象由java.beans.Beans.instantiate初始化;
步骤5: 假如< jsp:useBean>此次是实例化Bean对象而不是定位Bean对象,且它有体标记(body tags)或元素(位于< jsp:useBean>和</jsp:useBean>之间的内容,则执行该体标记
getProperty
获得JavaBean的对象的属性的值
- 语法格式
<jsp:getProperty name="beanInstanceName" property="propertyName" />
属性:
1) name="beanInstanceName" bean的ID值,由<jsp:useBean>指定
2) property="propertyName" 所指定的Bean对象的属性名
setProperty
给指定JavaBean的对象的属性赋值
- 语法格式
<jsp:setProperty
name="beanInstanceName"
{
property= "*" |
property="propertyName" [ param="parameterName" ] |
property="propertyName" value="{string | <%= expression %>}"
}
/>
1)name="beanInstanceName"
在“<jsp:useBean>”中id的值,创建的Bean实例的名字。
2) property="*"
指定javabean对象的某个属性名称。
3) value="*"
指定javabean对象的某个属性的值。
3.2 JavaBean应用
四、 中文乱码问题
Java语言编码:UNICODE(16位),支持中文 也 支持英文
常见编码:
-
1) gb2312
中国国家标准总局发布,1981年5月1日实施,通行中国大陆.
收录6763个汉字,一级汉字3755个,二级汉字3008个
生僻字、古汉字无法处理。 -
2) gbk
1995年12月完成GBK规范,兼容GB2312,收录汉字21003个、符号883个,并提供1894个造字码位,简、繁体字融于一库 -
3)Unicode
国际ISO和UNICODE协会共同制定的统一编码,世界上所有的符号都纳入其中 -
4)UTF-8
是UTNICODE的实现方式,最大的特点,其是一种变长的编码方式,可以使用1~4个字节表示一个符号,根据不同的符号而变化字节长度
4.1 乱码原因
4.2 解决乱码
1)信息源、传输过程、目的地保证编码方式的统一;
2)如果不一致,进行相应的转码,使其展示正常;
jsp文件中乱码
- 头文件修改
<%@ page language="java" contentType="text/html; charset=utf-8 pageEncoding="utf-8""%>
- 软件配置修改
Encoding更改为 UTF-8
include 和 forward中文乱码
request.setCharacterEncoding("utf-8");
form表单提交中文乱码
String username = request.getParameter("username");
username = new String(username.getBytes("ISO-8859-1"),"UTF-8");
五、 Cookie
Cookie:由服务器端生成,发送给User-Agent(一般是浏览器),浏览器会将Cookie的key/value保存到某个目录下的文本文件内,下次请求同一网站时就发送该Cookie给服务器(前提是浏览器设置为启用cookie)
Cookie名称和值可以由服务器端开发自己定义,对于JSP而言也可以直接写入JSESSIONID用于标记一个会话(session),这样服务器可以知道该用户是否合法用户以及是否需要重新登录等,服务器可以设置或读取Cookies中包含信息,借此维护用户跟服务器会话中的状态。
5.1 特点
1)一个小信息,由服务器写给浏览器的,由浏览器来保存
2)客户端保存的Cookie信息,可以再次带给服务器
3)Cookie类:javax.servlet.http.Cookie
5.2 cookie类中的属性
- name
必须,设置cookie的名字 - value
必须,与cookie关联的值 - comment
可选,cookie注释 - path
可选,设置cookie适用的路径
(如果不设置,当前页面相同目录下所有URL都会返回该Cookie) - domain
可选,该Cookie所属的网站域名 - maximum age
可选,cookie过期时间。
(如果不设置,当前session中有效) - version
可选,版本号
会话:当用户打开浏览器,访问多个WEB资源,然后关闭浏览器的过程,称之为一个会话
- 在会话的过程中,状态的保存与管理:
1)cookie将状态保存在客户端
2)session将状态保存在服务器端
5.3 cookie的使用
设置Cookie
-
引入 javax.servlet.http.Cookie类
-
创建一个cookie并进行设置
Cookie cookie=new Cookie(“name”,“独孤求败”);
cookie.setMaxAge(606024); -
通过response告诉客户端cookie
response.addCookie(cookie);
Cookie调用
-
引入 javax.servlet.http.Cookie类
-
通过request获得所有的cookies
Cookie[] cookies = request.getCookies(); -
通过cookies数组查找所有的cookie
for(int i=0;i<cookies.length;i++){
out.println(cookies[i].getName() + “,” + cookies[i].getValue());
}
5.4 cookie应用
浏览器记住用户名和密码
六、 Mysql & JDBC
6.1 JDBC连接sql
- JDBC(Java DataBase Connectivity,Java数据库连接)
用于执行SQL语句的Java API
可以为多种关系数据库提供统一访问
由一组用Java语言编写的类和接口组成
JDBC提供了一种基准,据此可以构建更高级的工具和接口,使数据库开发人员能够编写数据库应用程序
JDBC-DriverManage
- DriverManager
包含Driver类,它们已通过调用方法DriverManager.registerDriver对自己进行了注册
所有Driver类都必须包含有一个静态部分
-
1)下载MySQL JDBC驱动程序
地址:https://www.mysql.com/products/connector/ -
2)驱动jar包放到合适目录
WebContent->WEB-INF->lib 下 -
3)显示的加载MySQL驱动程序
Class.forName(“com.mysql.jdbc.Driver”);
JDBC-Connection
- Connection
加载Driver类并在DriverManager类中注册后,即可用来与数据库建立连接
当调用DriverManager.getConnection方法发出连接请求时,DriverManager将检查每个驱动程序,查看它是否可以建立连接
Connection conn = DriverManager.getConnection("jdbc:mysql://localhost/17", "root", "123456");
1) "jdbc:mysql://localhost/17": mysql URL地址
localhost:mysql服务器地址;
17:数据库名;
2) "root": mysql数据库用户名
3) "123456": mysql数据库密码
JDBC-Statement
- Statement
用于将SQL语句发送到数据库中
三种Statement对象
- Statement
执行不带参数的简单SQL语句 - PreparedStatement(从Statement继承而来)
执行带或不带参数的预编译SQL语句; - CallableStatement(从PreparedStatement继承而来)
执行对数据库已存储过程的调用
1)SQL语句
String sql = "select * from tb_user where username=? and password=?";
2)SQL处理和参数传递
pst = conn.prepareStatement(sql);
pst.setString(1, name);
pst.setString(2, pwd);
![在这里插入图片描述](https://img-blog.csdnimg.cn/6946197a0f924d00ae396f25671543da.png)
3)SQL执行
pst.executeQuery();
JDBC-ResultSet
execute方法能返回ResultSet对象,用于存储返回结果
通过对结果集查询,得到需要的值
while(result.next()){
String username = result.getString(“username”);
String password = result.getString(“password”);
}
1)while循环判断结果集有没有
2)result.getString(“username”):得到当前结果集记录中,数据库字段为username的值
JDBC登录判断
<%@ page import="java.sql.DriverManager"%>
<%@ page import="java.sql.Connection"%>
<%@ page import="java.sql.PreparedStatement"%>
<%@ page import="java.sql.ResultSet"%>
<%@ page import="java.sql.SQLException"%>
Boolean flag = false;
Connection conn=null;
PreparedStatement pst = null;
ResultSet result = null;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/StudentInfo", "root", "123456");
String sql = "select * from user where username=? and password=?";
pst = conn.prepareStatement(sql);
pst.setString(1, username);
pst.setString(2, pwd);
result = pst.executeQuery();
while(result.next()){
flag = true;
}
conn.close();
pst.close();
result.close();
if(flag==true){
session.setMaxInactiveInterval(30);
Cookie usercookie = new Cookie("username",username);
Cookie pwdcookie = new Cookie("pwd",pwd);
usercookie.setMaxAge(60*60*24);
pwdcookie.setMaxAge(60*60*24);
response.addCookie(usercookie);
response.addCookie(pwdcookie);
}
6.2 JDBC增删改查
增
index.jsp
//引入Jquery、Jquery artDialog、Jquery DateTimePicker
<script type="text/javascript" src="../js/jquery-3.4.0.min.js"></script>
<script src="../js/artDialog/jquery.artDialog.js?skin=default"></script>
<script src="../js/datetimepicker/jquery.datetimepicker.js"></script>
<link rel="stylesheet" type="text/css" href="../css/datetimepicker/jquery.datetimepicker.css"/>
//新增用户对话框关联学生信息信息表单
insertConfirm.jsp:
//接受index.jsp中Form表单传递的参数
String stunum = request.getParameter("stunum");
String stuname = request.getParameter("stuname");
stuname = new String(stuname.getBytes("ISO-8859-1"),"UTF-8");
String gender = request.getParameter("gender");
String datepicker = request.getParameter("datetimepicker");
Date date=Date.valueOf(datepicker);
//定义数据库操作对象,连接数据库
Connection conn=null;
PreparedStatement pst=null;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/studentinfo","root","123456");
//写插入SQL,参数传入,执行SQL
String sql = "insert into tb_student(stunumber,name,birthday,gender) values(?,?,?,?)";
pst= conn.prepareStatement(sql);
pst.setString(1, stunum);
pst.setString(2, stuname);
pst.setDate(3, date);
pst.setInt(4, Integer.parseInt(gender));
pst.executeUpdate();
//关闭数据库连接,跳转至index.jsp
conn.close();
pst.close();
<jsp:forward page="index.jsp"/>
删
index.jsp
//单击删除,当前选择记录的学生ID为参数,通过artDialog提示
<a href="#" onclick="ShowDelete(<%=id%>)">删除</a>
function ShowDelete(id){
$.ajax({
...//跳到query.jsp中查询
});
}
//获得Ajax请求返回值,对其值进行解析
//delete.jsp,单击弹框确定按钮,删除
delete.jsp
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Date" %>
String id = request.getParameter("id");
//连接sql、传参、执行删除、关闭资源
Connection conn=null;
PreparedStatement pst=null;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/studentinfo","root","123456");
String sql = "delete from tb_student where id = ?";
pst= conn.prepareStatement(sql);
pst.setInt(1, Integer.parseInt(id));
pst.executeUpdate();
conn.close();
pst.close();
//更新成功,跳转页面
<jsp:forward page="index.jsp"/>
改
index.jsp
//单击修改,当前选择记录的学生ID为参数,通过Ajax查找信息
<a href="#" onclick="ShowUpdate(<%=id%>)">修改</a>
function ShowUpdate(id){
$.ajax({
...//跳到query.jsp中查询
});
}
//获得Ajax请求返回值,对其值进行解析
//updateStudent.jsp,单击弹框确定按钮,提交FORM表单信息,更新
query.jsp
//query.jsp获得Ajax请求,根据ID查询信息并把信息返回页面
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
String strId = request.getParameter("id");
Integer id = Integer.parseInt(strId);
Boolean flag = false;
Connection conn=null;
PreparedStatement pst=null;
ResultSet result=null;
Integer stuId=0;
String stuNumber=null;
String stuName=null;
Integer stuGender=1;
String birthday=null;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/studentinfo","root","123456");
String sql = "select id,stunumber,name,gender,
DATE_FORMAT(birthday,'%Y-%m-%d') as birthday
from tb_student where id=?";
pst= conn.prepareStatement(sql);
pst.setInt(1, id);
result = pst.executeQuery();
while(result.next()){
stuId = result.getInt("id");
stuNumber = result.getString("stunumber");
stuName = result.getString("name");
stuGender = result.getInt("gender");
birthday = result.getString("birthday");
}
conn.close();
pst.close();
result.close();
out.println(stuId + "," + stuNumber + "," + stuName + "," + stuGender + "," + birthday);
updateStudent.jsp
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Date" %>
String stuid=request.getParameter("stuid");
String stunum = request.getParameter("stunumupdate");
String stuname = request.getParameter("stunameupdate");
stuname = new String(stuname.getBytes("ISO-8859-1"),"UTF-8");
String gender = request.getParameter("genderupdate");
String datepicker = request.getParameter("datetimepickerupdate");
Date date=Date.valueOf(datepicker);
//连接sql、传参、执行更新、关闭资源
...
//更新成功,跳转页面
<jsp:forward page="index.jsp"/>
查
index.jsp
<%@ page import="java.sql.DriverManager" %>
<%@ page import="java.sql.Connection" %>
<%@ page import="java.sql.PreparedStatement" %>
<%@ page import="java.sql.ResultSet" %>
<%@ page import="java.sql.SQLException" %>
<%@ page import="java.sql.Date" %>
//定义变量
Connection conn=null;
PreparedStatement pst=null;
ResultSet result=null;
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/studentinfo","root","123456");
//定义SQL,进行查询,并解析返回结果
String sql = "select * from tb_student";
pst= conn.prepareStatement(sql);
result = pst.executeQuery();
while(result.next()){
int id = result.getInt("id");
String stunum = result.getString("stunumber");
String name = result.getString("name");
Date date = result.getDate("birthday");
int gender = result.getInt("gender");
//结果嵌入到页面中,进行查询,并解析返回结果
<center>
<table border=1>
<tr>
<td>序号</td>
<td>学号</td>
<td>姓名</td>
<td>性别</td>
<td>出生日期</td>
</tr>
。。。。。result解析程序
<tr>
<td><%=id%></td>
<td><%=stunum%></td>
<td><%=name%></td>
<td><%=gender%></td>
<td><%=date%></td>
</tr>
<%
}
conn.close();
pst.close();
result.close();
%>
</table>
</center>
七、 servlet
Servlet是使用Java Servlet接口(API)运行在Web应用服务器上的Java程序
Servlet在服务器上运行以处理客户端请求、业务逻辑并做出响应的程序
-
特点
需要运行在服务器端(TOMCAT)
需要Web容器的支持
Java编写 -
servlet与JSP页面
servlet | JSP页面 |
---|---|
Servlet承担客户请求与业务处理的中间角色,需要调用固定的方法,将动态内容混合到静态之中产生HTML | 在JSP页面中,可直接使用HTML标签进行输出,要比Servlet更具显示层的意义 |
Servlet中需要调用Servlet API接口处理HTTP请求 | JSP页面中直接提供了内置对象进行处理 |
Servlet的使用需要进行一定的配置 | JSP文件通过“.jsp”扩展名部署在容器之中,容器对其自动识别,直接编译Servlet进行处理 |
7.1 生命周期
Servlet是一个单例
Servlet生命周期,可被定义为从创建到毁灭的整个过程
- 实例化 – 创建servlet实例
- 初始化 – init()
只调用一次,在第一次创建 Servlet 时被调用,在后续每次用户请求时不再调用 - 处理请求 – service()
执行实际任务的主要方法,Servlet 容器(即 Web 服务器)调用 service() 方法来处理来自客户端(浏览器)的请求,并把格式化的响应写回给客户端 - 服务终止 – destory()
只被调用一次,在 Servlet 生命周期结束时被调用
可以使 Servlet 关闭数据库连接、停止后台线程、把 Cookie 列表或点击计数器写入到磁盘,并执行其他类似的清理活动,在调用后,servlet 对象被标记为垃圾回收 - GC垃圾回收(可看作是服务终止的一部分)
如图描述:
具体过程:
7.2 处理流程
1、客户端使用浏览器(get/post)提交,并调用Servlet的doGet或者doPost方法
2、服务器接收到请求后,如果该Servlet第一次被调用,实例化这个Servlet
3、服务器调用该Servlet对象的service()方法
4、Servlet产生动态的回复内容
5、服务器发送回复内容给客户端浏览器
7.3 构建
基于注解
基于web.xml
-
web.xml中url-pattern路径设置规则:
1 精确匹配
2 路径匹配
3 扩展名匹配
4 缺省匹配 -
优先级
精确匹配 > 路径匹配 > 扩展名匹配 > 缺省
1、精确匹配:<url-pattern>中配置的项必须与url完全精确匹配
<servlet-mapping>
<servlet-name>helloworld</servlet-name>
<url-pattern>/helloWorld</url-pattern>
<url-pattern>/helloWorld.jsp</url-pattern>
<url-pattern>/helloWorld.html</url-pattern>
</servlet-mapping>
当在浏览器中输入如下几种url时,都会被匹配到servlet
http://localhost:8080/HelloWorld/helloworld.html
http://localhost:8080/HelloWorld/helloworld.jsp
http://localhost:8080/HelloWorld/helloworld
http://localhost:8080/HelloWorld/helloworld?username=Tom&age=23
2、路径匹配:以“/”字符开头,并以“/ *”结尾的字符串用于路径匹配
<servlet-mapping>
<servlet-name>helloworld</servlet-name>
<url-pattern>/hello/ *</url-pattern>
</servlet-mapping>
路径以/hello/开始,后面的路径可以任意。比如下面的url都会被匹配 http://localhost:8080/HelloWorld/hello/hello.html
http://localhost:8080/HelloWorld/hello/hello.action
http://localhost:8080/HelloWorld/hello/hello.jsp
3、扩展名匹配:以“*.”开头的字符串被用于扩展名匹配
<servlet-mapping>
<servlet-name>helloworld</servlet-name>
<url-pattern>*.jsp</url-pattern>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
任何扩展名为jsp或action的url请求都会匹配,比如下面的url都会被匹配
http://localhost:8080/HelloWorld/hello/users.jsp
http://localhost:8080/HelloWorld/hello.action
4、缺省匹配:以上都找不到对应的servlet,就用缺省匹配的servlet
<servlet-mapping>
<servlet-name>helloworld</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
- tips:
url-pattern映射匹配过程有优先顺序,当有一个servlet匹配成功以后,就不会去理会剩下的servlet了
"/*" 和 “/” 含义并不相同
-
“/*”
路径匹配,并且可以匹配所有request
由于路径匹配的优先级仅次于精确匹配,所以“/*”会覆盖所有的扩展名匹配,很多404错误均由此引起,所以这是一种特别恶劣的匹配模式 -
“/”
是servlet中特殊的匹配模式,该模式有且仅有一个实例
优先级最低,不会覆盖其他任何url-pattern,只是会替换servlet容器的内建default servlet ,该模式同样会匹配所有request
7.4 servlet类
GenericServlet
public abstract class GenericServlet extends Object
implements Servlet, ServletConfig, Serializable
GenericServlet类是一个抽象类,
·分别实现了Servlet接口与ServletConfig接口
·实现了除service()之外的其他方法
在创建Servlet对象时,可以继承GenericServlet类来简化程序中的代码,但需要实现service()方法。
HttpServlet
public abstract class HttpServlet extends GenericServlet
implements Serializable
HttpServlet类是一个抽象类
·继承了GenericServlet类
·通过对GenericServlet类的扩展,可以很方便地对HTTP请求进行处理及响应
7.5 转发与重定向
重定向:
response.sendRedirect("login.jsp");
转发:
RequestDispatcher dispatcher = request.getRequestDispatcher("index.jsp");
dispatcher.forward(request, response);
例:
1) 新建用户登录Servlet ValidateLogin
2) 通过POST方式处理用户验证(数据库连接验证)
3) 引入数据库包和Servlet中session的包;
4) 获得FORM表单参数;
5) 实现数据库查询;
6) Servlet中的转发与重定向;
7) login.jsp中Form表单提交Servlet;
7.6 过滤器Filter
Servlet过滤器是客户端与目标资源间的中间层组件,用于过滤、拦截客户端的请求与响应信息
只能转发请求,不能直接发出响应
应用场景:
- 1)性能评测
了解servlet从请求到响应之间的时间差 - 2)字符替换
用户输入的特定字符必须过滤并替换为无害字符 - 3)编码设置
请求与响应的编码换成另一种 - 4)用户行为控制
session判断
void doFilter(ServletRequest request, ServletResponse response)throws IOException , ServletException
主要用于将过滤器处理的请求或响应传递给下一个过滤器对象
中文编码转换
session统一验证
7.7 监听器Listener
监听器是一个实现特定接口的java程序
专门用于监听另一个特殊java对象的方法调用或属性改变,当被监听对象发生上述事件后,监听器某个方法将立即被执行
1)监听域对象自身创建和销毁的监听器;
2)监听域对象中的属性的增加、修改和删除的事件监听器
3)监听绑定到 HttpSession 域中某个对象的状态的事件监听器
ServletContextListener接口
监听 ServletContext对象
相关方法:
1、contextInitialized(ServletContextEvent arg0):在Web应用加载的时候被调用
2、contextDestroyed(ServletContextEvent arg0): 在Web应用卸载的时候被调用
arg0.getServletContext()可获取当前应用的上下文对象
- 作用
对相关资源进行初始化工作
(如创建数据库连接池、创建Spring IOC 容器、读取当前Web应用的初始化参数等)
HttpSessionListener接口
监听 HttpSession对象
相关方法
1、sessionCreated(HttpSessionEvent arg0): Session创建时被调用
2、sessionDestroyed(HttpSessionEvent arg0): Session销毁时被调用
Session什么时候销毁?
关闭服务器、Session过期、手动调用session.invalidate()方法
- 作用
统计在线人数、记录访问日志等
ServletRequestListener接口
监听 ServletRequest对象
相关方法
1、requestInitialized(ServletRequestEvent arg0): Request创建时被调用
2、requestDestroyed(ServletRequestEvent arg0): Request销毁时被调用
每次请求响应会创建一次和销毁一次;即每次刷新页面都会导致Request的创建和销毁
转发是一次响应,可以获取Request的信息
重定向是两次响应,即前一个页面的Request对象和重定向后的页面的Request对象不是同一个对象,因此不能获得前一个对象的Request信息
- 作用
读取参数,记录访问历史等
ServletContextAttributeListener接口
监听SercvletContext对象属性
相关方法
1、attributeAdded(ServletContextAttributeEvent arg0): 当程序把一个属性存入application范围时触发该方法
2、attributeReplaced(ServletContextAttributeEvent arg0): 当程序替换application范围内的属性时将触发该方法
3、attributeRemoved(ServletContextAttributeEvent arg0): 当程序把一个属性从application范围删除时触发该方法
HttpSessionAttributeListener接口
监听 HttpSession对象属性
相关方法
1、attributeAdded(HttpSessionBindingEvent arg0): session.setAttribute("name", "sessionValue")初次创建调用
2、attributeReplaced(HttpSessionBindingEvent arg0): session.setAttribute("name", "newSessionValue")被修改时调用
3、attributeRemoved(HttpSessionBindingEvent arg0):
执行session.removeAttribute("name")时调用
以上三个方法可用arg0.getName()获取属性名arg0.getValue()获取属性值
但是!要注意!在attributeReplaced()中获取的是旧值
ServletRequestAttributeListener接口
监听 ServletRequest对象属性
相关方法
1、attributeAdded(ServletRequestAttributeEvent arg0): request.setAttribute("name", "requestValue")初次创建调用
2、attributeReplaced(ServletRequestAttributeEvent arg0): request.setAttribute("name", "newRequestValue")被修改时调用
3、attributeRemoved(ServletRequestAttributeEvent arg0):
执行request.removeAttribute("name")时调用
以上三个方法中可用arg0.getName()获取属性名arg0.getValue()获取属性值
但是!要注意!在attributeReplaced()中获取的是旧的值
HttpSessionBindingListener接口
监听实现HttpSessionBindingListener接口的的session绑定和解除
相关方法
1、valueBound(HttpSessionBindingEvent arg0): session.setAttribute("name", javaBean)触发绑定方法
2、valueUnbound(HttpSessionBindingEvent arg0): session.removeAttribute("name")触发绑定解除方法
HttpSessionActivationListener接口
实现会话的持久化
前提:实现该接口和序列化接口Serializable,可以感知自己被活化(从硬盘到内存)和钝化(从内存到硬盘)的过程;当服务器突然关闭,用户的session就不存在了,即用户就需要重新登录等操作,这样很麻烦,于是我们就需要实现会话的持久化来解决。可以让我们在重新启动服务器之后用户的session还在服务器中存在
相关方法
1、sessionWillPassivate(HttpSessionEvent arg0): 钝化方法,关闭服务器调用的方法
将用户的Session储存到tomcat目录下的/work/Catalina/localhost/项目名下的SESSION.ser文件中
2、sessionDidActivate(HttpSessionEvent arg0): 活化方法,重新启动服务器时调用Session从硬盘回复到内存中,目录下的SESSION.ser文件消失
7.8 定时任务实现
八、 MVC
MVC(Model View Controller):模型(model)-视图(view)-控制器(controller)
用一种业务逻辑、数据、界面显示分离的方法组织代码,将业务逻辑聚集到一个部件里面
在改进和个性化定制界面及用户交互的同时,不需要重新编写业务逻辑
8.1 控制器controller
处理输入(写入数据库记录)
Student:学生信息的JavaBean
- LoginController控制器:通过控制器访问页面
Login:定义访问登录页面的Controller
- IndexController控制器:通过控制器请求所有学生数据,再发页面
StudentIndex:定义访问学生信息列表页面的Controller
- index.jsp
不需要再直接访问数据库,而是得到数据stuList进行展示
8.2 业务服务层(Service)
8.3 数据处理层(Dao)
dao,数据库访问层
2层模型直接在需要的地方进行数据库访问
3层模型通过业务逻辑层调用数据库,程序应用调用业务逻辑层
- UserService
用户业务逻辑处理
- DBUtil
数据库连接和资源释放工具类
- UserDao
用户数据库访问
- StudentService
user business logic processing