JavaWeb简介
什么是Web应用程序
Web应用程序是一种可以通过Web访问的应用程序。Web应用程序的一个最大好处是用户
很容易访问应用程序。用户只需要有浏览器即可,不需要在安装其他软件。
为什么要学习Web应用程序
我们说Web应用程序开发,是目前软件开发领域的三大方向之一。
JAVAEE方向需求一直是很大的,也是就业比较容易和稳定的。
软件领域三大方向
静态网页与动态网页
关于静态网页与动态网页下说法错误的是( )。
动态网页上可以显示动态元素比如:动画,视频等,而静态网页无法显示动态元素
动态网页的内容一般是从数据库里面读取出来的
动态网页的内容的显示是通过程序来实现的
学习动态网页开发至少要掌握一门高级语言
动态网页的动态指的是能与用户进行交互,比如登录时输入正确的用户名和密码,系统会提示登录成功。
工欲善其事必先利其器。学会搭建Java Web学习JSP动态网站开发的最基本技能之一。
Tomcat服务器简介
Tomcat安装与配置
安装Tomcat–>配置环境变量–>测试首页
CATALINA_HOME:Tomcat根目录
Tomcat服务器的目录结构
目录 | 说明 |
---|---|
/bin | 存放各种平台下用于启动和停止Tomcat的命令文件 |
/conf | 存放Tomcat服务器的各种配置文件 |
/lib | 存放Tomcat服务器所需的各种JAR文件 |
/logs | 存放Tomcat的日志文件 |
/temp | Tomcat运行时用于存放临时文件 |
webapps | 当发布web应用时,默认会将web应用的文件发布到此目录 |
/work | Tomcat把有JSP生成的Servlet放于此目录下 |
手工编写第一个Web程序
<html>
<head>
<title>第一个web应用title>
head>
<body>
第一个web应用
body>
html>
WEB-INF目录结构
MyEclipse
MyEclipse,是在eclipse基础上加上自己的插件开发而成的功能
强大的企业级集成开发环境,主要用于Java、Java EE以及移动应用
的开发。MyEclipse的功能非常强大,支持也十分广泛,尤其是对各种
开源产品的支持相当不错。
MyEclipse与Eclipse的区别
MyEclipse配置JRE
windows->Preference->Java->Installed JREs
MyEclipse集成Tomcat服务器
windows->Preference->MyEclipse->Server->Tomcat
MyEclipse Web项目目录结构
项目名称
java源程序
类库
项目根目录
资源文件
理解项目的虚拟路径
选择项目->属性->MyEclipse->Web->查看项目虚拟路径
Dynamic Web Project
<%@ page language="java" contentType="text/html; charset=utf-8"
pageEncoding="ISO-8859-1"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Insert title heretitle>
head>
<body>
hello world !
body>
html>
修改conf/server.xml
<Connector port="8080" protocol="HTTP/1.1"
connectionTimeout="20000"
redirectPort="8443" />
修改Tomcat服务器默认端口号需要修改的配置文件是( )
server.xml
JSP全名为Java Server Pages,其根本是一个简化的Servlet设计,
他实现了在Java当中使用HTML标签。Jsp是一种动态网页技术标准也是
JAVAEE的标准。JSP与Servlet一样,是在服务器端执行的。
常见动态网站开发技术对比
JSP页面组成部分
Jsp指令
page指令语法
<%@ page 属性1=”属性值” 属性2=”属性值1,属性值2”…
属性n=”属性值n”%>
属性 | 描述 | 默认值 |
---|---|---|
language | 指定JSP页面使用的脚本语言 | java |
import | 通过该属性来引用脚本语言中使用到的类文件 | 无 |
contentType | 用来指定JSP页面所采用的编码方式 | text/html,ISO-8859-1 |
以下哪个不属于JSP的三大指令元素( )
import
include
page
taglib
在JSP页面的注释
以下哪个注释是客户端无法查看到的注释( )
<%– 这里是注释–%>
在JSP页面中执行的java代码
语法:
<% Java代码 %>
<%
out.println("大家好!");
%>
在JSP页面中定义变量或者方法。
语法:
<%! Java代码 %>
<%!
String s = "张三";
int add(int a,int b){
return a+b;
}
%>
在JSP页面中执行的表达式。
语法:
<%= 表达式 %> //注意:表达式不以分号结尾
<p>你好,<%= s %>p>
<p>1+1= <%= add(1,1) %>p>
jspservice()方法被调用来处理客户端的请求。对每一个请求,JSP引擎创建
一个新的线程来处理该请求。如果有多个客户端同时请求该JSP文件,则JSP
引擎会创建多个线程。每个客户端请求对应一个线程。以多线程方式执行可以
大大降低对系统资源的需求,提高系统的并发量及响应时间。但是也要注意多线
程的编程带来的同步问题,由于该Servlet始终驻留在内存,所以相应是非常快的。
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="java.text.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>JSP生命周期h1>
<hr>
<%
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String s = sdf.format(new Date());
%>
今天是:<%= s %>
body>
html>
public final class index_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=utf-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("\r\n");
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" \r\n");
out.write(" );
out.print(basePath);
out.write("\">\r\n");
out.write(" \r\n");
out.write(" My JSP 'index.jsp' starting page \r\n");
out.write("\t\r\n");
out.write("\t\r\n");
out.write("\t \r\n");
out.write("\t\r\n");
out.write("\t\r\n");
out.write("\t\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" \tJSP生命周期
\r\n");
out.write(" \t
\r\n");
out.write(" \t");
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String s = sdf.format(new Date());
out.write("\r\n");
out.write(" \t今天是:");
out.print( s );
out.write("\r\n");
out.write(" \r\n");
out.write("\r\n");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
当用户第一次请求一个jsp页面时,首先被执行的方法是( )
构造方法
jspInit()
jspService()
jspDestroy()
第一次请求一个jsp页面时,首先被执行的方法是构造方法
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<%!
String printMultiTable1()
{
String s = "";
for(int i=1;i<=9;i++){
for(int j=1;j<=i;j++){
s += i + "*" + j + "=" +(i*j)+" ";
}
s += "
";
}
return s;
}
void printMultiTable2(JspWriter out) throws Exception
{
for(int i=1;i<=9;i++){
for(int j=1;j<=i;j++){
out.println( i + "*" + j + "=" +(i*j)+" ");
}
out.println("
");
}
}
%>
<h1>九九乘法表h1>
<hr>
<%= printMultiTable1() %>
<br>
<% printMultiTable2(out); %>
body>
html>
JSP内置对象是Web容器创建的一组对象,不使用new关键字就可以使用的内置对象。
int[] value = {60,70,80};
for(int i:value){
out.println(i);
}
九大内置对象
以下哪个不属于jsp九大内置对象( )
pageConfig
exception
page
pageContext
Web程序的请求响应模式
用户发送请求(request)
服务器给用户相应(response)
什么是缓冲区
缓冲区:Buffer,所谓缓冲区就是内存中的一块区域用来保存临时数据。
IO输出最原始的就是一个字节一个字节输出,就像一粒一粒吃一样,但效率太差。
刚煮好的米饭一粒一粒吃不知道要猴年马月。。。把米饭放到碗里,一碗一碗吃岂不痛快!
out对象是JspWriter类的实例,是向客户端输出内容的常用对象。
常用方法如下:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>out内置对象h1>
<%
out.println("静夜思
");
out.println("床前明月光
");
out.println("疑是地上霜
");
out.flush();
//out.clear();//这里会抛出异常。
out.clearBuffer();//这里不会抛出异常。
out.println("举头望明月
");
out.println("低头思故乡
");
%>
缓冲区大小:<%=out.getBufferSize() %>byte<br>
缓冲区剩余大小:<%=out.getRemaining() %>byte<br>
是否自动清空缓冲区:<%=out.isAutoFlush() %><BR>
body>
html>
执行以下jsp脚本输出效果是( )
<%
out.println("床前明月光");
out.flush();
out.clear();
out.println("疑是地上霜");
%>
在浏览器中只输出床前明月光
在浏览器中输出“床前明月光”,控制台会输出异常信息。
get与post区别
表单有两种提交方式:get与post
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting pagetitle>
<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">
head>
<body>
<h1>用户登录h1>
<hr>
<form action="dologin.jsp" name="loginForm" method="post">
<table>
<tr>
<td>用户名:td>
<td><input type="text" name="username"/>td>
tr>
<tr>
<td>密码:td>
<td><input type="password" name="password"/>td>
tr>
<tr>
<td colspan="2"><input type="submit" value="登录">td>
tr>
table>
form>
body>
html>
request对象
客户端的请求信息被封装在request对象中,通过它才能了解到客户的请求,然后
响应。它是HttpServletRequest类的实例。request对象具有请求域,即完成客户端
请求之前,该对象一直有效。常用方法如下:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>用户注册h1>
<hr>
<%
int number=-1;
//说明用户第一次访问页面,计数器对象还未创建
if(application.getAttribute("counter")==null)
{
application.setAttribute("counter", 0);
}
number = Integer.parseInt(application.getAttribute("counter").toString());
number++;
application.setAttribute("counter", number);
%>
<form name="regForm" action="response.jsp" method="post">
<table>
<tr>
<td>用户名:td>
<td><input type="text" name="username"/>td>
tr>
<tr>
<td>爱好:td>
<td>
<input type="checkbox" name="favorite" value="read">读书
<input type="checkbox" name="favorite" value="music">音乐
<input type="checkbox" name="favorite" value="movie">电影
<input type="checkbox" name="favorite" value="internet">上网
td>
tr>
<tr>
<td colspan="2"><input type="submit" value="提交"/>td>
tr>
table>
form>
<br>
<br>
<a href="request.jsp?username=李四">测试URL传参数a>
<br>
<br>
<center>
您是第<%=number %>位访问本页面的用户。
center>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>request内置对象h1>
<%
request.setCharacterEncoding("utf-8"); //解决中文乱码问题,无法解决URL传递中文出现的乱码问题。
request.setAttribute("password", "123456");
%>
用户名:<%=request.getParameter("username") %><br>
爱好 :<%
if(request.getParameterValues("favorite")!=null)
{
String[] favorites = request.getParameterValues("favorite");
for(int i=0;i" " );
}
}
%> <br>
密码:<%=request.getAttribute("password") %><br>
请求体的MIME类型:<%=request.getContentType() %><br>
协议类型及版本号: <%=request.getProtocol() %><br>
服务器主机名 :<%=request.getServerName() %><br>
服务器端口号:<%=request.getServerPort() %><BR>
请求文件的长度 :<%=request.getContentLength() %><BR>
请求客户端的IP地址:<%=request.getRemoteAddr() %><BR>
请求的真实路径:<%=request.getRealPath("request.jsp") %><br>
请求的上下文路径:<%=request.getContextPath() %><BR>
body>
html>
在用户注册表单中,用户的爱好信息用复选框表示,包括读书、音乐、电影和上网四项。如果已经选中读书和电影两项,此时要获取用户的爱好信息,使用request对象的哪个方法实现( )
request.getParameterValues(“favorite”);
response对象
response对象包含了响应客户请求的有关信息,但在JSP中很少直接用到它。它是
HttpServetResponse类的实例。response对象具有页面作用域,即访问一个页面时
该页面内的response对象只能对这次访问有效,其它页面的response对象对当前页面无效。
常用方法如下:
<%@ page language="java" import="java.util.*,java.io.*" contentType="text/html; charset=utf-8"%>
<%
response.setContentType("text/html;charset=utf-8"); //设置响应的MIMI类型
out.println("response内置对象
");
out.println("
");
//out.flush();
PrintWriter outer = response.getWriter(); //获得输出流对象
outer.println("大家好,我是response对象生成的输出流outer对象");
//response.sendRedirect("reg.jsp");//请求重定向
%>
请求转发与请求重定向
假设你去办理某个护照
重定向:你先去了A局,A局的人说:“这个事不归我管,去B局”,然后,你就从A局
退了出来,自己乘车去了B局。
转发:你去了A局,A局看了以后,知道这个事情其实应该B局来管,但是他没有把
你退回来,而是让你坐一会儿,自己到后面办公室联系了B的人,让他们办好后,送了
过来。
<%@ page language="java" import="java.util.*,java.io.*" contentType="text/html; charset=utf-8"%>
<%
response.setContentType("text/html;charset=utf-8"); //设置响应的MIMI类型
out.println("response内置对象
");
out.println("
");
//out.flush();
PrintWriter outer = response.getWriter(); //获得输出流对象
outer.println("大家好,我是response对象生成的输出流outer对象");
//response.sendRedirect("reg.jsp");//请求重定向
//请求重定向
//response.sendRedirect("request.jsp");
//请求转发
request.getRequestDispatcher("request.jsp").forward(request, response);
%>
关于请求重定向与请求转发的区别以下说法不正确的是( )
请求重定向是服务器端行为而请求转发是客户端行为
请求重定向相当于两次请求,地址栏地址会发生变化
重定向是response对象的方法而请求转发是request对象的方法
请求重定向不会保存原有request对象而请求转发会保存原有request对象
什么是session
购物流程说明
用户登录-》放入购物车-》订单填写-》提交订单-》确认订单-》立即付款
整个购物过程属于一次会话
在服务器的内存中保存着不同用户的session。
session对象
session对象常用方法如下:
long getCreationTime():返回SESSION创建时间
public String getId():返回SESSION创建时JSP引擎为它设置的唯一ID号
public Object setAttribute(String name,Object value):使用指定名称将对象绑定到此会话
public Object getAttribute(String name):返回与此会话中的指定名称绑定在一起的对象,如果没有对象绑定在该名称下,则返回null
String[] getValueNames():返回一个包含SESSION中所有可用属性的数组
int getMaxInactiveInterval():返回两次请求间隔多长时间此SESSION被取消(单位秒)
<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>session内置对象h1>
<hr>
<%
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date d = new Date(session.getCreationTime());
session.setAttribute("username", "admin");
session.setAttribute("password", "123456");
session.setAttribute("age", 20);
//设置当前session最大生成期限单位是秒
//session.setMaxInactiveInterval(10);//10秒钟
%>
Session创建时间:<%=sdf.format(d)%><br>
Session的ID编号:<%=session.getId()%><BR>
从Session中获取用户名:<%=session.getAttribute("username") %><br>
<a href="session_page2.jsp" target="_blank">跳转到Session_page2.jspa>
body>
html>
<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>session内置对象h1>
<hr>
<%
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//Date d = new Date(session.getCreationTime());
//session.setAttribute("username", "admin");
%>
Session的ID编号:<%=session.getId()%><BR>
从Session中获取用户名:<%=session.getAttribute("username") %><br>
Session中保存的属性有:<%
String[] names =session.getValueNames();
for(int i=0;i" " );
}
%> <br>
body>
html>
下面有关会话(session)描述不正确的是( )。
会话保存在客户端的内存里
会话是用来保存用户状态的一种机制
会话保存在服务器的内存里
每一个会话对应一个唯一的sessionId
session的生命周期
<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>session内置对象h1>
<hr>
<%
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
Date d = new Date(session.getCreationTime());
session.setAttribute("username", "admin");
session.setAttribute("password", "123456");
session.setAttribute("age", 20);
//设置当前session最大生成期限单位是秒
//session.setMaxInactiveInterval(10);//10秒钟
//session.invalidate();//销毁当前会话。
%>
Session创建时间:<%=sdf.format(d)%><br>
Session的ID编号:<%=session.getId()%><BR>
从Session中获取用户名:<%=session.getAttribute("username") %><br>
<%
//session.invalidate();//销毁当前会话
%>
<a href="session_page2.jsp" target="_blank">跳转到Session_page2.jspa>
body>
html>
<%@ page language="java" import="java.util.*,java.text.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>session内置对象h1>
<hr>
<%
//SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss");
//Date d = new Date(session.getCreationTime());
//session.setAttribute("username", "admin");
%>
Session的ID编号:<%=session.getId()%><BR>
从Session中获取用户名:<%=session.getAttribute("username") %><br>
Session中保存的属性有:<%
String[] names =session.getValueNames();
for(int i=0;i" " );
}
%> <br>
body>
html>
<web-app version="2.5"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<display-name>display-name>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
<session-config>
<session-timeout>1session-timeout>
session-config>
web-app>
有关session生命周期下列说法不正确的是( )。
每次重新打开新的浏览器窗口相当于开启了一次新的会话
session的生命周期分为创建、活动、销毁三个阶段
调用session.invalidate()方法可以销毁当前会话
重启web服务器会销毁所有的会话
常用方法如下:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>application内置对象h1>
<%
application.setAttribute("city", "北京");
application.setAttribute("postcode", "10000");
application.setAttribute("email", "[email protected]");
%>
所在城市是:<%=application.getAttribute("city") %><br>
application中的属性有:<%
Enumeration attributes = application.getAttributeNames();
while(attributes.hasMoreElements())
{
out.println(attributes.nextElement()+" ");
}
%><br>
JSP(SERVLET)引擎名及版本号:<%=application.getServerInfo() %><br>
body>
html>
使用application 实现计数器效果,在application中保存整型变量num,需要调用application对象的setAttribute方法,以下选项正确的是( )。
setAttribute(”counter”,num);
page对象是指向当前JSP页面本身,有点像类中的this指针,它是java.lang.Object类的实例。
常用方法如下:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>page内置对象h1>
当前page页面对象的字符串描述:<%=page.toString() %><br>
body>
html>
pageContext对象
常用方法:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>pageContext内置对象h1>
<hr>
用户名是:<%=pageContext.getSession().getAttribute("username") %><br>
<%
//跳转到注册页面
//pageContext.forward("reg.jsp");
pageContext.include("include.jsp");
%>
body>
html>
Config对象
config对象实在一个Servlet初始化时,JSP引擎向它传递信息用的,此信息包括
Servlet初始化时要用到的参数(通过属性名和属性值构成)以及服务器的有关信息
(通过传递一个ServletContext对象),常用方法如下:
exception对象是一个异常对象,当一个页面在运行过程中发生了异常,就产生
这个对象。如果一个JSP页面要应用此对象,就必须把isErrorPage设置为true,
否则无法编译。他实际上是java.lang.Throwable的对象,常用方法如下:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" errorPage="exception.jsp"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>测试异常的页面h1>
<hr>
<%
System.out.println(100/0); //抛出运行时异常,算数异常
%>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" isErrorPage="true" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>exception内置对象h1>
<hr>
异常的消息是:<%=exception.getMessage()%><BR>
异常的字符串描述:<%=exception.toString()%><br>
body>
html>
实现用户登录小例子
用户名admin,密码admin,登录成功使服务器内部转发到login_success.jsp页面,
并且提示登陆成功的用户名。如果登陆失败则重定向到login_failure.jsp页面。
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
String username ="";
String password ="";
request.setCharacterEncoding("utf-8");//防止中文乱码
username = request.getParameter("username");
password = request.getParameter("password");
//如果用户和密码都等于admin,则登录成功
if("admin".equals(username)&&"admin".equals(password))
{
session.setAttribute("loginUser", username);
request.getRequestDispatcher("login_success.jsp").forward(request, response);
}
else
{
response.sendRedirect("login_failure.jsp");
}
%>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>imooc - Logintitle>
<link type="text/css" href="css/login.css" rel="stylesheet" />
<link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js">script>
<script type="text/javascript" src="js/easyTooltip.js">script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js">script>
head>
<body>
<div id="container">
<div class="logo">
<a href="#"><img src="assets/logo.png" alt="" />a>
div>
<div id="box">
登录失败!请检查用户或者密码!<br>
<a href="login.jsp">返回登录a>
div>
div>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>imooc - Logintitle>
<link type="text/css" href="css/login.css" rel="stylesheet" />
<link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js">script>
<script type="text/javascript" src="js/easyTooltip.js">script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js">script>
head>
<body>
<div id="container">
<div class="logo">
<a href="#"><img src="assets/logo.png" alt="" />a>
div>
<div id="box">
<%
String loginUser = "";
if(session.getAttribute("loginUser")!=null)
{
loginUser = session.getAttribute("loginUser").toString();
}
%>
欢迎您<font color="red"><%=loginUser%>font>,登录成功!
div>
div>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>imooc - Logintitle>
<link type="text/css" href="css/login.css" rel="stylesheet" />
<link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js">script>
<script type="text/javascript" src="js/easyTooltip.js">script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js">script>
head>
<body>
<div id="container">
<div class="logo">
<a href="#"><img src="assets/logo.png" alt="" />a>
div>
<div id="box">
<form action="dologin.jsp" method="post">
<p class="main">
<label>用户名: label>
<input name="username" value="" />
<label>密码: label>
<input type="password" name="password" value="">
p>
<p class="space">
<input type="submit" value="登录" class="login" style="cursor: pointer;"/>
p>
form>
div>
div>
body>
html>
Javabean简介
Javabeans就是符合某种特定规范的Java类。使用Javabeans的好处是
解决代码重复编写,减少代码冗余,功能区分明确,提高了代码的维护性。
Javabean设计原则
public class Students {
private String name;
private int age;
public Students(){}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
this.age = age;
}
}
JSP动作元素(action elements),动作元素为请求处理阶段提供信息。动作
元素遵循XML元素的语法,有一个包含元素名的开始标签,可以有属性、可选
内容、与开始标签匹配的结束标签。
/*
* 用户类
* */
public class Users {
private String username;//用户名
private String password;//密码
//保留此默认的构造方法
public Users()
{
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="com.po.Users" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<%
Users user = new Users();
user.setUsername("admin"); //设置用户名
user.setPassword("123456");//设置密码
%>
<h1>使用普通方式创建javabean的实例h1>
<hr>
用户名:<%=user.getUsername() %><br>
密码:<%=user.getPassword() %><br>
body>
html>
作用:在Jsp页面中实例化或者在指定范围内使用javabean:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>
<h1>使用useBean动作创建javabean的实例h1>
<hr>
用户名:<%=myUsers.getUsername() %><br>
密码:<%=myUsers.getPassword() %><br>
body>
html>
作用:给已经实例化的Javabean对象的属性赋值,一共有四种形式。
(跟表单关联)
(跟表单关联)
(手工设置)
(跟request参数关联)
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'dologin.jsp' starting pagetitle>
<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">
head>
<body>
<jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>
<h1>setProperty动作元素h1>
<hr>
<%--
"myUsers" property="*"/>
--%>
<%--
"myUsers" property="username"/>
--%>
<%--
"myUsers" property="username" value="lisi"/>
"myUsers" property="password" value="888888"/>
--%>
<jsp:setProperty name="myUsers" property="username"/>
<jsp:setProperty name="myUsers" property="password" param="mypass"/>
用户名:<jsp:getProperty name="myUsers" property="username"/> <br>
密码:<jsp:getProperty name="myUsers" property="password"/><br>
<br>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting pagetitle>
<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">
head>
<body>
<h1>系统登录h1>
<hr>
<form name="loginForm" action="dologin.jsp?mypass=999999" method="post">
<table>
<tr>
<td>用户名:td>
<td><input type="text" name="username" value=""/>td>
tr>
<tr>
<td>密码:td>
<td><input type="password" name="password" value=""/>td>
tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="登录"/>td>
tr>
table>
form>
body>
html>
作用:获取指定Javabean对象的属性值。
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'dologin.jsp' starting pagetitle>
<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">
head>
<body>
<jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>
<h1>setProperty动作元素h1>
<hr>
<%--
"myUsers" property="*"/>
--%>
<%--
"myUsers" property="username"/>
--%>
<%--
"myUsers" property="username" value="lisi"/>
"myUsers" property="password" value="888888"/>
--%>
<jsp:setProperty name="myUsers" property="username"/>
<jsp:setProperty name="myUsers" property="password" param="mypass"/>
<%--
用户名:<%=myUsers.getUsername() %><br>
密码:<%=myUsers.getPassword() %><br>
--%>
用户名:<jsp:getProperty name="myUsers" property="username"/> <br>
密码:<jsp:getProperty name="myUsers" property="password"/><br>
body>
html>
Javabean的四个作用域范围
说明:使用useBeans的scope属性可以用来指定javabean的作用范围
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting pagetitle>
<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">
head>
<body>
<h1>系统登录h1>
<hr>
<form name="loginForm" action="dologin.jsp?mypass=999999" method="post">
<table>
<tr>
<td>用户名:td>
<td><input type="text" name="username" value=""/>td>
tr>
<tr>
<td>密码:td>
<td><input type="password" name="password" value=""/>td>
tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="登录"/>td>
tr>
table>
form>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'dologin.jsp' starting pagetitle>
<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">
head>
<body>
<jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>
<h1>setProperty动作元素h1>
<hr>
<%--
"myUsers" property="*"/>
--%>
<%--
"myUsers" property="username"/>
--%>
<%--
"myUsers" property="username" value="lisi"/>
"myUsers" property="password" value="888888"/>
--%>
<jsp:setProperty name="myUsers" property="username"/>
<jsp:setProperty name="myUsers" property="password" param="mypass"/>
<%--
用户名:<%=myUsers.getUsername() %><br>
密码:<%=myUsers.getPassword() %><br>
--%>
用户名:<jsp:getProperty name="myUsers" property="username"/> <br>
密码:<jsp:getProperty name="myUsers" property="password"/><br>
<br>
<br>
<a href="testScope.jsp">测试javabean的四个作用域范围a>
<%
request.getRequestDispatcher("testScope.jsp").forward(request, response);
%>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="com.po.Users" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'testScope.jsp' starting pagetitle>
<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">
head>
<body>
<h1>Javabean的四个作用域范围h1>
<hr>
<jsp:useBean id="myUsers" class="com.po.Users" scope="page"/>
用户名:<jsp:getProperty name="myUsers" property="username"/><br>
密码:<jsp:getProperty name="myUsers" property="password"/><br>
<hr>
<%--
用户名:<%=((Users)application.getAttribute("myUsers")).getUsername()%><br>
密码:<%=((Users)application.getAttribute("myUsers")).getPassword() %><br>
--%>
<%--
用户名:<%=((Users)session.getAttribute("myUsers")).getUsername()%><br>
密码:<%=((Users)session.getAttribute("myUsers")).getPassword() %><br>
--%>
<%--
用户名:<%=((Users)request.getAttribute("myUsers")).getUsername()%><br>
密码:<%=((Users)request.getAttribute("myUsers")).getPassword() %><br>
--%>
<%
String username = "";
String password = "";
if(pageContext.getAttribute("myUsers")!=null )
{
username = ((Users)pageContext.getAttribute("myUsers")).getUsername();
password = ((Users)pageContext.getAttribute("myUsers")).getPassword();
}
%>
用户名:<%=username%><br>
密码:<%=password%><br>
body>
html>
在Java Web 应用程序的jsp页面中有如下一行代码: 要使user对象可以作用于整个Web应用,下划线中应填入( )。
application
Model 1模型出现前,整个Web应用的情况:几乎全部由JSP页面
组成,JSP页面接受处理客户端请求,对请求处理后直接做出响应。
弊端:在界面层充斥着大量业务逻辑的代码和数据访问层的代码,
Web程序的可扩展性和可维护性非常差。
javabean的出项可以使jsp页面中使用Javabean封装的
数据或者调用Javabean的业务逻辑代码,这样大大提升
了程序的可维护性。
以下关于Javabean说法不正确的是( )。
Javabean只能封装数据不能封装业务逻辑。
Javabean就是符合某种设计规范的java类。
在Model1中,由Jsp页面去调用Javabean。
Javabean一般把属性设计为私有,使用setter和getter访问属性。
Javabean既可以封装数据同时也可以封装业务逻辑。
使用jsp+javabean完成用户登录功能
//用户的业务逻辑类
public class UsersDAO {
//用户登录方法
public boolean usersLogin(Users u)
{
if("admin".equals(u.getUsername())&&"admin".equals(u.getPassword()))
{
return true;
}
else
{
return false;
}
}
}
//用户类
public class Users {
private String username;
private String password;
public Users()
{
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
}
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
request.setCharacterEncoding("utf-8");
%>
<jsp:useBean id="loginUser" class="com.po.Users" scope="page"/>
<jsp:useBean id="userDAO" class="com.dao.UsersDAO" scope="page"/>
<jsp:setProperty property="*" name="loginUser"/>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
//如果用户和密码都等于admin,则登录成功
if(userDAO.usersLogin(loginUser))
{
session.setAttribute("loginUser", loginUser.getUsername());
request.getRequestDispatcher("login_success.jsp").forward(request, response);
}
else
{
response.sendRedirect("login_failure.jsp");
}
%>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>imooc - Logintitle>
<link type="text/css" href="css/login.css" rel="stylesheet" />
<link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js">script>
<script type="text/javascript" src="js/easyTooltip.js">script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js">script>
head>
<body>
<div id="container">
<div class="logo">
<a href="#"><img src="assets/logo.png" alt="" />a>
div>
<div id="box">
<form action="dologin.jsp" method="post">
<p class="main">
<label>用户名: label>
<input name="username" value="" />
<label>密码: label>
<input type="password" name="password" value="">
p>
<p class="space">
<input type="submit" value="登录" class="login" style="cursor: pointer;"/>
p>
form>
div>
div>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>imooc - Logintitle>
<link type="text/css" href="css/login.css" rel="stylesheet" />
<link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js">script>
<script type="text/javascript" src="js/easyTooltip.js">script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js">script>
head>
<body>
<div id="container">
<div class="logo">
<a href="#"><img src="assets/logo.png" alt="" />a>
div>
<div id="box">
<%
String loginUser = "";
if(session.getAttribute("loginUser")!=null)
{
loginUser = session.getAttribute("loginUser").toString();
}
%>
欢迎您<font color="red"><%=loginUser%>font>,登录成功!
div>
div>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<title>imooc - Logintitle>
<link type="text/css" href="css/login.css" rel="stylesheet" />
<link type="text/css" href="css/smoothness/jquery-ui-1.7.2.custom.html" rel="stylesheet" />
<script type="text/javascript" src="js/jquery-1.3.2.min.js">script>
<script type="text/javascript" src="js/easyTooltip.js">script>
<script type="text/javascript" src="js/jquery-ui-1.7.2.custom.min.js">script>
head>
<body>
<div id="container">
<div class="logo">
<a href="#"><img src="assets/logo.png" alt="" />a>
div>
<div id="box">
登录失败!请检查用户或者密码!<br>
<a href="login.jsp">返回登录a>
div>
div>
body>
html>
http协议的无状态性
无状态是指,当浏览器发送请求给服务器的时候,服务器响应客户端请求。
但是当同一个浏览器再一次发送请求给服务器的时候,服务器并不知道它
就是刚才那个浏览器。
简单的说,就是服务器不会去记得你,所以就是无状态协议。
保存用户的状态的两大机制
什么是Cookie?
Cookie:中文名称为“小甜饼”,是Web服务器保存在客户端的一些列文本信息。
生活中Cookie的应用
Cookie的作用
安全风险:容易泄露用户信息
Jsp中创建与使用Cookie
常用方法
方法名称 | 说明 |
---|---|
void setMaxAge(int expiry) | 设置cookie的有效期,以秒为单位 |
void setValue(String value) | 在cookie创建后,对cookie进行赋值 |
String getName() | 获取cookie的名称 |
String getValue() | 获取cookie的值 |
int getMaxAge() | 获取cookie的有效时间,以秒为单位 |
实现记忆用户名和密码功能
<%@ page language="java" import="java.util.*,java.net.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
head>
<body>
<h1>用户登录h1>
<hr>
<%
request.setCharacterEncoding("utf-8");
String username="";
String password = "";
Cookie[] cookies = request.getCookies();
if(cookies!=null&&cookies.length>0)
{
for(Cookie c:cookies)
{
if(c.getName().equals("username"))
{
username = URLDecoder.decode(c.getValue(),"utf-8");
}
if(c.getName().equals("password"))
{
password = URLDecoder.decode(c.getValue(),"utf-8");
}
}
}
%>
<form name="loginForm" action="dologin.jsp" method="post">
<table>
<tr>
<td>用户名:td>
<td><input type="text" name="username" value="<%=username %>"/>td>
tr>
<tr>
<td>密码:td>
<td><input type="password" name="password" value="<%=password %>" />td>
tr>
<tr>
<td colspan="2"><input type="checkbox" name="isUseCookie" checked="checked"/>十天内记住我的登录状态td>
tr>
<tr>
<td colspan="2" align="center"><input type="submit" value="登录"/><input type="reset" value="取消"/>td>
tr>
table>
form>
body>
html>
<%@ page language="java" import="java.util.*,java.net.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'dologin.jsp' starting pagetitle>
<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">
head>
<body>
<h1>登录成功h1>
<hr>
<br>
<br>
<br>
<%
request.setCharacterEncoding("utf-8");
//首先判断用户是否选择了记住登录状态
String[] isUseCookies = request.getParameterValues("isUseCookie");
if(isUseCookies!=null&&isUseCookies.length>0)
{
//把用户名和密码保存在Cookie对象里面
String username = URLEncoder.encode(request.getParameter("username"),"utf-8");
//使用URLEncoder解决无法在Cookie当中保存中文字符串问题
String password = URLEncoder.encode(request.getParameter("password"),"utf-8");
Cookie usernameCookie = new Cookie("username",username);
Cookie passwordCookie = new Cookie("password",password);
usernameCookie.setMaxAge(864000);
passwordCookie.setMaxAge(864000);//设置最大生存期限为10天
response.addCookie(usernameCookie);
response.addCookie(passwordCookie);
}
else
{
Cookie[] cookies = request.getCookies();
if(cookies!=null&&cookies.length>0)
{
for(Cookie c:cookies)
{
if(c.getName().equals("username")||c.getName().equals("password"))
{
c.setMaxAge(0); //设置Cookie失效
response.addCookie(c); //重新保存。
}
}
}
}
%>
<a href="users.jsp" target="_blank">查看用户信息a>
body>
html>
<%@ page language="java" import="java.util.*,java.net.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'users.jsp' starting pagetitle>
<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">
head>
<body>
<h1>用户信息h1>
<hr>
<%
request.setCharacterEncoding("utf-8");
String username="";
String password = "";
Cookie[] cookies = request.getCookies();
if(cookies!=null&&cookies.length>0)
{
for(Cookie c:cookies)
{
if(c.getName().equals("username"))
{
username = URLDecoder.decode(c.getValue(),"utf-8");
}
if(c.getName().equals("password"))
{
password = URLDecoder.decode(c.getValue(),"utf-8");
}
}
}
%>
<BR>
<BR>
<BR>
用户名:<%=username %><br>
密码:<%=password %><br>
body>
html>
session | cookie |
---|---|
在服务端保存用户信息 | 在客户端保存用户信息 |
session中保存的是Object类型 | cookie中保存的是String类型 |
随会话的结束而将其存储的数据销毁 | cookie可以长期保存在客户端 |
保存重要信息 | 保存不重要信息 |
下面关于Cookie与Session的对比描述不正确的是()
Cookie与Session都可以保存任意大小的对象类型
Cookie是客户端保存用户状态的机制
Session是服务器端保存用户状态的机制
Cookie与Session都可以设置生存期限
Cookie中对保存对象的大小是有限制的
如果想要设置当前Cookie的生存期限为24小时,以下代码正确的是
setMaxAge(86400);
include指令
语法:
<%@ include file=”URL” %>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'Include_Command.jsp' starting pagetitle>
<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">
head>
<body>
<h1>Include指令h1>
<hr>
<%@ include file="date.jsp"%>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%@ page import="java.text.*" %>
<%
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String s = sdf.format(d);
out.println(s);
%>
include动作
语法:
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'Include_Command.jsp' starting pagetitle>
<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">
head>
<body>
<h1>Include动作h1>
<hr>
<jsp:include page="date.jsp" flush="false"/>
body>
html>
include指令 | jsp:include动作 |
---|---|
语法格式 | <%@include file=”..” %> |
发生作用的时间 | 页面转换期间 |
包含的内容 | 文件的实际内容 |
转换成的Servlet | 主页面和包含页面转换成一个Servlet |
编译时间 | 较慢–资源必须被解析 |
执行时间 | 稍快 |
public final class include_005fcommand_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map _jspx_dependants;
static {
_jspx_dependants = new java.util.HashMap(1);
_jspx_dependants.put("/date.jsp", Long.valueOf(1504776944846L));
}
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=utf-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write('\r');
out.write('\n');
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" \r\n");
out.write(" );
out.print(basePath);
out.write("\">\r\n");
out.write(" \r\n");
out.write(" My JSP 'Include_Command.jsp' starting page \r\n");
out.write(" \r\n");
out.write("\t\r\n");
out.write("\t\r\n");
out.write("\t \r\n");
out.write("\t\r\n");
out.write("\t\r\n");
out.write("\t\r\n");
out.write("\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" Include指令
\r\n");
out.write("
\r\n");
out.write(" ");
out.write("\r\n");
out.write("\r\n");
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String s = sdf.format(d);
out.println(s);
out.write('\r');
out.write('\n');
out.write("\r\n");
out.write(" \r\n");
out.write("\r\n");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
public final class include_005faction_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=utf-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write('\r');
out.write('\n');
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write("\r\n");
out.write(" \r\n");
out.write(" );
out.print(basePath);
out.write("\">\r\n");
out.write(" \r\n");
out.write(" My JSP 'Include_Command.jsp' starting page \r\n");
out.write(" \r\n");
out.write("\t\r\n");
out.write("\t\r\n");
out.write("\t \r\n");
out.write("\t\r\n");
out.write("\t\r\n");
out.write("\t\r\n");
out.write("\r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" \r\n");
out.write(" Include动作
\r\n");
out.write("
\r\n");
out.write(" ");
org.apache.jasper.runtime.JspRuntimeLibrary.include(request, response, "date.jsp", out, false);
out.write("\r\n");
out.write(" \r\n");
out.write("\r\n");
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
public final class date_jsp extends org.apache.jasper.runtime.HttpJspBase
implements org.apache.jasper.runtime.JspSourceDependent {
private static final javax.servlet.jsp.JspFactory _jspxFactory =
javax.servlet.jsp.JspFactory.getDefaultFactory();
private static java.util.Map _jspx_dependants;
private javax.el.ExpressionFactory _el_expressionfactory;
private org.apache.tomcat.InstanceManager _jsp_instancemanager;
public java.util.Map getDependants() {
return _jspx_dependants;
}
public void _jspInit() {
_el_expressionfactory = _jspxFactory.getJspApplicationContext(getServletConfig().getServletContext()).getExpressionFactory();
_jsp_instancemanager = org.apache.jasper.runtime.InstanceManagerFactory.getInstanceManager(getServletConfig());
}
public void _jspDestroy() {
}
public void _jspService(final javax.servlet.http.HttpServletRequest request, final javax.servlet.http.HttpServletResponse response)
throws java.io.IOException, javax.servlet.ServletException {
final javax.servlet.jsp.PageContext pageContext;
javax.servlet.http.HttpSession session = null;
final javax.servlet.ServletContext application;
final javax.servlet.ServletConfig config;
javax.servlet.jsp.JspWriter out = null;
final java.lang.Object page = this;
javax.servlet.jsp.JspWriter _jspx_out = null;
javax.servlet.jsp.PageContext _jspx_page_context = null;
try {
response.setContentType("text/html; charset=utf-8");
pageContext = _jspxFactory.getPageContext(this, request, response,
null, true, 8192, true);
_jspx_page_context = pageContext;
application = pageContext.getServletContext();
config = pageContext.getServletConfig();
session = pageContext.getSession();
out = pageContext.getOut();
_jspx_out = out;
out.write("\r\n");
out.write("\r\n");
Date d = new Date();
SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
String s = sdf.format(d);
out.println(s);
out.write('\r');
out.write('\n');
} catch (java.lang.Throwable t) {
if (!(t instanceof javax.servlet.jsp.SkipPageException)){
out = _jspx_out;
if (out != null && out.getBufferSize() != 0)
try {
if (response.isCommitted()) {
out.flush();
} else {
out.clearBuffer();
}
} catch (java.io.IOException e) {}
if (_jspx_page_context != null) _jspx_page_context.handlePageException(t);
else throw new ServletException(t);
}
} finally {
_jspxFactory.releasePageContext(_jspx_page_context);
}
}
}
forward动作
语法:
等同于:
request.getRequestDispatcher(“/url”).forward(request,response);
param动作
语法:
常常与一起使用,作为其的子标签。
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'login.jsp' starting pagetitle>
<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">
head>
<body>
<h1>系统登录h1>
<hr>
<form name="loginForm" action="dologin.jsp" method="post">
<table>
<tr>
<td>用户名:td>
<td><input type="text" name="username"/>td>
tr>
<tr>
<td>密码:td>
<td><input type="password" name="password"/>td>
tr>
<tr>
<td colspan="2"><input type="submit" value="登录"/>td>
tr>
table>
form>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'dologin.jsp' starting pagetitle>
<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">
head>
<body>
<jsp:forward page="user.jsp">
<jsp:param value="[email protected]" name="email"/>
<jsp:param value="888888" name="password"/>
jsp:forward>
body>
html>
<%@ page language="java" import="java.util.*" contentType="text/html; charset=utf-8"%>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'user.jsp' starting pagetitle>
<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">
head>
<body>
<h1>用户资料h1>
<hr>
<%
request.setCharacterEncoding("utf-8");
String username = "";
String password = "";
String email = "";
if(request.getParameter("username")!=null)
{
username = request.getParameter("username");
}
if(request.getParameter("password")!=null)
{
password = request.getParameter("password");
}
if(request.getParameter("email")!=null)
{
email = request.getParameter("email");
}
%>
用户名:<%=username %><br>
密码:<%=password %><br>
电子邮箱:<%=email %><br>
body>
html>
下面关于include指令与include动作的对比描述不正确的是()
动作在编译期间被执行,而include指令在页面请求期间被执行
页面内容经常变化时更适合使用动作
页面内容不经常变化时更适合使用include指令
动作包含的是执行结果,而include指令包含的是文件内容
案例:商品浏览记录的应用
采用Model1(Jsp+Javabean)实现
实现DBhelper类型
String driver = “com.mysql.jdbc.Driver”;//数据库驱动
String url = “jdbc:mysql://localhost:3306/shopping?useUnicode=true&charaterEncoding=UTF”;//连接数据库的url地址
String username = “root”;//数据库的用户名
String password = “”;//数据库密码
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="root";//数据库的密码
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();
}
}
}
采用Model1(JSP+JavaBean)实现
//商品类
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;
}
}
//商品的业务逻辑类
public class ItemsDAO {
// 获得所有的商品信息
public ArrayList getAllItems() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList list = new ArrayList(); // 商品集合
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();
}
}
}
}
}
<%@ 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+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'index.jsp' starting pagetitle>
<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">
<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 list = itemsDao.getAllItems();
if(list!=null&&list.size()>0)
{
for(int i=0;iget (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() %> 价格:¥ <%=item.getPrice() %>dd>
dl>
div>
<%
}
}
%>
td>
tr>
table>
center>
body>
html>
//商品的业务逻辑类
public class ItemsDAO {
// 获得所有的商品信息
public ArrayList getAllItems() {
Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
ArrayList list = new ArrayList(); // 商品集合
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 getViewList(String list)
{
System.out.println("list:"+list);
ArrayList itemlist = new ArrayList();
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;
}
}
}
<%@ 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+"/";
%>
<html>
<head>
<base href="<%=basePath%>">
<title>My JSP 'details.jsp' starting pagetitle>
<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">
<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 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() %> 价格:<%=i.getPrice() %> ¥ dd>
dl>
div>
<%
}
}
%>
td>
tr>
table>
center>
body>
html>
《JAVA遇见HTML——JSP篇》视频地址