Jsp
Ø Web开发介绍(cgi)(javaee ssh (mvc))
Web技术的发展
静态网页与动态网页之间的区别(静态不能访问数据库)
PHP
Asp.net
Jsp
C/S和B/S
都是围绕数据库为中心
Ø myeclipse整合jdk和tomcat
1. 安装配置JDK
为了管理方便,此处安装jdk1.6.0_10到C:/Program Files/Java文件夹下,下面进行环境变量的配置。
右键我的电脑—属性—高级—环境变量:
(1) 首先,为了指定命令搜索路径,在系统变量的PATH变量中增加C:/Program Files/Java/jdk1.6.0_10/bin;。由于PATH变量中原本含有许多项,所以只需在最前面添加上述路径即可,注意末尾用分号隔开。
(2) 然后,为了指定类搜索路径,在系统变量中新建JAVA_HOME变量,变量名JAVA_HOME,变量值为C:/Program Files/Java/jdk1.6.0_10。
(3) 最后,在系统变量中新建classpath变量,用来指向jdk的安装目录,变量名为classpath,变量值为.;%JAVA_HOME%/lib /tools.jar;%JAVA_HOME%/lib/dt.jar;,注意最前面的.不可省略。
这样配置之后,单击开始菜单—运行—输入cmd—确定,键盘输入java -version(注意java与-之间有一空格)显示出版本信息,则证明配置成功。
2. 安装Tomcat
安装Tomcat应在配置MyEclipse之前进行,由于过程比较简单,便不再详述。此处只需注意安装过程中可将默认的端口号8080修改为8081,否则以后安装Oracle后会发生端口冲突,当然以后修改也可以,只是会比较麻烦。
3. 安装配置myeclipse
安装就不要讲了,这个比较简单,配置的话就按照以下步骤进行。
(1) 打开MyEclipse,在菜单拦中可以看到有Window一项,单击打开下拉菜单,找到Preferences一项,单击打开开始配置,如下图所示。
(2) 首先,在MyEclipse中配置JDK。从Preferences左侧菜单下找到Java,打开该项中的Installed JREs,如下图所示,点击Add进行添加。
3) 在弹出的Add JRE对话框中,找到JRE name,在此可以填入你想取的名字,如JDK;单击Browse..,选择JDK所在的目录,此处我选择的是C:/Program Files/Java/jre6,则自动生成JRE system libraries,如下图所示,点击OK完成此项配置
4) 返回Preferences,将刚刚配置的JRE选中。
5) 然后,在MyEclipse中配置Tomcat。从Preferences左侧菜单下找到MyEclipse Enterprise Workbench,打开其中的Servers项,找到Tomcat,选择自己安装的版本,此处我选择Tomcat 6.x,将其设为Enable,在Browse..目录下选择Tomcat的安装目录,如下图所示。
6) 打开Tomcat 6.x下的JDK选项,选择刚刚配置好的JDK,如下图所示,点击OK,整个配置工作就完成了
7) 现在就可以开启Tomcat服务了,大功告成
u 常见的web服务器
n WebLogic (支持J2EE规范)
n WebSphere (支持J2EE规范)
n Tomcat (apache免费)(支持jsp和servlet,但不支持EJB(要用JBOSS))
u 介绍Tomcat(注意:不要把tom猫放在有汉字和空格的目录下)
Tomcat 的下载地址
http://tomcat.apache.org/download-60.cgi(注意)
环境变量的设置
n JAVA_HOME
Tomcat目录的介绍
虚拟目录的配置
n <Context path="/Hello" docBase="D:\Workspaces\Hello\WebRoot"/>
Ø reloadable="true”自动加载 以后再说
n 如果将我们的网站放在webapps目录服务器自动配置 虚拟目录,目录名就我们网站的根目录名
n 也可以在Catalina(服务器引擎)中新建一个任意的xml 文件并在里边写入<Context docBase="D:\qqq"/>,那么 这个xml文件的名字就是我们的虚拟目录,如果文件为 aaa#bbb就是两级虚拟目录。
虚拟主机的配置
n <Host name="www.mazheng.com" appBase="d:\web">
n <Context path="" docBase="D:\web\app1"/>
n </Host>
n 如果想要实现直接用www.mazheng.com访问我的网站就要这么这么干
1.配置虚拟主机,并且path为空
2.配置web.xml的默认首页
<welcome-file-list>
<welcome-file>index.html</welcome-file>
</welcome-file-list>
3.将8080端口设置成80端口
4.向drivers中添加域名解析
配置tomcat的管理器的用户名和密码
将tomcat整合到myeclipse中
Web工程的目录结构
u 复习html,css,js
u XML
由前导区和数据区组成
规范的指定
Xml的解析
u JAVAEE的13种核心技术(api)
JAVAEE的核心API与组件
JAVAEE平台由一整套服务(Services)、应用程序接口(APIs)和协议构成,它对开发基于Web的多层应用提供了功能支持,下面对JAVAEE中的13种技术规范进行简单的描述(限于篇幅,这里只进行简单的描述):
1、JDBC(Java Database Connectivity) JDBC API为访问不同的数据库提供了一种统一的途径,象ODBC一样,JDBC对开发者屏蔽了一些细节问题,另外,JDCB对数据库的访问也具有平台无关性。
2、JNDI(Java Name and Directory Interface) JNDI API被用于执行名字和目录服务。它提供了一致的模型来存取和操作企业级的资源如DNS和LDAP,本地文件系统,或应用服务器中的对象。
3、EJB(Enterprise JavaBean) JAVAEE技术之所以赢得媒体广泛重视的原因之一就是EJB。它们提供了一个框架来开发和实施分布式商务逻辑,由此很显著地简化了具有可伸缩性和高度复杂的企业级应用的开发。EJB规范定义了EJB组件在何时如何与它们的容器进行交互作用。容器负责提供公用的服务,例如目录服务、事务管理、安全性、资源缓冲池以及容错性。但这里值得注意的是,EJB并不是实现JAVAEE的唯一途径。正是由于JAVAEE的开放性,使得有的厂商能够以一种和EJB平行的方式来达到同样的目的。
4、RMI(Remote Method Invoke) 正如其名字所表示的那样,RMI协议调用远程对象上方法。它使用了序列化方式在客户端和服务器端传递数据。RMI是一种被EJB使用的更底层的协议。
5、Java IDL/CORBA 在Java IDL的支持下,开发人员可以将Java和CORBA集成在一起。他们可以创建Java对象并使之可在CORBA ORB中展开, 或者他们还可以创建Java类并作为和其它ORB一起展开的CORBA对象的客户。后一种方法提供了另外一种途径,通过它Java可以被用于将你的新的应用和旧的系统相集成。
6、JSP(Java Server Pages) JSP页面由HTML代码和嵌入其中的Java代码所组成。服务器在页面被客户端所请求以后对这些Java代码进行处理,然后将生成的HTML页面返回给客户端的浏览器。
7、Java Servlet Servlet是一种小型的Java程序,它扩展了Web服务器的功能。作为一种服务器端的应用,当被请求时开始执行,这和CGI Perl脚本很相似。Servlet提供的功能大多与JSP类似,不过实现的方式不同。JSP通常是大多数HTML代码中嵌入少量的Java代码,而servlets全部由Java写成并且生成HTML。
8、XML(Extensible Markup Language) XML是一种可以用来定义其它标记语言的语言。它被用来在不同的商务过程中共享数据。 XML的发展和Java是相互独立的,但是,它和Java具有的相同目标正是平台独立性。通过将Java和XML的组合,您可以得到一个完美的具有平台独立性的解决方案。
9、JMS(Java Message Service) JMS是用于和面向消息的中间件相互通信的应用程序接口(API)。它既支持点对点的域,有支持发布/订阅(publish/subscribe)类型的域,并且提供对下列类型的支持:经认可的消息传递,事务型消息的传递,一致性消息和具有持久性的订阅者支持。JMS还提供了另 一种方式来对您的应用与旧的后台系统相集成。
10、JTA(Java Transaction Architecture) JTA定义了一种标准的API,应用系统由此可以访问各种事务监控。
11、JTS(Java Transaction Service) JTS是CORBA OTS事务监控的基本的实现。JTS规定了事务管理器的实现方式。该事务管理器是在高层支持Java Transaction API (JTA)规范,并且在较底层实现OMG OTS specification的Java映像。JTS事务管理器为应用服务器、资源管理器、独立的应用以及通信资源管理器提供了事务服务。
12、JavaMail JavaMail是用于存取邮件服务器的API,它提供了一套邮件服务器的抽象类。不仅支持SMTP服务器,也支持IMAP服务器。
13、JAF(JavaBeans Activation Framework) JavaMail利用JAF来处理MIME编码的邮件附件。MIME的字节流可以被转换成Java对象,或者转换自Java对象。大多数应用都可以不需要直接使用JAF
u Servlet(服务器端小程序)
第一个Servlet程序
1.在webapps里创建一个文件夹myweb,作为你的网站根目录
在myweb中创建一个目录WEB-INF
在WEB-INF中创建一个classes目录
在classes目录中创建你servlet程序
package cn.webapp;
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletDemo1 extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
response.setContentType("text/html");
PrintWriter out = response.getWriter();
out.println("hello!!");
/*out.flush();
out.close();*/
}
public void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
doGet(request, response);
}
}
n 配置Servlet-api.jar
Set classpath=%classpath%;D:\apache-tomcat-6.0.35-windows-x86\apache-tomcat-6.0.35\lib\servlet-api.jar
将tomcat整合到myeclipse中
在myeclipse中开发servlet
n 介绍自动创建的目录
n 修改myeclipse中的servlet模板
u D:\Users\Administrator\AppData\Local\Genuitec\Common\plugins\com.genuitec.eclipse.wizards_8.6.0.me201007140905.jar\templates
n *通配符
<servlet-name>ServletDemo2</servlet-name>
<url-pattern>*.aa</url-pattern>
n 缺省servlet(但是一般大家不要这么做,不然服务器自己默认的servlet就没有用了,在conf中的web.xml中可以看到服务器缺省的servlet);
<servlet-name>ServletDemo2</servlet-name>
<url-pattern>/</url-pattern>
Servlet的生命周期
l Servlet一般只会在第一次访问时创建,然后一直停留在内存中,直到服务器停止才会被释放,但是每一次请求都会产生request和response。
l 加载时创建servlet(一般不会这样用的,加载框架文件时就是这样用的)
<servlet>
<servlet-name>ServletDemo1</servlet-name>
<servlet-class>cn.webapp.ServletDemo1</servlet-class>
<!--加入了以下的标记,就会在启动时加载-->
<load-on-startup>1</load-on-startup>
</servlet>
l Servlet创建的时候会调用init方法和destroy方法
写一个登陆
乱码问题:
//设置请求的编码(但是这种设置方式只对post方式有效)
request.setCharacterEncoding("UTF-8");
//设置输出的编码
response.setCharacterEncoding("UTF-8");
//设置html的编码
response.setContentType("text/html;charset=UTF-8");
String name = request.getParameter("username");
//get方式就只有自己做如下的转码了哟
name = new String(name.getBytes("iso8859-1"),"UTF-8");
String ps = request.getParameter("password");
PrintWriter out = response.getWriter();
out.println("welcome:"+name);
System.out.print(name);
HTTP协议
n http协议时建立在tcp协议之上的
n 要先开启telnet的客服端,开启你的应用服务器
GET /SoftWeb/index.jsp HTTP/1.1
Host:localhost
n
n http1.0和http1.1的区别(1.0请求处理完tcp立刻断掉)
n 请求头
GET /myweb/index.html HTTP/1.1(请求行)
消息头
Accept-Encodinggzip, deflate
Hostlocalhost:8080
User-AgentMozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Accepttext/html, application/xhtml+xml, */*
Accept-Languagezh-CN
n 响应头:
HTTP/1.1 304 Not Modified(状态行)
消息头
ETagW/"37-1368603309298"
Content-Typetext/html
Content-Length37
Last-ModifiedWed, 15 May 2013 07:35:09 GMT
必须要有一个空行表示消息头结束
内容
<font color="red">adsfadsfadsf</font>
n 消息头:用来描述http消息本身的信息
n Get和post的区别
n 响应头的状态码
n HTTP请求的常用头
Accept: text/html,image/*
Accept-Charset: ISO-8859-1
Accept-Encoding: gzip,compress
Accept-Language: en-us,zh-cn
Host: www.ttt.org:80
If-Modified-Since: Tue, 11 Jul 2000 18:23:51 GMT
Referer: http://www.ittt.org/index.jsp
User-Agent: Mozilla/4.0 (compatible; MSIE 5.5; Windows NT 5.0)
Cookie
Connection: close/Keep-Alive
Date: Tue, 11 Jul 2000 18:23:51 GMT
n HTTP请求中的常用响应头
Location: http://www.ttt.org/index.jsp
Server:apache tomcat
Content-Encoding: gzip
Content-Length: 80
Content-Language: zh-cn
Content-Type: text/html; charset=GB2312
Last-Modified: Tue, 11 Jul 2000 18:23:51 GMT
Refresh: 1;url=http://www.ttt.org
Content-Disposition: attachment; filename=aaa.zip
Transfer-Encoding: chunked
Set-Cookie:SS=Q0=5Lb_nQ; path=/search
Expires: -1
Cache-Control: no-cache
Pragma: no-cache
Connection: close/Keep-Alive
Date: Tue, 11 Jul 2000 18:23:51 GMT
Servlet的线程安全问题
n 在我们有多个请求时,服务器可以利用多线程产生多个Servlet对象实例来响应,由于使用了多线线程,所以可能存在线程安全,api提过了一个SingleThreadMOdel接口 作为单线程运行的标志,但是实际上没有用,所以只有靠大家自己运用以前学习的解决线程安全的方式。
ServletConfig接口(在ServletConfig中封装了Servlet容器对象和Servlet的配置参数信息)
PrintWriter out = response.getWriter();
//out.print(getServletName());
out.println(getServletConfig().getServletName());
Enumeration e = getInitParameterNames();
while(e.hasMoreElements()){
String key = (String) e.nextElement();
String value = getInitParameter(key);
out.println(value);
}
ServletContext接口(代表一个web应用(域))
n 取得服务的相关信息
System.out.println(this.getServletContext().getServerInfo());
n 获得web应用的根目录
System.out.println(this.getServletContext().getContextPath());
n 获取web应用的参数(配置数据库)
<context-param>
<param-name>name</param-name>
<param-value>haoren</param-value>
</context-param>
String sex = this.getServletContext().getInitParameter("sex");
System.out.print(sex);
n 数据共享
this.getServletContext().setAttribute("address", "chengdu");
String address = (String) this.getServletContext().getAttribute("address");
n 读取资源文件
n 方式一:
1.创建配置文件 (properties)
2.利用
3. InputStream getResourceAsStream(String path)(注意这里的path应该是发布后的如/WEB-INF/classes)获得一个输入流,是相对于web应用的根目录
4.让后用我们以前学过的Properties来对文件中的键值(会用到load(InputStream inStream)和String getProperty(String key))
n 方式二
通过String getRealPath(String path)方法可以通过相对路径获得绝对路径,然后就可以同输入流来读资源。(直接使用输入流是不可以的,因为其相对的路径是jdk的bin目录)
介绍service与doGet和doPost的关系
??有了服务器后不是servlet程序的java程序读取文件的路径问题(解决这个问题就要靠类装载器)
类装载器(ClassLoader)(查阅javase手册)
n InputStream getResourceAsStream(String path)(这里的path是相对于classes文件夹)(不可以取得实时更新的内容)
InputStream in = ServletDemo4.class.getClassLoader().getResourceAsStream("pro.properties");
n URL getResource(String name) (可以取得实时更新的内容)
String path = ServletDemo4.class.getClassLoader().getResource("pro.properties").getPath();
HttpServletResponse
n response.getOutputStream();(注意乱码的问题,可以用setHeader()解决乱码)
n Ex:
response.setHeader("Content-type", "text/html;charset=UTF-8");
OutputStream out = response.getOutputStream();
out.write("好人".getBytes("UTF-8"));
n response.setCharacterEncoding("UTF-8");与response.setHeader("Content-type", "text/html;charset=UTF-8");的区别
n response.setContentType("text/html;charset=UTF-8");是
response.setHeader("Content-type","text/html;charset=UTF-8");加上response.setCharacterEncoding("UTF-8");的简写
实现资源下载功能:
//获得要下载的资源的地址
String filePath = this.getServletContext().getRealPath("/download/佛祖.jpg");
//切取药下载资源的名字
System.out.print(filePath);
int index = filePath.lastIndexOf("\\");
String fileName = filePath.substring(index+1);
//弹出下载对话框
response.setHeader("content-disposition", "attachment;filename="+URLEncoder.encode(fileName, "UTF-8"));
//将读取到的资源写给浏览器
InputStream in = new FileInputStream(filePath);
OutputStream out = response.getOutputStream();
byte[] b = new byte[1024];
int len = 0;
while((len = in.read(b))!=-1){
out.write(b, 0, len);
}
in.close();
让浏览器定时刷新
response.setHeader("Refresh", "2");
response.getWriter().println(new java.util.Date());
跳转:
response.getWriter().write("sdfsdfs");
response.setHeader("refresh", "3;url=/WebTest/index.jsp");
缓存的管理
n 禁止使用缓存
response.setContentType("text/html;charset=UTF-8");
/*
response.setHeader( "Pragma", "no-cache" );
response.setDateHeader("Expires", 0);
response.addHeader( "Cache-Control", "no-cache" );
*/
PrintWriter out = response.getWriter();
out.println("<form action=/WebTest/index.jsp mathed=post>");
out.println("<input type=text>");
out.println("<input type=submit value=提交>");
out.println("</form>");
n 对缓存的设置
Jsp文件:
<a href="ServletCache2">缓存</a>
Servlet文件:
response.setDateHeader("expires",System.currentTimeMillis()+1000*600);
response.getWriter().write("sdfadsfasdfadsf");
n 转发
RequestDispatcher rd = this.getServletContext().getRequestDispatcher("/index.jsp");
rd.forward(request, response);
n 重定向
response.sendRedirect("index.jsp");
(通过不能同时使用response.getOutputStream()和response.getWriter()来区别转发和重定向)
HttpServletRequest
获得请求行相关信息
//获得提交的方式
System.out.println(request.getMethod());
//取得资源名称
System.out.println(request.getRequestURI());
//取得网络资源地址
System.out.println(request.getRequestURL());
//请求行中的参数(
例如:http://localhost:8080/SoftWeb/Request?name=huairen)
System.out.println(request.getQueryString());
(在f12中查看)
请求 GET /SoftWeb/Request?name=huairen HTTP/1.1
Accept text/html, application/xhtml+xml, */*
Accept-Language zh-CN
User-Agent Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0)
Accept-Encoding gzip, deflate
Host localhost:8080
Connection Keep-Alive
n 获得网络连接的相关信息
//获得客户机的ip地址
System.out.println(request.getRemoteAddr());
//获得客户主机(要有DNS服务器)
System.out.println(request.getRemoteHost());
//获得服务的端口
System.out.println(request.getServerPort());
n 获取请求头
l getHeader(String name)
l getHeaders(String name)
l getHeaderNames()
n 获得表单数据
n 转发给jsp
n 防止盗链referer
response.setContentType("text/html;charset=UTF-8");
String referrer = request.getHeader("referer");
String server = "http://"+request.getServerName();
System.out.println(referrer);
if(referrer!=null&&referrer.startsWith(server)){
System.out.println("ok");
}
n 总结路径
n 防止重复提交
<script type="text/javascript">
var isSubmited = false;
function is(){
if(!isSubmited){
isSubmited = true;
return true;
}
else{
alert("不能重复提交");
return false;
}
}
</script>
<FORM action="/SchoolInfo/UserDemo1" method="post" submit="return is()">
会话技术
Cookie
n 一般只准许放300个cookie
n 一个站点一般只准许放20个cookie
n 一个cookie大小限制为4kb
n 记录客户是第几次来
response.setContentType("text/html;charset=UTF-8");
PrintWriter out = response.getWriter();
int count = 1;
Cookie[] ck = request.getCookies();
if(ck == null){
Cookie cookie = new Cookie("count", "1");
cookie.setMaxAge(3600);
cookie.setPath("/WebTest");
response.addCookie(cookie);
}else{
for(int i=0;i<ck.length;i++){
if("count".equals(ck[i].getName())){
System.out.print(Integer.parseInt(ck[i].getValue()));
count = Integer.parseInt(ck[i].getValue())+1;
/*//System.out.print(count);
ck[i].setValue(count+"");
response.addCookie(ck[i]);*/
Cookie cookie = new Cookie("count", count+"");
cookie.setMaxAge(3600);
cookie.setPath("/WebTest");
response.addCookie(cookie);
}
}
}
out.print("欢迎您的第"+count+"次");
n
n
n
获得前一次的访问时间
PrintWriter out = response.getWriter();
Cookie[] ck = request.getCookies();
for(int i=0;ck!=null&&i<ck.length;i++){
if("time".equals(ck[i].getName())){
out.print(new Date(Long.parseLong(ck[i].getValue())).toLocaleString());
}
}
Cookie cookie = new Cookie("time", System.currentTimeMillis()+"");
cookie.setMaxAge(3600);
cookie.setPath("/WebTest");
response.addCookie(cookie);
Session
n 介绍Session的原理(只能存活30分钟)
n 介绍session与cookie的区别和原理
n Session的创建
HttpSession hs = request.getSession();
//HttpSession hs = request.getSession(false);(只取不创建)
hs.setAttribute("name", "haoren");
n 修改Session存sessionid号的cookie的存活时间
HttpSession hs = request.getSession();
String id = hs.getId();
Cookie ck = new Cookie("JSESSIONID", id);
ck.setPath("/WebTest");
ck.setMaxAge(1800);
response.addCookie(ck);
hs.setAttribute("name", "haoren");
提前说下数据库
u 修改jsp模板
u 第一个jsp案例:
案例:Hello
别忘了配置虚拟目录
<Context path="/Hello" docBase="D:\Workspaces\Hello\WebRoot"/>
u Jsp中的注释:
显示注释:<!---->
隐式注释://,/**/,<%-- --%>(jsp注释)
u Scriptlet(脚本小程序)
第一种<%%>:可以定义局部变量和语句等
通过以下案例介绍jsp 的工作原理
Ex:
<%
int age = 12;
String name = "haoren";
out.print(name+"有"+age+"岁");
%>
第二种<%!%>:可以定义类和方法(很少这样弄)
第三种<%=%>:用于输出内容
注意:jsp中少用out.print()来输出
u Scriptlet标签
和使用<% %>的效果是一样的。
<jsp:scriptlet >
Java代码
</jsp:scriptlet >
Page指令设置jsp页面属性
u 设置页面mime(用contentType来实现)
Mime:多功能internet邮件扩充服务器,用指定一种扩展名用何种应用程序打开,
将jsp文件用word打开
在tomcat的conf/web.xml中可以看到mime的类型
<mime-mapping>
<extension>doc</extension>
<mime-type>application/msword</mime-type>
</mime-mapping>
<mime-mapping>
<extension>dtd</extension>
<mime-type>application/xml-dtd</mime-type>
</mime-mapping>
u 设置文件的编码(pageEncoding)
<%@ page language="java" import="java.util.*" pageEncoding="utf-8"%>
注意:
u 错误页的设置:
设置错误:(用web.xml的方式,处理错误的页面必须大于1k)
<%@page errorPage=”error.jsp”%>出现错误跳转到errorr.jsp页面
跳转到的页面要设置<%@page idErrorPage=”true”%>
也可以通过设置web.xml文件来实现错误页的实现
如果错误处理页也无法打开
就需要在错误处理页里做如下的处理
u 包含指令:
静态包含: 先包含在执行
<%@ include file="/head.jsp" %>
asdfadsfasdfasdfadsfadsf
<%@ include file="/foot.jsp" %>
Ø 查看include的源文件如下, 所以被包含的文件只留正文和page指令
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
headpage!!!
</body>
</html>
asdfadsfasdfasdfadsfadsf
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
footpage!!!
</body>
</html>
</body>
</html>
静态包含只会形成一个servlet文件
动态包含:先执行再包含
(可以传递参数和被包含的页面可以生成servlet)
<jsp:include page="/head.jsp" >
<jsp:param value="mazheng" name="name"/>
</jsp:include>
注意动态包含与静态包含的区别
u 跳转指令forward
案例:Include中的Forward.jsp
主页面:
<%
String username="haoren" ;
%>
<jsp:forward page="/recivce.jsp">
<jsp:param name="name" value="<%=username%>"/>
<jsp:param name="age" value="23"/>
</jsp:forward>
接受页面
<%=request.getParameter("name") %>
<%=request.getParameter("age") %>
Ø 九大内置对象
Ø 四种属性的范围
<%
//pageContext.setAttribute("name","haoren");
//request.setAttribute("name","haoren");
//session.setAttribute("name","haoren");
application.setAttribute("name","haoren"); %>
<jsp:forward page="/page1.jsp"></jsp:forward>
<a href="page1.jsp">点击</a>
<%
// String name = (String)pageContext.getAttribute("name");
// String name = (String)request.getAttribute("name");
//String name = (String)session.getAttribute("name");
String name = (String)application.getAttribute("name");
%>
<%=name %>
Ø PageContext详细介绍
一、代表 page域
二、可以获得其他内置对象
pageContext.getRequest().setAttribute("name","haoddren");
三、访问其他内置对象
1. pageContext.setAttribute("name","haoren",pageContext.REQUEST_SCOPE);
2. String name = (String)pageContext.findAttribute("name");
四、可以跳转
pageContext.forward("page1.jsp");
Ø Jsp标签
n 什么是标签(标签的意义在于jsp中少写或者不写java代码)
jsp:forward
jsp:include
jsp:param
Ø Javabean
n 每一个class都必须有包
n 类必须为public
n Bean必须有一个无参的构造方法
n 所有的属性都必须为私有
n 每个属性必须有set和get方法
<jsp:useBean id="person" class="cn.bean.domain.Person" scope="page"></jsp:useBean>
<%person.setName("haoren"); %>
<%=person.getName() %>
n 处理表单数据
n 设置属性的值
第一种:(通过参数名和属性名自动匹配)
<jsp:useBean id="person" class="cn.xinhua.domain.Person" scope="page">
</jsp:useBean>
<jsp:setProperty property="*" name="person"/>
<%=person.getName() %>
<%=person.getAge() %>
第二种
<jsp:setProperty property="name" name="person"/>
第三种
<jsp:setProperty property="name" name="person" param="age"/>(这里的name代表的是属性,age代表的是表单文本框的名字)
第四种直接赋值
<jsp:setProperty name="person" property="name" value="mzh"/>
n 取得属性的值
<jsp:getProperty property="name" name="person"/>
n javaBean的保存范围
<jsp:useBean id="person" class="cn.xinhua.domain.Person" scope="request">
</jsp:useBean>
<%--=person.getCount() --%>
<jsp:getProperty property="count" name="person"/>
<jsp:forward page="/jspbean1.jsp"></jsp:forward>
n 移除javaBean
<%request.removeAttribute("person"); %>
u EL表达式
v 好处:如果取得的值是空,则返回“”而不是null
<%pageContext.setAttribute("name","page")%>
${pageScope.name}
v 访问四种属性的值
<%
pageContext.setAttribute("name","page");
request.setAttribute("name","request");
session.setAttribute("name","session");
application.setAttribute("name","application");
%>
${pageScope.name}
${requestScope.name}
${sessionScope.name}
${applicationScope.name}
v 接受请求参数
${param.name}
(http://localhost:8080/WebTest/el1.jsp?name=haoren)
v 接受一组的参数
n 提交端
<form action="/WebTest/el1.jsp" method="post">
<input type="checkbox" name="enjoy" value="打架" checked="checked">打架
<input type="checkbox" name="enjoy" value="打人">打人
<input type="checkbox" name="enjoy" value="打球">打球
<input type="submit" value="提交">
</form>
n 接收端
<%request.setCharacterEncoding("UTF-8"); %>
${paramValues.enjoy[0]}
${paramValues.enjoy[1]}
${paramValues.enjoy[2]}
n 集合操作
l 1.
<%
List list = new ArrayList();
list.add("中国");
list.add("美国");
list.add("小日本");
request.setAttribute("hh",list);
%>
${hh[0] }
${hh[1] }
${hh[2] }
l 2.
<%
Map map = new HashMap();
map.put("name","haoren");
map.put("sex","fmial");
request.setAttribute("hh",map);
%>
${hh.name }
${hh["sex"] }
n 访问对象的属性
<%
Person p = new Person();
p.setName("haoren");
p.setAge(23);
request.setAttribute("person",p);
%>
${person.name };
${person.age };
n 通过servlet获得相关的信息,再转发给jsp显示
l Servlet部分
Person p = new Person();
p.setName("haoren");
p.setAge(23);
request.setAttribute("person",p);
request.getRequestDispatcher("el3.jsp").forward(request, response);
l Jsp部分
${person.name };
${person.age };
n 集合里装对象的情况
Map map = new HashMap();
map.put("p1",new Person("hauiren"));
map.put("p2",new Person("mzheng"));
request.setAttribute("hh",map);
%>
${hh.p1.name }
${hh.p2.name }
n EL表达式可以进行算术,关系运算和逻辑运算
u 自定义空标签
1、定义标签类继承TagSupport类
package cn.xinhua.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;
public class mytag extends TagSupport {
public int doStartTag() throws JspException{
JspWriter out = this.pageContext.getOut();
try {
out.print("haoren");
} catch (IOException e) {
throw new RuntimeException(e);
}
return TagSupport.SKIP_BODY;
}
}
2、注册标签
<?xml version="1.0" encoding="UTF-8" ?>
<taglib xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-jsptaglibrary_2_0.xsd"
version="2.0">
<description>A tag library exercising SimpleTag handlers.</description>
<tlib-version>1.0</tlib-version>
<short-name>firsttag</short-name>
<uri>http://www.xinhua.com</uri>
<tag>
<description>Outputs Hello, World</description>
<name>hello</name>
<tag-class>cn.xinhua.tag.mytag</tag-class>
<body-content>empty</body-content>
</tag>
</taglib>
3、在jsp页面中引用标签
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
(方式一:)<%--@ taglib prefix="test" uri="/WEB-INF/testtab.tld"--%>
(方式二:)<%@ taglib prefix="testtab" uri="http://www.xinhua.com"%>
(方式三:)<%--@ taglib prefix="test" uri="testtab"--%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<testtab:hello/>
</body>
</html>
方式三中在web.xml中对定义的标签类进行注册的代码
<jsp-config>
<taglib>
<taglib-uri>testtab</taglib-uri>
<taglib-location>/WEB-INF/testtab.tld</taglib-location>
</taglib>
</jsp-config>
定义带有属性的标签
定义标签类
package cn.xinhua.tag;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class attributetag extends TagSupport{
private String format;
public String getFormat() {
return format;
}
public void setFormat(String format) {
this.format = format;
}
@Override
public int doStartTag() throws JspException {
SimpleDateFormat sdf = new SimpleDateFormat(format);
try {
this.pageContext.getOut().write(sdf.format(new Date()));
} catch (IOException e) {
throw new RuntimeException(e);
}
return TagSupport.SKIP_BODY;
}
}
注册标签
<tag>
<description>Outputs Hello, World</description>
<name>attribute</name>
<tag-class>cn.xinhua.tag.attributetag</tag-class>
<body-content>empty</body-content>
<attribute>
<name>format</name>
<required>true</required>
<rtexprvalue>true</rtexprvalue>
</attribute>
</tag>
在jsp中引用
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%--@ taglib prefix="test" uri="/WEB-INF/testtab.tld"--%>
<%@ taglib prefix="testtab" uri="http://www.xinhua.com"%>
<%@ taglib prefix="attributetag" uri="http://www.xinhua.com"%>
<%--@ taglib prefix="test" uri="testtab"--%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<testtab:hello/>
<attributetag:attribute format="yyyy-MM-dd HH:mm:ss:SSS"/>
</body>
</html>
详细介绍TagSupport类
l 定义有标签体的标签并控制标签体是否显示
标签类
package cn.beida.tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class Tag2 extends TagSupport {
@Override
public int doStartTag() throws JspException {
// TODO Auto-generated method stub
//return TagSupport.EVAL_BODY_INCLUDE;
return TagSupport.SKIP_BODY;
}
}
配置
<tag>
<name>hello2</name>
<tag-class>cn.beida.tag.Tag2</tag-class>
<body-content>JSP</body-content>
</tag>
Jsp文件:
<testtab2:hello2>sdsdsdsdsd</testtab2:hello2>
l 页面是否显示
标签类
package cn.beida.tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class Tag3 extends TagSupport {
@Override
public int doEndTag() throws JspException {
// TODO Auto-generated method stub
//return TagSupport.SKIP_PAGE;
return TagSupport.EVAL_PAGE;
}
}
配置
<tag>
<name>hello3</name>
<tag-class>cn.beida.tag.Tag3</tag-class>
<body-content>empty</body-content>
</tag>
Jsp页面:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@taglib prefix="testtab1" uri="http://www.qinghua.com" %>
<%@taglib prefix="testtab2" uri="http://www.qinghua.com" %>
<%@taglib prefix="testtab3" uri="http://www.qinghua.com" %>
<testtab3:hello3/>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<font color=""></font>
<testtab1:hello inf="mazhengishaoren"/>
<testtab2:hello2>sdsdsdsdsd</testtab2:hello2>
</body>
</html>
l 循环输出标签体
标签类
package cn.beida.tag;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;
public class Tag4 extends TagSupport {
int i = 0;
public int doStartTag() throws JspException {
// TODO Auto-generated method stub
return TagSupport.EVAL_BODY_INCLUDE;
}
@Override
public int doAfterBody() throws JspException {
i++;
if(i<5){
return TagSupport.EVAL_BODY_AGAIN;
}
else{
return TagSupport.SKIP_BODY;
}
}
}
配置
......
Jsp
......
l 修改标签体的内容(要继承BodyTagSupport)
实现标签类
package cn.beida.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.BodyContent;
import javax.servlet.jsp.tagext.BodyTagSupport;
public class Tag5 extends BodyTagSupport {
public int doStartTag() throws JspException {
return BodyTagSupport.EVAL_BODY_BUFFERED;
}
public int doEndTag() throws JspException {
BodyContent bc = this.getBodyContent();
String s = bc.getString();
String st = s+"haha";
try {
this.pageContext.getOut().print(st);
} catch (IOException e) {
// TODO Auto-generated catch block
throw new RuntimeException(e);
}
return BodyTagSupport.EVAL_PAGE;
}
}
配置
......
Jsp
......
u 简单标签体SimpleTagSupport
u
l 简单标签的执行流程:
调用标签---实例化标签类---setJspContext(传递pagecotext)---setParent(传递父标签)---setJspBody(传递标签体)---doTag()
l 控制标签体是否显示
package cn.beida.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class Tag6 extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
JspFragment jf= this.getJspBody();
//jf.invoke(this.getJspContext().getOut());
jf.invoke(null);//null和this.getJspContext().getOut()等价
}
}
如果想让标签内容不显示doTag()方法里为空就可以了
配置
<tag>
<name>hello6</name>
<tag-class>cn.beida.tag.Tag6</tag-class>
<body-content>scriptless</body-content>(注意这个地方不能写成JSP了)
</tag>
l 控制jsp页面是否显示
标签类
package cn.beida.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.SkipPageException;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class Tag9 extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
throw new SkipPageException();
}
}
配置
......
Jsp
......
l 修改标签体的内容
标签类
package cn.beida.tag;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.StringWriter;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class Tag8 extends SimpleTagSupport {
@Override
public void doTag() throws JspException, IOException {
JspFragment jf = this.getJspBody();
//在内存中开辟一个空间来暂时存储标签体的内容
StringWriter sw = new StringWriter();
jf.invoke(sw);
String s = sw.toString()+"???";
this.getJspContext().getOut().println(s);
}
}
配置
......
Jsp
......
l 控制循环输出
标签类:
package cn.beida.tag;
import java.io.IOException;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.JspFragment;
import javax.servlet.jsp.tagext.SimpleTagSupport;
public class Tag7 extends SimpleTagSupport {
public void doTag() throws JspException, IOException {
JspFragment jf = this.getJspBody();
for(int i=0;i<5;i++){
jf.invoke(null);
}
}
}
配置
......
Jsp
......
Jstl(自学可以吗???)
JDBC
u Jdbc中常见的接口和类
u Mysql数据库的登陆
mysql -uroot -pmazheng
v 创建数据库
v
v 打开数据库
use mydatabase;
v 创建表
create table my(
id int auto_increment primary key,
name varchar(20) not null,
password varchar(20) not null,
age int not null
);
v 查看表的结构
Desc mytable;
v 删除表
Drop table if exists mytable;
在mysql中常用的数据类有int、float、varchar(M)、text(最多可以达到64k,大小写不敏感)、date、datetime、blob/clob(最多可以达到64k,大小写敏感)
v 插入数据
insert into mytable(name,password,age)values('admin','123',33);
v MySql 修改表结构语句
ALTER TABLE:添加,修改,删除表的列,约束等表的定义。
查看列:desc 表名;
修改表名:alter table t_book rename to bbb;
添加列:alter table 表名 add column 列名 varchar(30);
删除列:alter table 表名 drop column 列名;
修改列名MySQL: alter table bbb change nnnnn hh int;
修改列名SQLServer:exec sp_rename't_student.name','nn','column';
修改列名Oracle:lter table bbb rename column nnnnn to hh int;
修改列属性:alter table t_book modify name varchar(22);
u 连接MySql数据库
查寻记录
案例:Jsp1.0
代码如下:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>数据库连接</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/menagerie;
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "select id,name,age from mytable";
psmt = conn.prepareStatement(sql);
rs = psmt.executeQuery();
%>
<center>
<table border="1px"width=" 80%" >
<tr>
<td> 职工工号</td>
<td> 职工姓名</td>
<td> 职工年龄</td>
</tr>
<%
response.setCharacterEncoding("UTF-8");
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
int age = rs.getInt(3);
%>
<tr>
<td><%=id%></td>
<td><%=name%></td>
<td><%=age%></td>
</tr>
<%
}
%>
</table>
<%
System.out.print(rs);
}catch(Exception e){
System.out.print(e);
}finally{
rs.close();
psmt.close();
conn.close();
}
%>
</center>
</body>
</html>
l 增加、修改和删除记录
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
Statement state = null;
//PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
//插入新的记录
String sql = "insert into mytable(name,password,age) values ('mazheng','123455625',30)";
//修改记录
//String sql = "update mytable set name='mazheng123' where id=5";
//删除记录
//String sql = "delete from mytable where id='4'";
//psmt = conn.prepareStatement(sql);
state = conn.createStatement();
state.executeUpdate(sql);
}catch(Exception e){
System.out.print(e);
}finally{
state.close();
conn.close();
}
%>
</body>
</html>
l 预处理
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
//Statement state = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "insert into mytable(name,password,age) values (?,?,?)";
psmt = conn.prepareStatement(sql);
String name = request.getParameter("name");
String psd = request.getParameter("psd");
//int age = Integer.parseInt(request.getParameter("age"));
String age = request.getParameter("age");
psmt.setString(1,name);
psmt.setString(2,psd);
//psmt.setInt(3,age);
psmt.setString(3,age);
psmt.executeUpdate();
}catch(Exception e){
System.out.print(e);
}finally{
psmt.close();
conn.close();
}
%>
</body>
</html>
l Date数据类型的处理
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%@page import="java.text.SimpleDateFormat"%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
out.print("good");
Connection conn = null;
//Statement state = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "insert into info(name,bir) values (?,?)";
psmt = conn.prepareStatement(sql);
String date = "2001-02-12";
java.util.Date temp = new SimpleDateFormat("yyyy-MM-dd").parse(date);
java.sql.Date bir = new java.sql.Date(temp.getTime());
String name = "gg";
psmt.setString(1,name);
psmt.setDate(2,bir);
psmt.executeUpdate();
}catch(Exception e){
System.out.print(e);
}finally{
psmt.close();
conn.close();
}
%>
</body>
</html>
l 模糊查询的使用
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>数据库连接</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "select id,name,age from mytable where name like ?";
psmt = conn.prepareStatement(sql);
psmt.setString(1,"%a%");
rs = psmt.executeQuery();
%>
<center>
<table border="1px"width=" 80%" >
<tr>
<td> 职工工号</td>
<td> 职工姓名</td>
<td> 职工年龄</td>
</tr>
<%
response.setCharacterEncoding("UTF-8");
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
int age = rs.getInt(3);
%>
<tr>
<td><%=id%></td>
<td><%=name%></td>
<td><%=age%></td>
</tr>
<%
}
%>
</table>
<%
System.out.print(rs);
}catch(Exception e){
System.out.print(e);
}finally{
rs.close();
psmt.close();
conn.close();
}
%>
</center>
</body>
</html>
l 插入大数据文本
<%@ page language="java" import="java.util.*,java.io.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
PreparedStatement psmt = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "insert into file (name,text) values(?,?)";
File f = new File("D:\\test73.txt");
InputStream is = new FileInputStream(f);
//StringBuffer sb = new StringBuffer();
psmt = conn.prepareStatement(sql);
psmt.setString(1,"file1");
psmt.setAsciiStream(2,is,(int)f.length());
psmt.executeUpdate();
}catch(Exception e){
System.out.print(e);
}finally{
psmt.close();
conn.close();
}
%>
</body>
</html>
l 读取大数据文本
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "select id,name,text from file";
psmt = conn.prepareStatement(sql);
rs = psmt.executeQuery();
%>
<center>
<table border="1px"width=" 80%" >
<tr>
<td> 文件号</td>
<td> 文件名</td>
<td> 文件内容</td>
</tr>
<%
response.setCharacterEncoding("UTF-8");
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
Clob c = rs.getClob(3);
String s = c.getSubString(1,(int)c.length());
%>
<tr>
<td><%=id%></td>
<td><%=name%></td>
<td><%=s%></td>
</tr>
<%
}
%>
</table>
<%
System.out.print(rs);
}catch(Exception e){
System.out.print(e);
}finally{
rs.close();
psmt.close();
conn.close();
}
%>
</center>
</body>
</html>
l 如何来存储图片和视屏
存储:
<%@ page language="java" import="java.util.*,java.io.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<title></title>
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
PreparedStatement psmt = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "insert into ps (name,image) values(?,?)";
psmt = conn.prepareStatement(sql);
psmt.setString(1,"file1");
psmt.setString(2,"/JDBC/images/007.jpg");
psmt.executeUpdate();
}catch(Exception e){
System.out.print(e);
}finally{
psmt.close();
conn.close();
}
%>
</body>
</html>
读取:
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>数据库连接</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "select id,name,image from ps";
psmt = conn.prepareStatement(sql);
rs = psmt.executeQuery();
%>
<center>
<table border="1px"width=" 80%" height="100" >
<tr>
<td> id</td>
<td> 姓名</td>
<td> 照片</td>
</tr>
<%
response.setCharacterEncoding("UTF-8");
while(rs.next()){
int id = rs.getInt(1);
String name = rs.getString(2);
String image = rs.getString(3);
%>
<tr>
<td><%=id%></td>
<td><%=name%></td>
<td><img width="300" height="200" alt="sdf" src=<%=image%>></td>
</tr>
<%
}
%>
</table>
<%
System.out.print(rs);
}catch(Exception e){
System.out.print(e);
}finally{
rs.close();
psmt.close();
conn.close();
}
%>
</center>
</body>
</html>
l Jdbc2.0的新特性
滚动结果集
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>数据库连接</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "select id,name,age from mytable";
psmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_READ_ONLY);
rs = psmt.executeQuery();
rs.absolute(8);
rs.beforeFirst();
rs.next();
rs.afterLast();
rs.previous();
%>
<center>
<table border="1px"width=" 80%" >
<tr>
<td> 职工工号</td>
<td> 职工姓名</td>
<td> 职工年龄</td>
</tr>
<%
response.setCharacterEncoding("UTF-8");
int id = rs.getInt(1);
String name = rs.getString(2);
int age = rs.getInt(3);
%>
<tr>
<td><%=id%></td>
<td><%=name%></td>
<td><%=age%></td>
</tr>
</table>
<%
System.out.print(rs);
}catch(Exception e){
System.out.print(e);
}finally{
rs.close();
psmt.close();
conn.close();
}
%>
</center>
</body>
</html>
通过结果集插入数据
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>数据库连接</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "select id,name,password,age from mytable";
psmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
rs = psmt.executeQuery();
rs.moveToInsertRow();
rs.updateString("name","huairen2");
rs.updateString("password","123");
rs.updateInt("age",12);
rs.insertRow();
%>
<%
}catch(Exception e){
System.out.print(e);
}finally{
rs.close();
psmt.close();
conn.close();
}
%>
</body>
</html>
通过结果集修改数据库
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>数据库连接</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "select id,name,password,age from mytable where id=?";
psmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
psmt.setInt(1,6);
rs = psmt.executeQuery();
rs.last();
rs.updateString("name","好好好");
rs.updateString("password","123");
rs.updateInt("age",12);
rs.updateRow();
%>
<%
}catch(Exception e){
System.out.print(e);
}finally{
rs.close();
psmt.close();
conn.close();
}
%>
</body>
</html>
通过结果集删除数据
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>数据库连接</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "select id,name,password,age from mytable where id=?";
psmt = conn.prepareStatement(sql,ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
psmt.setInt(1,3);
rs = psmt.executeQuery();
rs.last();
rs.deleteRow();
%>
<%
}catch(Exception e){
System.out.print(e);
}finally{
rs.close();
psmt.close();
conn.close();
}
%>
</body>
</html>
批处理
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%>
<%@ page import="java.sql.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>数据库连接</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "org.gjt.mm.mysql.Driver";
//数据连接地址
public static final String DBURL = "jdbc:mysql://localhost:3306/mydata";
public static final String DBUSER = "root";
public static final String DBPASS = "mazheng";
%>
<%
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "insert into mytable(name,password,age) values (?,?,?)";
psmt = conn.prepareStatement(sql);
for(int i=0;i<5;i++){
psmt.setString(1,"haoren"+i);
psmt.setString(2,"123"+i);
psmt.setInt(3,23);
psmt.addBatch();
}
psmt.executeBatch();
%>
<%
}catch(Exception e){
System.out.print(e);
}finally{
psmt.close();
conn.close();
}
%>
</body>
</html>
u 连接oracle数据库
案例:JspOracle
代码:
<%@ page language="java" import="java.util.*" pageEncoding="GBK"%>
<%@ page import="java.sql.*" %>
<%
String path = request.getContextPath();
String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";
%>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<base href="<%=basePath%>">
<title>数据库连接</title>
<meta http-equiv="pragma" content="no-cache">
<meta http-equiv="cache-control" content="no-cache">
<meta http-equiv="expires" content="0">
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="description" content="This is my page">
<!--
<link rel="stylesheet" type="text/css" href="styles.css">
-->
</head>
<body>
<%!
//定义数据库驱动
public static final String DBDRIVER = "oracle.jdbc.driver.OracleDriver";
//数据连接地址
public static final String DBURL = "jdbc:oracle:thin:@localhost:1521:orcl";
public static final String DBUSER = "scott";
public static final String DBPASS = "haoren";
%>
<%
request.setCharacterEncoding("gbk");
Connection conn = null;
PreparedStatement psmt = null;
ResultSet rs = null;
%>
<%
try{
Class.forName(DBDRIVER);
conn = DriverManager.getConnection(DBURL,DBUSER,DBPASS);
String sql = "select empno,ename,job,hiredate,sal from emp";
psmt = conn.prepareStatement(sql);
rs = psmt.executeQuery();
%>
<center>
<table border="1px"width=" 80%" >
<tr>
<td> 职工工号</td>
<td> 职工姓名</td>
<td> 职工职务</td>
<td> 职工工资</td>
<td> 入职时间</td>
</tr>
<%
while(rs.next()){
int empno = rs.getInt(1);
String ename = rs.getString(2);
String job = rs.getString(3);
java.util.Date hiredate = rs.getDate(4);
float sal = rs.getFloat(5);
%>
<tr>
<td><%=empno%></td>
<td><%=ename%></td>
<td><%=job%></td>
<td><%=hiredate%></td>
<td><%=sal%></td>
</tr>
<%
}
%>
</table>
<%
System.out.print(rs);
}catch(Exception e){
System.out.print(e);
}finally{
rs.close();
psmt.close();
conn.close();
}
%>
</center>
</body>
</html>
DAO设计模式
www.open-open.com
u MyEclipse对数据库的管理