jsp 基础

来源:互联网 发布:撒切尔夫人摔跤知乎 编辑:程序博客网 时间:2024/05/02 00:18
 
commons, js, css, images
 
  1. ========
记录访问次数
 
<% ! private int requestCount = 0 ; %>
Object lock = new Object();
<% = sychronized{++requestCount} %>
 
说明:
jsp声明变量, _jspServic 方法之外
对同一个 Servlet 的多个请求会产生多个线程, 如果这个 Servlet 没有实现SingleThreadModel 接口,则每个线程都调用同一个Servlet servce方法
 
相关:
jspInit
jspDestory
 
  1. ========
指令
 
<%@page contentType="text/html; charset=GB18030" buffer="none" autoFlush="true" extends="jspxper.Jsp1Bean" isELIgnored="true" isErrorPage="true" isThreadSafe="true" session="true"%>
 
默认情况下,自动导入了:
java.lang.*,
javax.servlet.*
javax.servlet.jsp.*
javax.servlet.http.*
 
contentType="text/html; charset=GB18030":
JSP默认 MIME 类型:text/html
Servlet默认 MIME 类型:text/plain
pageEncoding默认为 ISO-8859-1
<%@pageEncoding="GB18030"%>
 
session="true":
将JSP 内置对象 绑定到session
JSP开发答疑200问--P26
 
buffer="none" autoFlush="true":
buffer 指定JSP内置对象out使用的缓冲区大小,服务器实际使用的缓冲区比此设置值更大
如果关闭缓冲区,要求设置报头和JSP状态码都要出现在文件顶部,即 html 前
 
isErrorPage="true" errorPage="RelativeURL"
errorPage 放在 WEB-INF 目录中
相关
web.xml 中的 error-page
 
  1. ========
Word, Excel
<%@page contentType="application/msword;charset=GBK" %>
<%@page contentType="application/vnd.ms-excel;charset=GBK" %>
 
  1. ========
include 指令与 include 动作
<%@ include file="" %>    <jsp:include page="">
See: JSP开发答疑200问--P29
 
<jsp:include page="">可以用于包含 WEB-INF 中的文件
 
  1. ========
跳转方法
 
----
转发(请求作用域的参数 在转发的页面间有效)
{
<jsp:forward page=""/> =Servlet 的RequestDispatcher 的 forward方法
由服务器执行
目标可放在 WEB-INF 中
使用 jsp:forward 时,主页面不能有任何内容
}
 
----
重定向(请求作用域的参数 在在重定向到下一页面失效)
{
response.sendRedirect()
发送特殊的Header 给浏览器,由浏览器执行
目标不可放在 WEB-INF 中
调用response.sendRedirect()之前, 主也面不能有任何内容输出
调用之后,应该紧跟 return; 语句
 
页面自动刷新
<meta http-equiv="Refresh" content="秒数"; url="destination">
}
 
  1. ========
参数传递方法
 
----
get, post
 
----
url
 
<a href="transParam.jsp?action=transParam&detail=direct">直接参数传递</a>
response.sendRedirect("transParam.jsp?action=transParam&detail=direct")
 
----
jsp:param
 
<jsp:include page="RelativeURL">
<jsp:param name="paramName" value="paramValue"/>
</jsp:inclue>
 
<jsp:forward page="RelativeURL">
<jsp:param name="paramName" value="paramValue"/>
</jsp:forwad>
 
----
session, request
session 和request 维护着 自身的哈希表
除 int, long 等原生类型外,value 自动继承 java.lang.Object
 
session.setAttribute(name,value);
request.setAttribute(name,value);
 
value=(value.className)session.get(name);
value=(value.className)request.get(name);
 
 
  1. ========
JSP 中包含插件
 
<jsp:plugin
classid = "clsid:CAFEEFAC-0014-0002-0005-ABCDEFFEDCBA"
codebase = "http://java.sun.com/update/1.4.2/jinstall-1_4_2_03-windows-i586.cab#Version=1,4,2,30" width = 170 height = 150 >
 
<jsp:params>
<jsp:param name="CODE" value = "Clock.class" />
<jsp:param name = "type" value = "application/x-java-applet;jpi-version=1.4.2_03"/>
<jsp:param name = "scriptable" value = "false"/>
</jsp:params>
 
<jsp:fallback>
您的浏览器不支持Java Applet.
</jsp:fallback>
 
</jsp:plugin>
 
--------
<!-- HTML CONVERTER -->
<OBJECT classid="clsid:8AD9C840-044E-11D1-B3E9-00805F499D93" width="170" height="150" codebase="http://java.sun.com/products/plugin/1.2.2/jinstall-1_2_2-win.cab#Version=1,2,2,0">
 
<PARAM name="java_code" value="Clock.class">
<PARAM name="type" value="application/x-java-applet;">
<PARAM name="CODE" value="Clock.class">
<PARAM name="java_type" value="application/x-java-applet;jpi-version=1.4.2_03">
<PARAM name="scriptable" value="false">
 
<COMMENT>
 
<EMBED type="application/x-java-applet;" width="170" height="150" pluginspage="http://java.sun.com/products/plugin/" java_code="Clock.class" CODE="Clock.class" java_type="application/x-java-applet;jpi-version=1.4.2_03" scriptable="false"/>
 
<NOEMBED>
您的浏览器不支持Java Applet.
</NOEMBED>
 
</COMMENT>
</OBJECT>
 
 
  1. ========
Applet 与 JavaScript 通信
 
Applet 调用 Javascript
----
netscape.JavaScript.JSObject
netscape.JavaScript.JSException
 
JSObject.getWindow()    获取 JavaScript 窗口的对象
JSObject.getMember("...") 访问 JavaScript 对象
JSObject.eval()    调用 JavaScript 方法
 
注:HTML 中的 Applet 的标签处 需要标明 MAYSCRIPT 属性
 
 
Javascript 调用 Applet
----
function SetText(){
    document.appletName.setTitle("Applect Test");
}
 
See: JSP开发答疑200问--P37
 
 
  1. ======
Applet 中显示另一个 HTML 页面
 
import java.applet.Applet;
import java.applet.AppletContext;
import java.net.URL;
import java.net.MalformedURLException;
 
public class ShowHtml extends Applet {
 
public void start(){
AppletContext ac = getAppletContext();
URL url=getCodeBase();
try{
ac.showDocument(new URL(url + "appletHtml.html"));
}catch(MalformedURLException e){
showStatus("The URL not found.");
}
}
}
 
  1. ========
正确显示特殊字符
 
----
透明的 <textare>:
边框颜色和文本框颜色都与背景颜色 一致的文本框, 并用 disable 设置成只读
 
<span style="BACKGROUND-COLOR: transparent">
<textarea name="textarea" rows="4" style="overflow: auto; border-style:none;" disabled>
第一行文字
第二行文字
第三行文字
</textarea>
</span>
 
----
输入或输出前过滤
 
public class FilterString {
public static String filter(String value) {
if (value == null)
return (null);
 
StringBuffer result = new StringBuffer();
for (int i = 0; i < value.length(); i++) {
char ch = value.charAt(i);
if (ch == '<')
result.append("&lt;");
else if (ch == '>')
result.append("&gt;");
else if (ch == '&')
result.append("&amp;");
else if (ch == '"')
result.append("&quot;");
else if (ch == '/r')
result.append("<BR>");
else if (ch == '/n') {
if (i > 0 && value.charAt(i - 1) == '/r') {
} else {
result.append("<BR>");
}
} else if (ch == '/t')
result.append("&nbsp;&nbsp;&nbsp;&nbsp");
else if (ch == ' ')
result.append("&nbsp;");
else
result.append(ch);
}
return (result.toString());
}
}
 
  1. ========
设置打印格式
 
----
利用CSS
<style type="text/css" media="print">
CSS定义
 </style>
 
----
利用webBrower控件
 
<form name="form1" method="post" action="">
 
<OBJECT id=WebBrowser classid=CLSID:8856F961-340A-11D0-A96B-00C04FD705A2 height=0 width=0>
</OBJECT>
 
<input type=button value=打印 onclick=document.all.WebBrowser.ExecWB(6,1)>
<input type=button value=直接打印 onclick=document.all.WebBrowser.ExecWB(6,6)>
<input type=button value=页面设置 onclick=document.all.WebBrowser.ExecWB(8,1)>
<input type=button value=打印预览 onclick=document.all.WebBrowser.ExecWB(7,1)>
 
</form>
 
  1. ========
request 对象
 
javax.servlet.HttpServletRequest
 
request => 传递到 _jspService() 的 HttpServletRequest 对象
 
----
服务器:
 
getServletPath,接受 客户提交信息 的页面: public String getServletPath() Returns the part of this request's URL that calls the servlet. This path starts with a " / " character and includes either the servlet name or a path to the servlet, but does not include any extra path information or a query string. Same as the value of the CGI variable SCRIPT_NAME. This method will return an empty string ( "" ) if the servlet used to process this request was matched using the " /* " pattern. Returns: a String containing the name or path of the servlet being called, as specified in the request URL, decoded, or an empty string if the servlet used to process the request is matched using the " /* " pattern.
/requestParm.jsp
 
getServerName,服务器的名称:
jackson
 
getServerPort,服务器的端口号:
8080
 
----
客户机:
getRemoteAddr,客户的 IP 地址:
192.168.1.101
 
getRemoteHost,客户机的名称:
192.168.1.101
 
----
信息内容
getProtocol,协议:
HTTP/1.1
 
getContentLength,客户提交信息的长度
26
 
getMethod,客户提交信息的方式
POST
 
getParameterNamesgetParameter(...)客户端提交的所有参数的名字:
field1 = yrdy
field2 = bafgbad
 
 
getHeaderNames(),request.getHeaders("...")
 
<%
out.println("==============<br/>");
 
Enumeration enumHeaded = request.getHeaderNames();
while (enumHeaded.hasMoreElements()) {
String s=(String)enumHeaded.nextElement();
out.println(s);
out.println("<br/>");
 
Enumeration enumHeadedValues = request.getHeaders(s);
while (enumHeadedValues.hasMoreElements()) {
out.println((String) enumHeadedValues.nextElement());
 
out.println("<br/>");
}
 
out.println("-----<br/>");
}
 
out.println("==============<br/>");
%>
 
==============
accept
*/*     //指定客户端能够处理的 MIME 类型(在 Content-Type 响应报头中指明)
----------------
referer
http://jackson:8080/JSPXper/jsp2.jsp
 
(本机访问:http://localhost:8080/JSPXper/jsp2.jsp)
 
/* 应用
String referer=request.getHeader("Referer")
 
if(referer!=null){
    持久化
}
*/
----------------
accept-language
zh-cn //国际化时据此选择相应的资源包
----------------
content-type
application/x-www-form-urlencoded
----------------
ua-cpu
x86
----------------
accept-encoding
gzip, deflate
----------------
user-agent
Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 5.2; .NET CLR 1.1.4322; .NET CLR 2.0.50727)
----------------
host
jackson:8080
 
(本机访问:localhost:8080)
----------------
content-length
26
----------------
connection
Keep-Alive
----------------
cache-control
no-cache
----------------
cookie
JSESSIONID=D43F2CE04DADA2A3AC29813C5B76DCC0
----------------
==============
注意: User-Agent, Referer 很容易被伪造
 
  1. ========
Bean
 <jsp:useBean id="showDate" scope="page" class="jspxper.GetDate"></jsp:useBean>
 
<%= showDate.getNowDate("yyyy/MM/dd hh:mm:ss") %>
 
 
  1. ========
session
 
javax.servlet.http
HttpSession
 
session 的信息保存在服务器端
session 的ID 保存在客户端
 
 
session.getId();
session.isNew();
session.setMaxInactiveInterval(1); // Counted in seconds
session.setAttribute("Attri1",new Integer("4")); //public void setAttribute(String name, Object value)
 
 
  1. =======
PageContext
 
java.lang.Object
javax.servlet.jsp.JspContext
javax.servlet.jsp.PageContext
 
page,request,session,application 等对象可用 PageContext 对象表示
 
PageContext extends JspContext to provide useful context information for when JSP technology is used in a Servlet environment.
 
A PageContext instance provides access to all the namespaces associated with a JSP page, provides access to several page attributes, as well as a layer above the implementation details. Implicit objects are added to the pageContext automatically.
 
The PageContext class is an abstract class, designed to be extended to provide implementation dependent implementations thereof, by conformant JSP engine runtime environments. A PageContext instance is obtained by a JSP implementation class by calling the JspFactory.getPageContext() method, and is released by calling JspFactory.releasePageContext().
 
An example of how PageContext, JspFactory, and other classes can be used within a JSP Page Implementation object is given elsewhere.
 
The PageContext provides a number of facilities to the page/component author and page implementor, including:
 
a single API to manage the various scoped namespaces
a number of convenience API's to access various public objects
a mechanism to obtain the JspWriter for output
a mechanism to manage session usage by the page
a mechanism to expose page directive attributes to the scripting environment
mechanisms to forward or include the current request to other active components in the application
a mechanism to handle errorpage exception processing
Methods Intended for Container Generated Code
 
Some methods are intended to be used by the code generated by the container, not by code written by JSP page authors, or JSP tag library authors.
 
The methods supporting lifecycle are initialize() and release()
 
The following methods enable the management of nested JspWriter streams to implement Tag Extensions: pushBody()
 
Methods Intended for JSP authors
 
The following methods provide convenient access to implicit objects: getException(), getPage() getRequest(), getResponse(), getSession(), getServletConfig() and getServletContext().
 
The following methods provide support for forwarding, inclusion and error handling: forward(), include(), and handlePageException().
 
 
  1. ========
application
 
javax.servlet
Interface ServletContext
 
Defines a set of methods that a servlet uses to communicate with its servlet container, for example, to get the MIME type of a file, dispatch requests, or write to a log file.
 
There is one context per "web application" per Java Virtual Machine. (A "web application" is a collection of servlets and content installed under a specific subset of the server's URL namespace such as /catalog and possibly installed via a .war file.)
 
In the case of a web application marked "distributed" in its deployment descriptor, there will be one context instance for each virtual machine. In this situation, the context cannot be used as a location to share global information (because the information won't be truly global). Use an external resource like a database instead.
 
The ServletContext object is contained within the ServletConfig object, which the Web server provides the servlet when the servlet is initialized.
 
----
public String getServerInfo() --> Apache Tomcat/5.5.14
 
----
public Set getResourcePaths(String path)
 
Returns a directory-like listing of all the paths to resources within the web application whose longest sub-path matches the supplied path argument.
Paths indicating subdirectory paths end with a '/'.
The returned paths are all relative to the root of the web application and have a leading '/'.
 
application.getResourcePaths("/") --> [/Drawing.jsp, /WEB-INF/, /CallOtherApp.jsp, /requestParm.jsp, /jsp2.jsp]
 
----
application.getRealPath("/")
E:/Study/Codes/Java/JBuilderProject/JSPXper/JSPXper/
 
Comp. ASP 中,用 Server.Mappath(".") 实现相同功能
 
/*
request.getRequestURL()
http://localhost:8080/JSPXper/requestParm.jsp
 
request.getRequestURI()
/JSPXper/requestParm.jsp
*/
 
application.getRealPath(request.getRequestURI())
E:/Study/Codes/Java/JBuilderProject/JSPXper/JSPXper/JSPXper/requestParm.jsp
 
----
new java.io.File("/").getAbsolutePath()
D:/
 
/*
java.lang.Object
java.io.File
 
public String getAbsolutePath()
 
Returns the absolute pathname string of this abstract pathname
*/
 
----
获取当前文件所在的文件夹
 
String strRealPath=new java.io.File(application.getRealPath(request.getRequestURI())).getParent();
 
 
----
InputStream getResourceAsStream(String path)
Returns the resource located at the named path as an InputStream object. 
 
Returns the resource located at the named path as an InputStream object.
The data in the InputStream can be of any type or length. The path must be specified according to the rules given in getResource. This method returns null if no resource exists at the specified path.
 
Meta-information such as content length and content type that is available via getResource method is lost when using this method.
 
The servlet container must implement the URL handlers and URLConnection objects necessary to access the resource.
 
This method is different from java.lang.Class.getResourceAsStream, which uses a class loader. This method allows servlet containers to make a resource available to a servlet from any location, without using a class loader.
 
 
Parameters:
path - a String specifying the path to the resource
Returns:
the InputStream returned to the servlet, or null if no resource exists at the specified path
 
----
application.log("JacksonRuan Added Log") --> 
2006-9-10 20:30:02 org.apache.catalina.core.ApplicationContext log
信息: JacksonRuan Added Log
(D:/Java/Apache Software Foundation/Tomcat 5.5/logs/localhost.2006-09-10.log)
 
  1. ========
会话跟踪
 
session, cookie, 隐藏域, URL重写
 
session 在 cookie 中存放 sessionID
 
session:
服务器端的内存里(会使服务器 多次读写磁盘文件)
失效:用户下线,关闭浏览器,session timeout
安全性:用户不能修改
 
cookie:
客户端的硬盘里
失效:决定于 expire属性 (默认为关闭浏览器的时候)
安全性:比较差
用途:存储用户名,密码,配色方案等
 
  1. ========
URL相关
 
out.println("Protocol: " + request.getProtocol() + " <br>");
//public String getProtocol(), javax.servlet ServletRequest
// --> HTTP/1.1
out.println("Host: " + request.getHeader("Host") + " <br>");
//public String getHeader(String name), javax.servlet.http HttpServletRequest
// --> 8080
out.println("Server Name: " + request.getServerName() + " <br>");
//public String getServerName(), javax.servlet.http HttpServletRequest
// --> localhost
out.println("Server Port: " + request.getServerPort() + "<br> ");
//public int getServerPort(), javax.servlet.http HttpServletRequest
// --> 8080
out.println("HTTP Method: " + request.getMethod() + " <br>");
//public String getMethod(), javax.servlet.http HttpServletRequest
// --> GET
 
 
out.println("Path Info: " + request.getPathInfo() + " <br>");
//public String getPathInfo(), javax.servlet.http HttpServletRequest
// --> null
out.println("Path Trans: " + request.getPathTranslated() + "<br> ");
//public String getPathTranslated(), javax.servlet.http HttpServletRequest
// --> null
 
----
http: //localhost:8080/JSPXper/showURLInfo.jsp
 
http: //hostName:port/contextPath/servletPath?parm1=parmValue1&parm2=parmValue2
 
out.println("Context Path: " + request.getContextPath() + "<br> ");
//public String getContextPath(), javax.servlet.http HttpServletRequest
// --> /JSPXper
out.println("Servlet Path: " + request.getServletPath() + " <br>");
//public String getServletPath(),javax.servlet.http HttpServletRequest
// --> /showURLInfo.jsp
----
out.println("Request URI: " + request.getRequestURI() + "<br> ");
//public String getRequestURI(), javax.servlet.http HttpServletRequest
// --> /JSPXper/showURLInfo.jsp
out.println("Request URL: " + request.getRequestURL() + "<br> ");
//public StringBuffer getRequestURL(),javax.servlet.http HttpServletRequest
// --> http://localhost:8080/JSPXper/showURLInfo.jsp
out.println("Query String: " + request.getQueryString() + "<br> ");
//public String getServletPath(),javax.servlet.http HttpServletRequest
// --> cat&food=fish&requestMethod=GET
 
----
javax.servlet.http
Interface HttpServletRequest
 
public String getPathInfo()
 
Returns any extra path information associated with the URL the client sent when it made this request. The extra path information follows the servlet path but precedes the query string and will start with a "/" character.
This method returns null if there was no extra path information.
 
Same as the value of the CGI variable PATH_INFO.
 
Returns:
a String, decoded by the web container, specifying extra path information that comes after the servlet path but before the query string in the request URL; or null if the URL does not have any extra path information
 
 
public String getPathTranslated()
 
Returns any extra path information after the servlet name but before the query string, and translates it to a real path. Same as the value of the CGI variable PATH_TRANSLATED.
If the URL does not have any extra path information, this method returns null or the servlet container cannot translate the virtual path to a real path for any reason (such as when the web application is executed from an archive). The web container does not decode this string.
Returns:
a String specifying the real path, or null if the URL does not have any extra path information
 
  1. ========
获取请求中所有参数
 
客户端提交的所有参数的名字:<br/>
<%
Enumeration enumParmNames = request.getParameterNames();
while (enumParmNames.hasMoreElements()) {
 
String parmName = (String) enumParmNames.nextElement();
String[] parmValues = request.getParameterValues(parmName);
out.println(parmName + ": ");
 
for (int index = 0; index < parmValues.length; index++) {
String parmValuesGB = new String(parmValues[index].getBytes("ISO-8859-1"), "GB2312");
out.println(parmName + "_" + index + "=" + parmValuesGB);
if (index != parmValues.length - 1) {
out.println(",");
}
}
out.println("<br/>");
}
%>
 
  1. ========
获取完整的请求URL
 
<%
String fullRUL="";
StringBuffer url=request.getRequestURL();
 
// URL中有查询串,即 method=get
if (request.getQueryString()!=null) {
url.append('?');
url.append(request.getQueryString());
}else { // URL中没有查询串,即 method=post
java.util.Enumeration params=request.getParameterNames();
 
// 没有参数的 post 表单
if (params==null || !params.hasMoreElements()) {
fullRUL=url.toString();
}
 
// 有参数的 post 表单
url.append('?');
String name=(String)params.nextElement();
url.append(name);
url.append("=");
url.append(request.getParameter(name));
 
while (params.hasMoreElements()) {
url.append("&");
name=(String)params.nextElement();
url.append(name);
url.append("=");
url.append(request.getParameter(name));
}
}
 
fullRUL=url.toString();
out.print(fullRUL);
%>
 
  1. ========
判断session是否过期
 
javax.servlet.http
Interface HttpServletRequest
 
----
public HttpSession getSession(boolean create)
 
Returns the current HttpSession associated with this request or, if there is no current session and create is true, returns a new session.
If create is false and the request has no valid HttpSession, this method returns null.
 
To make sure the session is properly maintained, you must call this method before the response is committed. If the container is using cookies to maintain session integrity and is asked to create a new session when the response is committed, an IllegalStateException is thrown.
 
Parameters:
create - true to create a new session for this request if necessary; false to return null if there's no current session
Returns:
the HttpSession associated with this request or null if create is false and the request has no valid session
 
----
public HttpSession getSession()
Returns the current session associated with this request, or if the request does not have a session, creates one.
 
Returns:
the HttpSession associated with this request
 
----
if(request.getSession(false)==true){
session已经过期
}else{
session未经过期
}
 
  1. ========
在response 对象中控制页面缓存
 
<%
response.setHeader("Cache-Control","no-cache"); //不缓存
response.setHeader("Cache-Control","no-store"); //不缓存,并且不存储到临时目录
response.setDateHeader("Expires", 0); //规定内容的过期时间
response.setHeader("Pragma","no-cache");
%>
 
----
long curTime=System.currentTimeMillis();
long expired=1*60*1000; // 以毫秒来计算
response.setDateHeader("Expires",curTime+expired);
 
 
 
 
原创粉丝点击