jsp 全
来源:互联网 发布:摩尔庄园源码 编辑:程序博客网 时间:2024/04/29 08:06
[学习笔记]马士兵 Servlet & JSP(1.Servlet)
www.diybl.com 时间 : 2010-05-22 作者:匿名 编辑:Mr.阿布 点击: 131 [ 评论 ]
1.HTTP协议基础测试(获取页面源代码)
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.Socket;
import java.net.UnknownHostException;
/**
* HTTP协议基础测试
* 本程序将Tomcat首页的页面源代码拿下来
* 用此方法,我们可以将我们访问到的页面的内容都拿下来
* @author ykn
*
*/
public class HttpTest {
public static void main(String[] args) {
Socket s = null;
PrintWriter pw = null;
BufferedReader br = null;
try {
// 建立连接端口,s指向本地机器tomcat服务器端口上
s = new Socket("127.0.0.1",8888);
// 对于本程序而言是输出,则相当于是准备向tomcat服务器端口写请求
pw = new PrintWriter(new OutputStreamWriter(s.getOutputStream()));
// 请求访问页面(此处等同于访问http://localhost:8888/)
pw.println("GET / HTTP/1.1");
pw.println("Host: www.bjsxt.com");
pw.println("Content-Type:text/html");
pw.println("");
// 上一句表示请求内容结束
pw.flush();
// 上面这一段用于本程序向Tomcat服务器发出访问请求(get)
// 服务器端作出响应,对于本程序而言是输入
br = new BufferedReader(new InputStreamReader(s.getInputStream()));
String str = "";
// 将服务器端的响应信息打印输出(即将http://localhost:8888/页面代码源文件中的内容输出)
// 用此方法,我们可以将我们访问到的页面的内容都拿下来
while((str = br.readLine()) != null) {
System.out.println(str);
}
} catch (UnknownHostException e) {
System.out.println("未知的主机异常。。。");
e.printStackTrace();
} catch (IOException e) {
System.out.println("IO异常。。。");
e.printStackTrace();
} finally {
try {
if (br != null) {
br.close();
br = null;
}
if (pw != null) {
pw.close();
pw = null;
}
if (s != null) {
s.close();
s = null;
}
} catch (IOException e) {
System.out.println("IO异常。。。");
e.printStackTrace();
}
}
}
}
--------------------------------------------------------------------------------------------------------------------------------------
2.最简单的servlet示例
说明:
①将HelloWorldServlet .class拷贝到test\WEB-INF\classes目录下(test是项目名)
②在web.xml中添加对应的servlet处理语句:
<servlet>
<servlet-name>HW</servlet-name>
<servlet-class>HelloWorldServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>HW</servlet-name>
<url-pattern>/abc</url-pattern>
</servlet-mapping>
③在URL地址栏中以http://localhost:8888/test/abc形式访问
④页面上显示结果:Hello World!
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;
/**
* 简单的servlet示例
* @author jukey
*
*/
public class HelloWorldServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.println("Hello World!");
}
}
-----------------------------------------------------------------------------------------------------------------------------------
3.Servlet的生命周期测试
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet的生命周期
* @author jukey
*
*/
public class TestLifeCycleServlet extends HttpServlet {
// 处理请求
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doGet");
}
// 实例化
// 注意:构造方法不能有返回值类型,连void也不行(否则就变成普通方法了)
public TestLifeCycleServlet() {
System.out.println("constructed");
}
// 退出服务
public void destroy() {
System.out.println("destory");
}
// 初始化
public void init() throws ServletException {
System.out.println("init");
}
}
/*
测试结果(在tomcat服务器控制台窗口):
constructed
init
doGet
*/
------------------------------------------------------------------------------------------------------------------------------------
4.读取指定的参数
①Threeparams.htm
<form id="form1" name="form1" method="post" action="servlet/Threeparams">
<table width="343" border="1">
<tr>
<td width="92">param1</td>
<td width="94"><input name="param1" type="text" id="param1"/></td>
</tr>
<tr>
<td width="92">param2</td>
<td width="94"><input name="param2" type="text" id="param2"/></td>
</tr>
<tr>
<td width="92">param3</td>
<td width="94"><input name="param3" type="text" id="param3"/></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value="提交"/></td>
</tr>
</table>
</form>
②ThreeParams.java
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;
/**
* 读取指定的参数
* @author jukey
*
*/
public class ThreeParams extends HttpServlet {
// 参数在传递过程中,在URL地址栏中显示出来
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter pw = response.getWriter();
pw.println(request.getParameter("param1"));
pw.println("<br>");
pw.println(request.getParameter("param2"));
pw.println("<br>");
pw.println(request.getParameter("param3"));
pw.println("<br>");
}
// 参数在传递过程中,在URL地址栏中隐藏了
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
// 调用doGet方法
doGet(request,response);
}
}
----------------------------------------------------------------------------------------------------------------------------------
5.读取所有的参数
①Showparameters.htm
<html>
<head>
<title>A sample show parameters</title>
</head>
<body>A sample show parameters
<form method="post" action="servlet/ShowParameters">
Item Number:<input type="text" name="itemNum"><br>
Quantity:<input type="text" name="quantity"><br>
Price each:<input type="text" name="price" value="$"><br>
First Name:<input type="text" name="firstName"><br>
Last Name:<input type="text" name="lastName"><br>
Middle Initial:<input type="text" name="initial"><br>
Shipping Address:<textarea name="address" row="3" cols="40"></textarea><br>
Credit Card:<br>
<!--单选框示例-->
<input type="radio" name="cardType" value="Visa">Visa<br>
<input type="radio" name="cardType" value="Master Card">Master Card<br>
<input type="radio" name="cardType" value="Amex">Amex<br>
<input type="radio" name="cardType" value="Discover">Discover<br>
<input type="radio" name="cardType" value="Java SmartCard">Java SmartCard<br>
<!--密码输入框-->
Credit Card password:<input type="password" name="cardNum"><br>
Repeat Credit Card password:<input type="password" name="cardNum"><br><br>
<center><input type="submit" value="Submit Order"></center>
</form>
</body>
</html>
②ShowParameters.java
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Enumeration;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 读取所有的参数
* @author jukey
*
*/
public class ShowParameters extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
String title = "Reading All Request Parameters";
out.println("init");
out.println("<html><head><title>读取所有参数</title></head>"
+ title
+ "\n" + "<table border=1 align=center>\n"
+ "<TH>Parameter Name<TH>Parameter Value(s)");
// Returns an Enumeration of String objects containing the names of the parameters contained in this request.
Enumeration paramNames = request.getParameterNames();
// Tests if this enumeration contains more elements.
while(paramNames.hasMoreElements()) {
// Returns the next element of this enumeration if this enumeration object has at least one more element to provide.
String paraName = (String)paramNames.nextElement();
out.println("<tr><td>" + paraName + "\n<td>");
// Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.
// 注意参数paraName(变量)不能加双引号,否则就是找参数名叫paraName的对应值了。
String[] paramValues = request.getParameterValues(paraName);
// 这个参数只有一个值
if(paramValues.length == 1) {
String paramValue = paramValues[0];
if(paramValue.length() == 0) {
out.println("<I>no value</I>");
} else {
out.println(paramValue);
}
}else {
// 这个参数有好几条值
out.println("<UL>");
for(int i = 0; i < paramValues.length; i++) {
out.println("<LI>" + paramValues[i]);
}
out.println("</UL>");
}
}
out.println("</table>\n<body></html>");
}
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
System.out.println("doPost");
doGet(request,response);
}
}
--------------------------------------------------------------------------------------------------------------------------------------------
6.Cookies的设置和读取
①设置Cookie到客户端
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 设置Cookie到客户端
* @author jukey
*
*/
public class SetCookies extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 向客户端写入Cookie,共6个
for(int i = 0; i < 3; i++) {
// 3个没有设置时间的Cookie,属于本窗口及其子窗口
Cookie cookie = new Cookie("Session-Cookie-" + i, "Cookie-Value-S" + i);
response.addCookie(cookie);
// 以下3个Cookie设置了时间(3600秒,1小时),属于文本,别的窗口也可以访问到这些Cookie
cookie = new Cookie("Persistent-Cookie-" + i, "Cookie-Value-P" + i);
cookie.setMaxAge(3600);
response.addCookie(cookie);
}
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
String title = "Setting Cookies";
out.println("<html><head><title>设置Cookie</title></head>"
+ "<body>" + title + "<br>"
+ "There are six cookies associates with this page.<br>"
+ "to see them,visit the <a href=\"ShowCookies\">\n"
+ "<code>ShowCookies</code> servlet</a>"
+ "</body></html>");
}
}
②读取客户端的Cookies
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 读取客户端的Cookies
* @author jukey
*
*/
public class ShowCookies extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter pw = response.getWriter();
String title = "Active Cookies";
pw.println("init");
pw.println("<html><head><title>读取客户端</title></head>"
+ title
+ "\n" + "<table border=1 align=center>\n"
+ "<TH>Cookie Name<TH>Cookie Value" + "<br>");
// 读取客户端的所有Cookie
Cookie[] cookies = request.getCookies();
if(cookies != null) {
Cookie cookie;
for(int i = 0; i < cookies.length; i++) {
cookie = cookies[i];
pw.println("<tr>\n" + "<td>" + cookie.getName() +"</td>\n"
+ "<td>" + cookie.getValue() +"</td></tr>\n");
}
}
pw.println("</table>\n<body><html>");
}
}
--------------------------------------------------------------------------------------------------------------------------------------
7.Session的测试
①演示Servlet API中的session管理机制(常用方法)
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* 演示Servlet API中的session管理机制(常用方法)
* @author jukey
*
*/
public class SessionInfoServlet extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// Returns the current session associated with this request, or if the request does not have a session, creates one.
HttpSession mySession = request.getSession(true);
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Session Info Servlet";
out.println("<html>");
out.println("<head>");
out.println("<title>Session Info Servlet</title>");
out.println("</head>");
out.println("<body>");
out.println("<h3>Session Infomation</h3>");
// Returns true if the client does not yet know about the session or if the client chooses not to join the session.
out.println("New Session:" + mySession.isNew() + "<br>");
// Returns a string containing the unique identifier assigned to this session.
out.println("Session Id:" + mySession.getId() + "<br>");
// Returns the time when this session was created, measured in milliseconds since midnight January 1, 1970 GMT.
out.println("Session Create Time:" + new Date(mySession.getCreationTime()) + "<br>");
out.println("Session Last Access Time:" + new Date(mySession.getLastAccessedTime()) + "<br>");
out.println("<h3>Request Infomation</h3>");
// Returns the session ID specified by the client.
out.println("Session Id From Request:" + request.getRequestedSessionId() + "<br>");
// Checks whether the requested session ID came in as a cookie.
out.println("Session Id Via Cookie:" + request.isRequestedSessionIdFromCookie() + "<br>");
// Checks whether the requested session ID came in as part of the request URL.
out.println("Session Id Via URL:" + request.isRequestedSessionIdFromURL() + "<br>");
// Checks whether the requested session ID is still valid.
out.println("Valid Session Id:" + request.isRequestedSessionIdValid() + "<br>");
out.println("<a href=" + response.encodeURL("SessionInfoServlet") + ">refresh</a>");
out.println("</body></html>");
out.close();
}
}
②Session追踪
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
/**
* Session追踪
* 如果浏览器支持Cookie,创建Session的时候会把SessionId保存在Cookie中
* 否则必须自己编程使用URL重写的方式实现Session:response.encodeURL()
* @author jukey
*
*/
public class ShowSession extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
String str = "Session Tracking Example";
String heading;
// 如果会话已经存在,则返回一个HttpSession;否则创建一个新的
HttpSession session = request.getSession(true);
// 从当前session中读取属性accessCount的值
Integer accessCount = (Integer)session.getAttribute("accessCount");
if(accessCount == null) {
accessCount = new Integer(0);
heading = "Welcome newUser";
} else {
heading = "Welcome Back";
accessCount = new Integer(accessCount.intValue() + 1);
}
// 向当前session中插入键(key,属性)值(value)对
// Binds an object to this session, using the name specified.
session.setAttribute("accessCount", accessCount);
out.println("<html><head><title>Session追踪</title></head>"
+ "<body>" + heading + "<br>"
+ "<h2>Information on Your Session</h2><br>"
+ "\n" + "<table border=1 align=center>\n"
+ "<TH>Info Type<TH>Value" + "<br>"
+ "<tr>\n" + "<td>ID</td>\n"
+ "<td>" + session.getId() +"</td></tr>\n"
+ "<tr>\n" + "<td>CreatTime</td>\n"
+ "<td>" + new Date(session.getCreationTime()) +"</td></tr>\n"
+ "<tr>\n" + "<td>LastAccessTime</td>\n"
+ "<td>" + new Date(session.getLastAccessedTime()) +"</td></tr>\n"
+ "<tr>\n" + "<td>Number of Access</td>\n"
+ "<td>" + accessCount +"</td></tr>\n"
+ "</body></html>");
}
}
--------------------------------------------------------------------------------------------------------------------------------
8.Application测试
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Application测试
* 用于保存整个web应用的生命周期内都可以访问的数据
* 可供多个不同窗口访问,可作为某一页面被总共访问次数的计数器(比如网站首页的访问量)
* @author jukey
*
*/
public class TestServletContext extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
// Returns a reference to the ServletContext in which this servlet is running.
ServletContext application = this.getServletContext();
// 从当前application中读取属性accessCount的值
Integer accessCount = (Integer)application.getAttribute("accessCount");
if(accessCount == null) {
accessCount = new Integer(0);
} else {
accessCount = new Integer(accessCount.intValue() + 1);
}
// 向当前application中插入键(key,属性)值(value)对
application.setAttribute("accessCount", accessCount);
out.println("<html><head><title>ServletContext测试</title></head><br>"
+ "<body><td>" + accessCount +"</td>\n"
+ "</body></html>");
}
}
---------------------------------------------------------------------------------------------------------------------------------------------
9.Servlet类本身位于包中的情况
package com.bjsxt.servlet;
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;
/**
* Servlet类本身位于包中的情况
* classes中要class文件及其各级目录一起放置
* web中如下设置:<servlet-class>com.bjsxt.servlet.HelloWorldServlet2</servlet-class>
* @author jukey
*
*/
public class HelloWorldServlet2 extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.println("Hello World!");
}
}
--------------------------------------------------------------------------------------------------------------------------------
10.在Servlet中直接连接数据库,并查询显示信息
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* 在Servlet中直接连接数据库,并查询显示信息
* 每个application都应该有自己的驱动包,放在各自项目的WEB-INF\lib\目录下
* @author jukey
*
*/
public class ShowRs extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
Connection conn = null;
Statement stmt = null;
ResultSet rs = null;
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.println("<table border=1>");
out.println("<tr><td>Content:</td></tr>");
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/bbs?user=root&password=mysql");
stmt = conn.createStatement();
String sql = "select * from article";
rs = stmt.executeQuery(sql);
while(rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getString("cont") + "</td>");
out.println("</tr>");
}
} catch (SQLException ex) {
ex.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
} finally {
if (rs != null) {
try {
rs.close();
rs = null;
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
}
if (stmt != null) {
try {
stmt.close();
stmt = null;
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
}
if (conn != null) {
try {
conn.close();
conn = null;
} catch (SQLException sqlEx) {
sqlEx.printStackTrace();
}
}
}
}
}
----------------------------------------------------------------------------------------------------------------------------------
11.Servlet中使用专门的数据库操作类DB
①Servlet中使用专门的数据库操作类DB,这样,本程序就比前一个显得简单清楚
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
* Servlet中使用专门的数据库操作类DB,这样,本程序就比前一个显得简单清楚
* DB类,专门跟数据库打交道,分工明确,各司其职
* @author jukey
*
*/
public class ShowRsUseBean extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
PrintWriter out = response.getWriter();
out.println("<table border=1>");
out.println("<tr><td>Content:</td></tr>");
// 直接调用DB中的静态方法来为本类服务
Connection conn = DB.getConnection();
Statement stmt = DB.getStatement(conn);
String sql = "select * from article";
ResultSet rs = DB.getResultSet(stmt, sql);
try {
while(rs.next()) {
out.println("<tr>");
out.println("<td>" + rs.getString("cont") + "</td>");
out.println("</tr>");
}
} catch (SQLException e) {
System.out.println("执行SQL遍历过程中出现了错误。。。");
e.printStackTrace();
} finally {
// 直接调用DB中的静态方法来关闭一系列被打开的资源
DB.close(rs);
DB.close(stmt);
DB.close(conn);
}
}
}
②专门跟数据库打交道的类
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* 专门跟数据库打交道的类
* @author ykn
*
*/
public class DB {
// 获取连接
public static Connection getConnection() {
Connection conn = null;
try {
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection("jdbc:mysql://localhost/bbs?user=root&password=mysql");
} catch (ClassNotFoundException e) {
System.out.println("驱动程序未找到,请加入mysql.jdbc的驱动包。。。");
e.printStackTrace();
} catch (SQLException e) {
System.out.println("执行数据库连接过程中出现了错误。。。");
e.printStackTrace();
}
return conn;
}
// 获取表达式语句
public static Statement getStatement(Connection conn) {
Statement stmt = null;
try {
if (conn != null) {
stmt = conn.createStatement();
}
} catch (SQLException e) {
System.out.println("执行获取表达式语句过程中出现了错误。。。");
e.printStackTrace();
}
return stmt;
}
// 获取查询的结果集
public static ResultSet getResultSet(Statement stmt, String sql) {
ResultSet rs = null;
try {
if (stmt != null) {
rs = stmt.executeQuery(sql);
}
} catch (SQLException e) {
System.out.println("执行查询过程中出现了错误。。。");
e.printStackTrace();
}
return rs;
}
// 关闭连接
public static void close(Connection conn) {
try {
if (conn != null) {
conn.close();
conn = null;
}
} catch (SQLException e) {
System.out.println("执行关闭数据库连接过程中出现了错误。。。");
e.printStackTrace();
}
}
// 关闭表达式语句
public static void close(Statement stmt) {
try {
if (stmt != null) {
stmt.close();
stmt = null;
}
} catch (SQLException e) {
System.out.println("执行关闭表达式语句过程中出现了错误。。。");
e.printStackTrace();
}
}
// 关闭结果集
public static void close(ResultSet rs) {
try {
if (rs != null) {
rs.close();
rs = null;
}
} catch (SQLException e) {
System.out.println("执行关闭结果集过程中出现了错误。。。");
e.printStackTrace();
}
}
[学习笔记]马士兵 Servlet & JSP(2.JSP)
www.diybl.com 时间 : 2010-05-22 作者:匿名 编辑:Mr.阿布 点击: 34 [ 评论 ]
1.最简单的JSP
HelloWorld.jsp
<html>
<head>
<title>Hello</title>
<body>
<%
out.println("Hello World!");
%>
</body>
</head>
</html>
---------------------------------------------------------------------------------------------------------------------------------------
2.JSP中的全局变量和局部变量
AccessCounts.jsp
<html>
<head>
<title>JSP Declaration</title>
</head>
<body>
<%!
// 全局变量
int accessCount = 0;
%>
<%
// 局部变量
int accessCount2 = 0;
%>
<h2>AccessCount:
<br>Overall Variable:<%= ++accessCount %>
<br>Local Variable:<%= ++accessCount2 %>
</h2>
</body>
</html>
测试结果:访问同一页面,每刷新一次,accessCount增1,accessCount2不变(每次出现一个新的局部变量)。
----------------------------------------------------------------------------------------------------------------------------------
3.注释、当前页面从URL中取背景色参数
BGColor.jsp
<html>
<head>
<title>Color Testing</title>
</head>
<!--
HTML注释
客户端可以看见
-->
<%--
JSP注释
客户端看不见
--%>
<%
//注释2
/*
注释3
*/
// 将请求中参数bgColor的值拿过来,假如没有传这个参数,则值为null
String bgColor = request.getParameter("bgColor");
boolean hasColor;
if(bgColor != null) {
hasColor = true;
} else {
hasColor = false;
bgColor = "white";
}
%>
<!--显示背景色-->
<body bgcolor="<%= bgColor%>">
<h2 align="center">Color Testing</h2>
<%
if(hasColor) {
out.println("You supplied a backgroud color of " + bgColor + ".");
} else {
out.println("Use Default backgroud color of white");
}
%>
</body>
</html>
-----------------------------------------------------------------------------------------------------------------------------
4.表达式
Expressions.jsp
<html>
<head>
<title>JSP Expressions</title>
</head>
<!--表达式-->
<body>
<h2>JSP Expressions</h2>
<UL>
<!--获取当前本地时间-->
<LI>Current Time:<%= new java.util.Date().toLocaleString() %>
<LI>Your HostName:<%= request.getRemoteHost() %>
<!--获取当前页面的SessionID-->
<LI>Your Session Id:<%= session.getId() %>
<LI>The <code>testParam</code> from parameter:<%= request.getParameter("testParam") %>
</UL>
</body>
</html>
----------------------------------------------------------------------------------------------------------------------------------------
5.@page指示语句的测试
TestDirective.jsp
<%@page import="java.util.*" %>
<%@page contentType="text/html;charset=gb2312" %>
<!--@page指示语句的测试-->
<!--将当前系统时间转变成我们本地常用的形式输出-->
<%= new Date().toLocaleString() %>
<br><br>
<%
out.println("你好!");
%>
--------------------------------------------------------------------------------------------------------------------------------
6.错误页跳转测试
①TestErr.jsp
<%@page errorPage="ErrPage.jsp" %>
<!--如果本页面出错则跳转到ErrPage.jsp页面-->
<%
String str = "123abc";
int i = Integer.parseInt(str);
out.println("str= " + str + ",i= " + i);
%>
②ErrPage.jsp
<%@page contentType="text/html;charset=gb2312" %>
<%@page isErrorPage="true" %>
<!--本页面是个错误信息显示页-->
<html>
<body text="red">
错误信息:<%= exception.getMessage()%>
</body>
</html>
-----------------------------------------------------------------------------------------------------------------------------
7.include指令”%@ include file“和include动作指令“jsp:include page”
前者是先包含进来再编译执行;后者是先各自编译执行再包含进来
①include.jsp
<html>
<head>
<title>include test</title>
</head>
<body bgcolor="white">
<font color="red">
The current time and date are:<br>
<!--先将date.jsp的内容包含进来,再一起进行转换、编译和执行-->
<%@include file="date.jsp" %><br>
<!--先将date.jsp进行转换、编译和执行,再将结果包含进来-->
<jsp:include page="date.jsp" flush="true" />
</font>
</body>
</html>
②date.jsp
<%@page import="java.util.*" %>
<%--a string representation of this date, using the locale conventions.--%>
<%= (new Date()).toLocaleString() %>
说明:以下转载自网络 http://blog.matrix.org.cn/rudy541/entry/200708162
jsp中两种包含文件的区别:
相同点:两者逗能包含一个页面
不同点:
区别1:
<jsp:include page="b.jsp" />(先执行,后包含)
此标签表示法:能动态区别加进来的是动态页面还是静态页面
对于静态页面则直接将资源包含(仅取其文本)。
对于动态页面则先处理各自资源,之后将处理过的结果包含在一起。
<%@ include file="b.jsp">
此指令表示:静态地包含页面,不管其内容如何,不过是静态页面还是动态页面都首先将页面的内容先加进来。
然后一起处理,再将所有内容发给客户端。
实例挑战:
有b.jsp页面
<%int i = 10 ;%>
<%=i%>
主界面a.jsp也有<%int i = 100 ;%> <%=i%>
如果是加载<%@ include file="b.jsp">,则是先包含后执行,就会发现报错,i被重新定义,
但如果是加载<jsp:include page="b.jsp" />则是先执行结果,然后将结果包括到主页面。不会报错。
区别2:
<jsp:include page="b.jsp" />可以分开写成:
<jsp:include page="b.jsp" >
<jsp:param name="参数名" value="参数值"/>
</jsp:include>
这样就可以传递参数。
----------------------------------------------------------------------------------------------------------------------
8.两个数的乘除运算
①Compute.html
<html>
<head>
<title>Compute</title>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
</head>
<!--两个数的乘除运算-->
<body bgcolor="#FFFFFF">
<div align="center">
<form method="post" action="Compute.jsp">
<p>选择要做的运算:
<input type="radio" name="compute" value="division" checked>
除法
<input type="radio" name="compute" value="multiplication">
乘法
</p>
<p>被除数(被乘数)
<input type="text" name="value1">
除数(乘数)
<input type="text" name="value2">
</p>
<p>
<input type="submit" name="Submit" value="计算结果">
</p>
</form>
</div>
</body>
</html>
②Compute.jsp
<%@page language="java" %>
<%@page contentType="text/html;charset=gb2312" %>
<%
// 将Compute.html页面输入的要进行计算的两个变量拿过来
String value1 = request.getParameter("value1");
String value2 = request.getParameter("value2");
%>
<% if("division".equals(request.getParameter("compute"))) { %>
<!--进行除法计算,把两个参数v1和v2先传到divide.jsp,再那边编译运行,然后把结果拿到这边显示出来-->
<jsp:include page="divide.jsp" flush="true">
<jsp:param name="v1" value="<%=value1%>"/>
<jsp:param name="v2" value="<%=value2%>"/>
</jsp:include>
<% } else { %>
<!--直接把multiply.jsp拿过来,跟本页面一起编译执行-->
<%@include file="multiply.jsp" %>
<% } %>
③multiply.jsp
<%@page contentType="text/html;charset=gb2312" %>
<html>
<head>
<title>Multiply</title>
</head>
<%--进行乘法计算的JSP--%>
<body bgcolor="#FFFFFF">
<center>
<h1>
<%
try{
float multiplicand = Float.parseFloat(request.getParameter("value1"));
float multiplicator = Float.parseFloat(request.getParameter("value2"));
double result = multiplicand*multiplicator;
out.println(multiplicand + "*" + multiplicator +" = " + result);
} catch(Exception e) {
out.println("不合法的乘数或被乘数");
}
%>
</h1>
</center>
</body>
</html>
④divide.jsp
<%@page contentType="text/html;charset=gb2312" %>
<html>
<head>
<title>Divide</title>
</head>
<%--进行除法计算的JSP--%>
<body bgcolor="#FFFFFF">
<center>
<h1>
<%
try{
float divident = Float.parseFloat(request.getParameter("v1"));
float divisor = Float.parseFloat(request.getParameter("v2"));
double result = divident/divisor;
%>
<%= result%>
<%
} catch(Exception e) {
out.println("不合法的除数或被除数");
}
%>
</h1>
</center>
</body>
</html>
----------------------------------------------------------------------------------------------------------------------------------
9.jsp:forward和response.sendRedirect
①最简单的jsp:forward
forward.jsp
<html>
<head>
<title>Forward Example</title>
</head>
<!--最终显示的是forforward.jsp中的内容-->
<body bgcolor=red>
Welcome to forward.jsp
<%--直接跳转到forforward.jsp,这两个jsp用的是同一个request--%>
<jsp:forward page="forforward.jsp" />
</body>
</html>
forforward.jsp
<html>
<head>
<title>forforward.jsp</title>
</head>
<body bgcolor=blue>
Welcome<br>
Here is forforward.jsp
</body>
</html>
②jsp:forward和response.sendRedirect的比较
forward1.jsp
<html>
<head>
<title>Forward Example</title>
</head>
<body bgcolor=red>
Welcome to forward1.jsp
<jsp:forward page="forforward1.jsp" >
<jsp:param name="name" value="m" />
<jsp:param name="oldName" value='<%= request.getParameter("name")%>' />
<jsp:param name="roles" value="manager" />
</jsp:forward>
</body>
</html>
forforward1.jsp:和forward1.jsp使用的是同一个request(服务器跳转)
<html>
<head>
<title>forforward1.jsp</title>
</head>
<body bgcolor=blue>
Welcome<br>
Here is forforward1.jsp<br>
<%= request.getParameter("name")%>
<%= request.getParameter("oldName")%>
<%= request.getParameter("roles")%>
<%= request.getParameter("address")%>
</body>
</html>
测试结果:
访问http://localhost:8888/test/forward/forward1.jsp?name=yyg&address=34527144231
结果:
Welcome
Here is forforward1.jsp
m yyg manager 34527144231
此时页面URL还是forward1.jsp,并没有跳转到forforward1.jsp,给用户的感觉还是刚才的页面在为自己服务。
说明:m 和manager 是forward1.jsp中传过来的;而yyg 和34527144231 是在URL中通过request传过来的。并且forward1.jsp中也没有address属性,这也从另一个角度说明了这两个jsp使用的是同一个request。
test.jsp:和forward1.jsp使用的是不同的request
说明:访问过http://localhost:8888/test/forward/test.jsp后,页面跳转成http://localhost:8888/test/forward/forforward1.jsp
这个过程中客户和服务器之间产生了两个request,并且test.jsp后跟参数并不能传递到forforward1.jsp(原因也很明显:两次是不同的request)
<%
response.sendRedirect("forforward1.jsp");
%>
---------------------------------------------------------------------------------------------------------------------------------------------
10.jsp:useBean
①CounterBean.java
package bean;
import java.io.Serializable;
/**
* 一个很普通的JavaBean
* @author jukey
*
*/
public class CounterBean implements Serializable {
private int count = 0;
public CounterBean() {}
public int getCount() {
count++;
return count;
}
public void setCount(int count) {
this.count = count;
}
}
②test.jsp:JSP往JavaBean中设置值,从JavaBean中拿值
<%@page import="bean.*" %>
<%--
<%
// 下面这个语句等同于<jsp:useBean id="cb" class="bean.CounterBean"></jsp:useBean>
CounterBean cb = new CounterBean();
%>
--%>
<jsp:useBean id="cb" class="bean.CounterBean">
</jsp:useBean>
<font color="red" size="5">
<%--将bean中存储的值拿出来--%>
<%= cb.getCount()%>
</font>
<!--往bean中存值-->
<jsp:setProperty name="cb" property="count" value="25" />
<%--cb.setCount(25)--%>
<!--往bean中取值-->
<jsp:getProperty name="cb" property="count" />
<%--cb.getCount()--%>
以下是Bean的4种作用范围的测试:
③page有效(仅涵盖使用JavaBean的页面)
PageBean.jsp
<jsp:useBean id="counterBean" scope="page" class="bean.CounterBean" />
<html>
<body>
<h3>CounterBean scope="page" Example</h3>
<b>count:</b> <%= counterBean.getCount()%>
<%--上下两句效果一样--%>
<jsp:getProperty name="counterBean" property="count"/>
</body>
</html>
④request有效(有效范围仅限于使用JavaBean的请求)
RequestBean.jsp
<jsp:useBean id="counterBean" scope="request" class="bean.CounterBean" />
<%--
bean.CounterBean counterBean = request.getAttribute("counterBean");
if(counterBean == null) {
counterBean = new bean.CounterBean();
request.setAttribute("counterBean",counterBean);
}
--%>
<html>
<body>
<h3>CounterBean scope="request" Example</h3>
<!--往当前request对应的bean中设置-->
<% counterBean.setCount(100); %>
<%--和RequestBean2.jsp用的是同一个request,也是同一个counterBean对象--%>
<!--测试结果是101-->
<jsp:forward page="RequestBean2.jsp" />
<%--和RequestBean2.jsp用的不是同一个request,也不是同一个counterBean对象--%>
<!--访问RequestBean.jsp,跳转到RequestBean2.jsp,因为和当前request不是同一个request-->
<!--则产生一个新的request,产生一个新的bean对象,测试结果是1而不是101-->
<%-- response.sendRedirect("RequestBean2.jsp"); --%>
</body>
</html>
RequestBean2.jsp
<jsp:useBean id="counterBean" scope="request" class="bean.CounterBean" />
<html>
<body>
<h3>CounterBean scope="request" Example</h3>
<b>count:</b> <%= counterBean.getCount()%>
</body>
</html>
⑤Session有效(有效范围在用户整个连接过程中,整个会话阶段均有效)
SessionBean.jsp
<jsp:useBean id="counterBean" scope="session" class="bean.CounterBean" />
<%--
// 这一段java代码等同于上面这句JSP语句
bean.CounterBean counterBean = session.getAttribute("counterBean");
if(counterBean == null) {
counterBean = new bean.CounterBean();
session.setAttribute("counterBean",counterBean);
}
--%>
<html>
<body>
<h3>CounterBean scope="session" Example</h3>
<b>count:</b> <%= counterBean.getCount()%>
</body>
</html>
SessionBean2.jsp
<jsp:useBean id="counterBean" scope="session" class="bean.CounterBean" />
<html>
<body>
<h3>CounterBean scope="session" Example</h3>
<b>count:</b> <%= counterBean.getCount()%>
</body>
</html>
⑥application有效(有效范围涵盖整个应用程序,也就是对整个网站都有效)
可用于作为首页访问量的计数器
ApplicationBean.jsp
<jsp:useBean id="counterBean" scope="application" class="bean.CounterBean" />
<html>
<body>
<h3>CounterBean scope="application" Example</h3>
<b>count:</b> <%= counterBean.getCount()%>
</body>
</html>
ApplicationBean2.jsp
<jsp:useBean id="counterBean" scope="application" class="bean.CounterBean" />
<html>
<body>
<h3>CounterBean scope="application" Example</h3>
<b>count:</b> <%= counterBean.getCount()%>
</body>
</html>
----------------------------------------------------------------------------------------------------------------------
11.jsp:setProperty和jsp:getProperty
①SaleEntry.jsp
<html>
<head>
<title>Using jsp:setProperty</title>
</head>
<!--销售条目(单行:商品编号、单价、数量、总价)-->
<body>
<table border=5 align="center" >
<tr><th class="title">
Using jsp:setProperty
</table>
<jsp:useBean id="entry" class="bean.SaleEntry" />
<%--从JSP向JavaBean中设值--%>
<!--通过param指定表单元素的名称,通过property指定bean的属性名称,由此建立两个变量的关联-->
<jsp:setProperty name="entry" property="itemID" value="<%= request.getParameter("itemID")%>" />
<jsp:setProperty name="entry" property="numItems" param="numItems" />
<jsp:setProperty name="entry" property="discountCode" param="discountCode" />
<br>
<table border=1 align="center" >
<tr class="colored">
<th>Item ID<th>Unit Price<th>Number Ordered<th>Total Price
<tr align="right">
<%--Jsp从JavaBean中取值--%>
<td><jsp:getProperty name="entry" property="itemID" />
<td>$<jsp:getProperty name="entry" property="itemCost" />
<td><jsp:getProperty name="entry" property="numItems" />
<td>$<jsp:getProperty name="entry" property="totalCost" />
</table>
</body>
</html>
②SaleEntry.java
package bean;
public class SaleEntry {
private String itemID = "unknown";
// 折扣
private double discountCode = 1.0;
private int numItems = 0;
public double getDiscountCode() {
return discountCode;
}
public void setDiscountCode(double discountCode) {
this.discountCode = discountCode;
}
public String getItemID() {
return itemID;
}
public void setItemID(String itemID) {
this.itemID = itemID;
}
public int getNumItems() {
return numItems;
}
public void setNumItems(int numItems) {
this.numItems = numItems;
}
// 获取单价
public double getItemCost() {
double cost;
if("a1234".equals(itemID)) {
cost = 12.99 * getDiscountCode();
} else {
cost = -99;
}
return roundToPennies(cost);
}
// 计算到分位
public double roundToPennies(double cost) {
return (Math.floor(cost * 100) / 100.0);
}
// 计算总价格
public double getTotalCost() {
return (getItemCost() * getNumItems());
}
}
-------------------------------------------------------------------------------------------------------------------------------------
12.HTML页面输入内容,提交给JSP文件,JSP将这些内容存入JavaBean,再从JavaBean中拿出来显示。
中间有个中文乱码的处理问题。
①SayHelloBean.html
<html>
<head>
<title>数据输入</title>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
</head>
<body bgcolor="#FFFFFF">
<div align="center" >
<p>请输入数据</p>
<form method="post" action="SayHelloBean.jsp" >
<p>姓名
<input type="text" name="name">
性别
<select name="sex">
<option value="先生">先生</option>
<option value="女士">女士</option>
</select>
</p>
<p>
<input type="submit" name="Submit" value="提交">
</p>
</form>
<p> </p>
<p> </p>
</div>
</body>
</html>
②SayHelloBean.jsp
<%@page language="java" import="bean.HelloBean;" %>
<%@page contentType="text/html;charset=gb2312" %>
<%--先将传过来的request中的字符编码格式设置成gbk,再取内容--%>
<% request.setCharacterEncoding("gbk"); %>
<jsp:useBean id="hello" class="bean.HelloBean" scope="request" >
<%--通过*来设置所有属性和输入参数之间的关联,struts中大量运用--%>
<jsp:setProperty name="hello" property="*" />
</jsp:useBean>
<html>
<head>
<title>HelloBean</title>
<meta http-equiv="Content-Type" content="text/html;charset=gb2312">
</head>
<body bgcolor="#FFFFFF">
<p> </p>
<p align="center" >
<font size="4">欢迎
<font color="#0000FF">
<b>
<%--转码(终结解决方案):将hello对象中name属性的值用ISO8859_1编码格式以字节数组拿出,再转化成gbk格式---%>
<%--= new String(hello.getName().getBytes("ISO8859_1"),"gbk")--%>
</b>
</font>
<%--转码(终结解决方案):将hello对象中sex属性的值用ISO8859_1编码格式以字节数组拿出,再转化成gbk格式---%>
<%--= new String(hello.getSex().getBytes("ISO8859_1"),"gbk")--%>
</font>
</p>
<jsp:getProperty name="hello" property="name" />
<jsp:getProperty name="hello" property="sex" />
</body>
</html>
③HelloBean.java
package bean;
public class HelloBean {
private String name = "";
private String sex = "";
public HelloBean() {}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
}
[学习笔记]马士兵 Servlet & JSP(3.Servlet和JSP的通信)
www.diybl.com 时间 : 2010-05-22 作者:匿名 编辑:Mr.阿布 点击: 92 [ 评论 ]
(1)从JSP调用Servlet可用<jsp:forward>,请求信息自动转到Servlet
FromJspToServlet.jsp
<html>
<body bgcolor="green">
<!-- Forward to a servlet, 这个servlet存放在web-inf的servlet目录下 -->
<jsp:forward page="/servlet/ServletToJSP" />
</body>
</html>
(2)从Servlet调用JSP可以使用RequestDispatcher接口的forward(req, resp)方法,请求信息需要显示传递
ServletToJSP.java
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class ServletToJSP extends HttpServlet {
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// 设置属性并将它分发给/servlet_jsp/ServletUseJsp.jsp处理
resp.setContentType("text/html;charset=gb2312");
req.setAttribute("servletName", "ServletToJSP");
// RequestDispatcher getRequestDispatcher(String path):
// Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
getServletConfig().getServletContext().getRequestDispatcher("/servlet_jsp/ServletUseJsp.jsp").forward(req, resp);
}
}
(3)ServletUseJsp.jsp
<%@page contentType="text/html;charset=gb2312" %>
<html>
<meta context="text/html;charset=gb2312">
<head>
<title>Servlet使用JSP</title>
</head>
<body bgcolor="gray">
<h2>Servlet使用JSP的例子</h2>
<h2>这个页面是被Servlet调用的</h2>
</body>
</html>
说明:以上相互调用也可以直接使用sendRedirect
- jsp 全
- jsp乱码(全)
- jsp验证全
- jsp验证全
- JSP乱码全解析
- JSP程序员成长全计划
- JSP程序员成长全计划
- JSP程序员成长全计划
- jsp-SmartUpload上传下载全攻略
- JSP程序员成长全计划
- jsp注册页面,全解
- jsp乱码问题全解
- JSP程序员成长全计划(转)
- JSP制作文件上传下载全攻略~!~
- servlet和JSP过滤器Filter(全)
- jsp useBean元素使用全解
- jsp Smart Upload上传下载全攻略
- JSP连接不同数据库全攻略(待续)
- oracle 10g 数据语言
- HP-UX MP管理端口使用介绍
- 黑马程序员_学习日记9_ASP.NET服务器处理过程_一般处理程序_复习HTML标签
- Oracle Round
- ORACLE 查看各表空间大小
- jsp 全
- C11标准委员会成员解读C语言新标准
- MYSQL常用命令
- ORACLE 10g下载地址
- 内部类有哪些好处?什么时候使用内部类
- android资源管理备注
- PHP5.4的变化关注---What has changed in PHP 5.4.x
- DirectShow OpenCV GDI+ 图形显示格式转换
- socket编程时碰到的No route to host