to: zcjl() ( )
请贴一些技巧的源码或模式等。 像"大款"之类不算技巧吧!
请贴一些技巧的源码或模式等。 像"大款"之类不算技巧吧!
解决方案 »
- <c:forEach items="" var="">使用解释?
- FCKeditor怎样得到提交的文本内容,如果没用过那MyEclipse调试时怎么查看request的各个param的值
- 助网页变灰的问题
- 大虾们来看看我的程序是什么地方有问题?总是只显示第一页的内容,不会翻页
- Java技术交流群:37773450,欢迎你的加入!!
- 急用,查询不区分大小写问题?谢谢
- 各位高手,请教字符函数
- 要往数据库里插入当前时间该怎么插入?
- 聘请JSP/BEA/Oracle辅导老师解决技术问题
- base64在java里重新转成图片,结果图片打不开
- request.getParameter(name)方法在本页中可获得参数值吗?
- 编译时出现这段代码是什么意思??
http://www.mypcera.com/softxue/pian/jsp.htm
1、使用java提供的方法,在jsp或者servlet中都可以
<%
response.setHeader("Pragma","No-cache");
response.setHeader("Cache-Control","no-cache");
response.setDateHeader("Expires", 0);
%>
2|、使用HTML标记,如下面:
<HEAD>
<META HTTP-EQUIV="Pragma" CONTENT="no-cache">
<META HTTP-EQUIV="Cache-Control" CONTENT="no-cache">
<META HTTP-EQUIV="Expires" CONTENT="0">
</HEAD>
import java.math.*;
public class TestMd5
{
public String MD5(String sInput) throws Exception{
String algorithm="";
//输入不能为空
if(sInput.trim()==null){
return "null";
}
//指定采用MD5算法
try{
algorithm=System.getProperty("MD5.algorithm","MD5");
}catch(SecurityException se){
}
//定义MessageDigest对象
MessageDigest md=MessageDigest.getInstance(algorithm);
//按照系统缺省的字符编码方式把sInput 转换成字节,并把结果存到一新的字节数组buffer中
byte buffer[]=sInput.getBytes();
//从指定的字节数组buffer的偏移量0开始,用指定的字节数组修改由sInput生成摘要
//count为从 0 开始用的字节数长度。
for(int count=0;count<sInput.length();count++)
{
md.update(buffer,0,count);
}
//通过执行最后的诸如填充的操作完成散列码的计算。 在调用之后复位该摘要
//返回存放结果散列值的字节数组bDigest
byte bDigest[]=md.digest();
//将bDigest转换为大整数bi
BigInteger bi=new BigInteger(bDigest);
//返回bi字符串表示,即最终的编码结果
return(bi.toString(16));
} public static void main(String [] a)
{
TestMd5 my = new TestMd5();
try
{
System.out.println(my.MD5("abc"));
//50f260602273676bfc60ab35352d8d40 //111
//-19da6a11674a7aeac2537831e54963c4 //abc
}catch (Exception e){}
}
}
* 如传入字符型"-5" 意为将当前日期减去5天的日期
* 如传入字符型"5" 意为将当前日期加上5天后的日期
* 返回字串 例(1999-02-03)
*/
public String dateAdd(String to)
{
//日期处理模块 (将日期加上某些天或减去天数)返回字符串
int strTo;
try {
strTo = Integer.parseInt(to);
}
catch (Exception e) {
System.out.println("日期标识转换出错! : \n:::" + to + "不能转为数字型");
e.printStackTrace();
strTo = 0;
}
Calendar strDate = Calendar.getInstance(); //java.util包
strDate.add(strDate.DATE, strTo); //日期减 如果不够减会将月变动
//生成 (年-月-日) 字符串
String meStrDate = strDate.get(strDate.YEAR) + "-" +
String.valueOf(strDate.get(strDate.MONTH)+1) + "-" + strDate.get(strDate.DATE); return meStrDate;
}
* 提供 IO 操作的工具类
* @version 1.0
* @author 陶建风
*/
public final class StreamUtil
{
/**
* 将输入流复制到输出流
* @param is
* @param os
* @throws IOException
*/
public final static void write(InputStream is, OutputStream os) throws IOException
{
BufferedInputStream bis = new BufferedInputStream(is, 1024);
int c = bis.read();
while(c != -1)
{
os.write(c);
c = bis.read();
}
os.flush();
} /**
* 将输入流按指定的编码转成字符串
* @param is
* @param encoding
* @return
* @throws IOException
*/
public final static String toString(InputStream is, String encoding) throws IOException
{
ByteArrayOutputStream bos = new ByteArrayOutputStream();
write(is, bos);
if(encoding == null) return new String(bos.toByteArray());
else return new String(bos.toByteArray(), encoding); } /**
* 将输入流按默认的编码转成字符串
* @param is
* @return
* @throws IOException
*/
public final static String toString(InputStream is) throws IOException
{
return toString(is, null);
} /**
* 关闭输入流,忽略异常
* @param is
*/
public final static void closeQuitely(InputStream is)
{
try
{
if(is != null) is.close();
}
catch (IOException e)
{
} } /**
* 关闭输出流,忽略异常
* @param os
*/
public final static void closeQuitely(OutputStream os)
{
try
{
if(os != null) os.close();
}
catch (IOException e)
{
}
} /**
* 半闭输入输出流,忽略异常
* @param is
* @param os
*/
public final static void closeQuitely(InputStream is, OutputStream os)
{
closeQuitely(is);
closeQuitely(os);
}
}
package com.iaworld.util;
import org.apache.commons.codec.base64.Base64;/**
* 提供对 URL 进行处理的工具类
*/
public class URLUtil
{
/**
* 将 URL 参数据进行安全编码
* @param s
* @return
*/
public final static String safeRequestParameter(String s)
{
byte[] b = Base64.encode(s.getBytes());
StringBuffer sb = new StringBuffer();
for(int i = 0; i < b.length; i++)
{
sb.append("%" + Integer.toHexString(b[i]));
}
return sb.toString(); }
/**
* 对 URL 参数据进行安全解码
* @param s
* @return
*/
public final static String decodeSafeRequestParameter(String s)
{
return new String(Base64.decode(s.getBytes()));
}
}
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerException;
import javax.xml.transform.TransformerFactory;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.stream.StreamResult;
import java.io.*;/**
* 提供对 DOM 操作的工具类
*
* @version 1.0
* @author 陶建风
*/
public final class DOMUtil
{
private static Transformer transformer = null;
/**
* 将 Document 对象输出到流
* @param doc
* @param os
* @throws TransformerException
*/
public final static void saveDOMTree(Document doc, OutputStream os) throws TransformerException
{
Transformer t = getTransformer();
DOMSource src = new DOMSource(doc);
StreamResult rs = new StreamResult(os);
t.transform(src, rs);
} /**
* 将 Document 对象输出到文件
* @param doc
* @param file
* @throws FileNotFoundException
* @throws TransformerException
*/
public final static void saveDOMTree(Document doc, File file) throws FileNotFoundException, TransformerException
{
FileOutputStream fos = null; try
{
fos = new FileOutputStream(file);
saveDOMTree(doc, fos);
}
catch (FileNotFoundException e)
{
throw e;
}
finally
{
try
{
if(fos != null) fos.close();
}
catch (IOException e)
{
}
} } private static Transformer getTransformer() throws TransformerConfigurationException
{
if(transformer == null)
{
TransformerFactory tf = TransformerFactory.newInstance();
transformer = tf.newTransformer();
}
return transformer;
}}
package com.iaworld.web.filters;import javax.servlet.*;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;/**
* 用于的使 Browser 不缓存页面的过滤器
* @version 1.0
* @author 陶建风
*/
public class ForceNoCacheFilter
implements Filter
{ public void doFilter(ServletRequest request, ServletResponse response, FilterChain filterChain) throws IOException, ServletException
{
((HttpServletResponse) response).setHeader("Cache-Control","no-cache");
((HttpServletResponse) response).setHeader("Pragma","no-cache");
((HttpServletResponse) response).setDateHeader ("Expires", -1);
filterChain.doFilter(request, response);
} public void destroy()
{
} public void init(FilterConfig filterConfig) throws ServletException
{
}
}package com.iaworld.web.filters;import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.List;
import java.util.ArrayList;
import java.util.StringTokenizer;
import java.io.IOException;/**
* 用于检测用户是否登陆的过滤器,如果未登录,则重定向到指的登录页面<p>
* 配置参数<p>
* checkSessionKey 需检查的在 Session 中保存的关键字<br>
* redirectURL 如果用户未登录,则重定向到指定的页面,URL不包括 ContextPath<br>
* notCheckURLList 不做检查的URL列表,以分号分开,并且 URL 中不包括 ContextPath<br>
*
* @version 1.0
* @author TaoJianFeng
*/
public class CheckLoginFilter
implements Filter
{
protected FilterConfig filterConfig = null;
private String redirectURL = null;
private List notCheckURLList = new ArrayList();
private String sessionKey = null; public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
HttpServletRequest request = (HttpServletRequest) servletRequest;
HttpServletResponse response = (HttpServletResponse) servletResponse; HttpSession session = request.getSession();
if(sessionKey == null)
{
filterChain.doFilter(request, response);
return;
}
if((!checkRequestURIIntNotFilterList(request)) && session.getAttribute(sessionKey) == null)
{
response.sendRedirect(request.getContextPath() + redirectURL);
return;
}
filterChain.doFilter(servletRequest, servletResponse);
} public void destroy()
{
notCheckURLList.clear();
} private boolean checkRequestURIIntNotFilterList(HttpServletRequest request)
{
String uri = request.getServletPath() + (request.getPathInfo() == null ? "" : request.getPathInfo());
return notCheckURLList.contains(uri);
} public void init(FilterConfig filterConfig) throws ServletException
{
this.filterConfig = filterConfig;
redirectURL = filterConfig.getInitParameter("redirectURL");
sessionKey = filterConfig.getInitParameter("checkSessionKey"); String notCheckURLListStr = filterConfig.getInitParameter("notCheckURLList"); if(notCheckURLListStr != null)
{
StringTokenizer st = new StringTokenizer(notCheckURLListStr, ";");
notCheckURLList.clear();
while(st.hasMoreTokens())
{
notCheckURLList.add(st.nextToken());
}
}
}
}package com.iaworld.web.filters;
import javax.servlet.*;
import java.io.IOException;/**
* 用于设置 HTTP 请求字符编码的过滤器,通过过滤器参数encoding指明使用何种字符编码,用于处理Html Form请求参数的中文问题
* @version 1.0
* @author 陶建风
*/
public class CharacterEncodingFilter
implements Filter
{
protected FilterConfig filterConfig = null;
protected String encoding = ""; public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException
{
if(encoding != null)
servletRequest.setCharacterEncoding(encoding);
filterChain.doFilter(servletRequest, servletResponse);
} public void destroy()
{
filterConfig = null;
encoding = null;
} public void init(FilterConfig filterConfig) throws ServletException
{
this.filterConfig = filterConfig;
this.encoding = filterConfig.getInitParameter("encoding"); }
}
package com.iaworld.web.taglibs;import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.io.IOException;/**
* 将标签体的的空格转换成
* @version 1.0
* @author TaoJianFeng
*/
public class Space2NbspTag
extends BodyTagSupport
{
private String bodyText; public int doAfterBody() throws JspException
{
if(bodyContent != null)
{
bodyText = bodyContent.getString();
}
return SKIP_BODY;
}
public int doEndTag() throws JspException
{
try
{
JspWriter out = pageContext.getOut();
StringBuffer buffer = new StringBuffer();
for(int i = 0, count = bodyText.length(); i < count; i++)
{
char ch = bodyText.charAt(i);
if(ch == ' ') buffer.append(" ");
else buffer.append(ch);
}
if(bodyText != null) out.print(buffer.toString());
return SKIP_BODY;
}
catch(IOException e)
{
throw new JspException(e.getMessage());
} }
}
package com.iaworld.web.taglibs;import com.iaworld.web.utils.ResponseUtils;import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.io.IOException;/**
* 将将标签体的文字过滤成浏览器可以正确显示的字符串
* @version 1.0
* @author TaoJianFeng
*/
public class FilterTag
extends BodyTagSupport
{
private String bodyText; public int doAfterBody() throws JspException
{
if(bodyContent != null)
{
bodyText = bodyContent.getString().trim();
}
return SKIP_BODY;
}
public int doEndTag() throws JspException
{
try
{
JspWriter out = pageContext.getOut();
if(bodyText != null) out.print(ResponseUtils.filter(bodyText));
return SKIP_BODY;
}
catch(IOException e)
{
throw new JspException(e.getMessage());
} }
}
package com.iaworld.web.taglibs;import com.iaworld.web.utils.ResponseUtils;import javax.servlet.jsp.tagext.TagSupport;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.util.Date;
import java.text.SimpleDateFormat;
import java.io.IOException;/**
* 以指定的格式输出当前日期
* @version 1.0
* @author TaoJianFeng
*/
public class CurrentDateTag
extends TagSupport
{
private String format = null;
public int doStartTag() throws JspException
{
JspWriter out = pageContext.getOut();
try
{
Date curDate = new Date();
SimpleDateFormat sdf = null;
if(format != null)
sdf = new SimpleDateFormat(format);
else
sdf = new SimpleDateFormat();
String str = sdf.format(curDate);
out.print(ResponseUtils.filter(str));
return SKIP_BODY;
}
catch(IOException e)
{
throw new JspException(e.getMessage());
}
} public String getFormat()
{
return format;
} public void setFormat(String format)
{
this.format = format;
}
}package com.iaworld.web.taglibs;import javax.servlet.jsp.tagext.BodyTagSupport;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspWriter;
import java.io.IOException;/**
* 将标签体的回车换行换成 <BR>
* @version 1.0
* @author TaoJianFeng
*/
public class CrLf2BRTag
extends BodyTagSupport
{
private String bodyText; public int doAfterBody() throws JspException
{
if(bodyContent != null)
{
bodyText = bodyContent.getString().trim();
}
return SKIP_BODY;
}
public int doEndTag() throws JspException
{
try
{
JspWriter out = pageContext.getOut();
StringBuffer buffer = new StringBuffer();
for(int i = 0, count = bodyText.length(); i < count; i++)
{
char ch = bodyText.charAt(i);
if(ch == '\n') buffer.append("<br/>");
if(!Character.isISOControl(ch)) buffer.append(ch);
}
if(bodyText != null) out.print(buffer.toString());
return SKIP_BODY;
}
catch(IOException e)
{
throw new JspException(e.getMessage());
} }
}
* Created by IntelliJ IDEA.
* @version 1.0
* @author TaoJianFeng
*/
public final class ResponseUtils
{
/**
* 将指定的字符串过滤成浏览器可以正确显示的字符串
* @param value
* @return
*/
public final static String filter(String value)
{ if (value == null)
return (null); char content[] = new char[value.length()];
value.getChars(0, value.length(), content, 0);
StringBuffer result = new StringBuffer(content.length + 50);
for (int i = 0; i < content.length; i++)
{
switch (content[i])
{
case '<':
result.append("<");
break;
case '>':
result.append(">");
break;
case '&':
result.append("&");
break;
case '"':
result.append(""");
break;
case '\'':
result.append("'");
break;
default:
result.append(content[i]);
}
}
return (result.toString()); }}
http://expert.csdn.net/Expert/topic/2878/2878705.xml?temp=.2906458是一个好贴
测试环境为 jdk1.2.2 jswdk-1.0 winnt4.0中文版。 1。java是大小写敏感的,用过其他编程语言的人最容易犯这个错误,尤其是刚上手的时候。我刚开始调试jsp的时50%以上的编译错误是都是因为这个。 2。java的调用过程都是要加括号的,一开始比较容易忽视,如title=request.getParameter(\"title\").trim(); 3。jsp中对应asp中的request.form()和request.querystring()的解决方法。
jsp中取得参数没有form和queryString之分,都是通过request.getParameter(\"XXXX\")来取得。虽然jsp也有request.getQueryString()方法,但测试结果是 test.jsp?id=1&page=20 得到 id=1&page=20。
如果url和form有相同的参数名称呢?下面是一段测试代码:
<form method=\"POST\" action=\"query.jsp?id=2\">
<input type=\"text\" name=\"id\" value=\"1\" size=\"60\">
</form>
name都是id,结果是url的参数优先得到,jsp的这种处理方式和asp相比我觉的各有所长。 4。头疼的汉字处理问题。
在其他的文章里曾说到在中文NT环境下如下语句输出会得到乱码,
<%=\"你好\"%> 及 out.print(\"你好\");等。解决方法是只要对字符串变量进行编码就可以得到正确结果,如下代码可以得到正确的输出:
<% String title=\"你好\";
byte[] tmpbyte=title.getBytes(\"ISO8859_1\");
title=new String(tmpbyte);
out.print(title); %>
或者<%=title%> 关于sql语句汉字问题,例句为 select * from test where title=\'谁是傻瓜\'
在jdbc-odbc驱动下连db2,不管是原句还是对sql语句进行编码后都死活通不过。
换了ibm的jdbc直接驱动后,对sql语句编码后程序可以通过。 这个问题的产生大概是中文NT的原因,在其他环境下可能就没汉字处理问题了,据说ibm的web sphere对中文支持的很好,这也给jsp的开发带来一定的通用性问题。据说对字符串编码是一种通用的解决方法,不过没有这么多环境来测试。 5。在asp中经常使用到字符串判断语句如 if state=\"真是傻瓜\" then.....
在java中String变量不是一个简单的变量而是一个类实例,不同的方法会得到不同的结果
a.
String str1=\"我是傻瓜\";
String str2=\"我是傻瓜\"; (or String str2=\"我是\"+\"傻瓜\"; )
if (str1==str2)
out.print(\"yes\");
else
out.print(\"no\");
结果是\"yes\"。
大概是编译优化,str1,str2指向同一个类实例; b.
String str1,str2,str3;
str1=\"我是傻瓜\";
str2=\"我是\";
str3=str2+\"傻瓜\";
if (str1==str3)
out.print(\"yes\");
else
out.print(\"no\");
结果是\"no\"。 String str1=new String(\"我是傻瓜\");
String str2=new String(\"我是傻瓜\");
if (str1==str2)
out.print(\"yes\");
else
out.print(\"no\");
结果是\"no\"。 String str1=new String(\"我是傻瓜\");
String str2=new String(\"我是傻瓜\");
if (str1.compareTo(str2)==0)
out.print(\"yes\");
else
out.print(\"no\");
结果是\"yes\"。 所以在jsp中判断字符串要使用compareTo方法,用惯传统语言还真一下子适应不过来,熟悉java的朋友应该没这个问题。 6。如何判断数据库为空?
result = stmt.executeQuery(sql);
if (result.next())
......
result执行后游标出于一个未明的状态,不能进行状态判断,也不能取值,一定要next()一下才可以用。
7。在jsp中实现分页。
page是关键字,不能当变量。
conn.jsp
<%
String sDBDriver = \"COM.ibm.db2.jdbc.app.DB2Driver\";
String sConnStr = \"jdbc:db2:faq\";
Connection conn = null;
Statement stmt = null;
ResultSet rs=null;
try {
Class.forName(sDBDriver);
}
catch(java.lang.ClassNotFoundException e) {
out.print(\"faq(): \" + e.getMessage());
}
try{
conn = DriverManager.getConnection(sConnStr,\"wsdemo\",\"wsdemo1\");
stmt = conn.createStatement();
}catch(SQLException e){
out.print(e.toString());
}
%> query.jsp <%@ page language=\"java\" import=\"java.sql.*\" %>
<%@ page contentType=\"text/html; charset=gb2312\" %>
<%@ include file=\"conn.jsp\" %>
<%
.......
int pages=0;
int pagesize=10;
ResultSet result = null;
ResultSet rcount = null; pages = new Integer(request.getParameter(\"pages\")).intValue(); if (pages>0)
{ String sql=\" state=\'我不傻\'\";
int count=0;
try {
rcount = stmt.executeQuery(\"SELECT count(id) as id from user where \"+sql);
catch(SQLException ex) {
out.print(\"aq.executeQuery: \" + ex.getMessage());
}
if(rcount.next())
count = rcount.getInt(\"id\");
rcount.close(); if (count>0)
{
sql=\"select * from user where \"+sql;
try {
result = stmt.executeQuery(sql);
}
catch(SQLException ex) {
out.print(\"aq.executeQuery: \" + ex.getMessage());
} int i;
String name;
// result.first();
// result.absolute((pages-1)*pagesize);
// 此方法jdbc2.0支持。编译通过,但执行不过,不知是不是跟驱动有关,只好用下面的笨办法。
for(i=1;i<=(pages-1)*pagesize;i++)
result.next();
for(i=1;i<=pagesize;i++) {
if (result.next()) {
name=result.getString(\"name\");
out.print(name);
}
result.close();
int n= (int)(count/pagesize);
if (n*pagesize<count) n++;
if (n>1)
{
for(i=1;i<=n;i++)
out.print(\"<a href=query.jsp?pages=\"+i+\">\"+i+\" </a>\");
}
}
}
%>
create table test(test1 varchar(20),test2 varchar(20)
然后向这个表写入一条测试纪录
那么现在开始我们的jsp和数据库之旅吧。
一、jsp连接Oracle8/8i/9i数据库(用thin模式)
testoracle.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("oracle.jdbc.driver.OracleDriver").newInstance();
String url="jdbc:oracle:thin:@localhost:1521:orcl";
//orcl为你的数据库的SID
String user="scott";
String password="tiger";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
二、jsp连接Sql Server7.0/2000数据库
testsqlserver.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("com.microsoft.jdbc.sqlserver.SQLServerDriver").newInstance();
String url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=pubs";
//pubs为你的数据库的
String user="sa";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
三、jsp连接DB2数据库
testdb2.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("com.ibm.db2.jdbc.app.DB2Driver ").newInstance();
String url="jdbc:db2://localhost:5000/sample";
//sample为你的数据库名
String user="admin";
String password="";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
四、jsp连接Informix数据库
testinformix.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("com.informix.jdbc.IfxDriver").newInstance();
String url =
"jdbc:informix-sqli://123.45.67.89:1533/testDB:INFORMIXSERVER=myserver;
user=testuser;password=testpassword";
//testDB为你的数据库名
Connection conn= DriverManager.getConnection(url);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
五、jsp连接Sybase数据库
testmysql.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("com.sybase.jdbc.SybDriver").newInstance();
String url =" jdbc:sybase:Tds:localhost:5007/tsdata";
//tsdata为你的数据库名
Properties sysProps = System.getProperties();
SysProps.put("user","userid");
SysProps.put("password","user_password");
Connection conn= DriverManager.getConnection(url, SysProps);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
六、jsp连接MySQL数据库
testmysql.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("org.gjt.mm.mysql.Driver").newInstance();
String url ="jdbc:mysql://localhost/softforum?user=soft&password=soft1234&useUnicode=true&characterEncoding=8859_1"
//testDB为你的数据库名
Connection conn= DriverManager.getConnection(url);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
七、jsp连接PostgreSQL数据库
testmysql.jsp如下:
<%@ page contentType="text/html;charset=gb2312"%>
<%@ page import="java.sql.*"%>
<html>
<body>
<%Class.forName("org.postgresql.Driver").newInstance();
String url ="jdbc:postgresql://localhost/soft"
//soft为你的数据库名
String user="myuser";
String password="mypassword";
Connection conn= DriverManager.getConnection(url,user,password);
Statement stmt=conn.createStatement(ResultSet.TYPE_SCROLL_SENSITIVE,ResultSet.CONCUR_UPDATABLE);
String sql="select * from test";
ResultSet rs=stmt.executeQuery(sql);
while(rs.next()) {%>
您的第一个字段内容为:<%=rs.getString(1)%>
您的第二个字段内容为:<%=rs.getString(2)%>
<%}%>
<%out.print("数据库操作成功,恭喜你");%>
<%rs.close();
stmt.close();
conn.close();
%>
</body>
</html>
在JSP中可以使用如下方式包含纯HTML:
<!--#include file="data.inc"-->
但是如果data.inc中包含JSP CODE ,我们可以使用:
<%@include file="data.inc"%>
如何执行一个线程安全的JSP?
只需增加如下指令
<%@ page isThreadSafe="false" %>
JSP如何处理HTML FORM中的数据?
通过内置的request对象即可,如下:
<%
String item = request.getParameter("item");
int howMany = new Integer(request.getParameter("units")).intvalue();
%>
在JSP如何包含一个静态文件?
静态包含如下:<%@ include file="copyright.html" %>
动态包含如下:<jsp:include page="copyright.html" flush="true"/>
在JSP中如何使用注释?
主要有四中方法:
1。<%-- 与 --%>
2。//
3。/**与**/
4。<!--与-->
在JSP中如何执行浏览重定向?
使用如下方式即可:response.sendRedirect("http://ybwen.home.chinaren.com/index.html";);
也能物理地改变HTTP HEADER属性,如下:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn="/newpath/index.html";
response.setHeader("Location",newLocn);
%>
如何防止在JSP或SERVLET中的输出不被BROWSER保存在CACHE中?
把如下脚本加入到JSP文件的开始即可:
<%
response.setHeader("Cache-Control","no-store"); //HTTP 1.1
response.setHeader("Pragma","no-cache"); //HTTP 1.0
response.setDateHeader ("Expires", 0); //prevents caching at the proxy server
%>
在JSP中如何设置COOKIE?
COOKIE是作为HTTP HEADER的一部分被发送的,如下方法即可设置:
<%
Cookie mycookie = new Cookie("aName","avalue");
response.addCookie(mycookie);
%>
在JSP中如何删除一个COOKIE?
<%
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
%>
在一个JSP的请求处理中如何停止JSP的执行
如下例:
<%
if (request.getParameter("wen") != null) {
// do something
} else {
return;
}
%>
在JSP中如何定义方法
你可以定义方法,但是你不能直接访问JSP的内置对象,而是通过参数的方法传递。如下:
<%!
public String howBadFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();
...
return req.getRemoteHost();
}
%>
<%
out.print("in general,lao lee is not baddie ");
%>
<%= howBadFrom(request) %>
如果BROWSER已关闭了COOKIES,在JSP中我如何打开SESSION来跟踪
使用URL重写即可,如下:
hello1.jsp
<%@ page session="true" %>
<%
Integer num = new Integer(100);
session.putvalue("num",num);
String url =response.encodeURL("hello2.jsp");
%>
<a href='<%=url%>'>hello2.jsp</a> hello2.jsp
<%@ page session="true" %>
<%
Integer i= (Integer )session.getvalue("num");
out.println("Num value in session is "+i.intvalue());
%>
在JSP中能发送EMAIL吗
可以使用SUN的专用包:sun.net.smtp包。如下脚本使用SmtpClient类发送EMAIL。
<%@ page import="sun.net.smtp.SmtpClient, java.io.*" %>
<%
String from="[email protected]";
String to="[email protected], [email protected]";
try{
SmtpClient client = new SmtpClient("mail.xxxxx.xxx");
client.from(from);
client.to(to);
PrintStream message = client.startMessage();
message.println("To: " + to);
message.println("Subject: Sending email from JSP!");
message.println("This was sent from a JSP page!");
message.println();
message.println("Cool! ");
message.println();
message.println("Good Boy");
message.println("I'm in genius.com");
message.println();
client.closeServer();
}
catch (IOException e){
System.out.println("ERROR SENDING EMAIL:"+e);
}
%>
在SERVLET中我能调用一个JSP错误页吗
当然没问题,如下展示了如何在一个SERVLET控制逻辑单元内调用一个JSP错误页面。
protected void sendErrorRedirect(HttpServletRequest request,
HttpServletResponse response, String errorPageURL,
Throwable e)
throws ServletException, IOException {
request.setAttribute ("javax.servlet.jsp.jspException", e);
getServletConfig().getServletContext().
getRequestDispatcher(errorPageURL).forward(request,
response);
} public void doPost(HttpServletRequest request,HttpServletResponse response) {
try {
// do something
} catch (Exception ex) {
try {
sendErrorRedirect(request,response,"/jsp/MyErrorPage.jsp",ex);
} catch (Exception e) {
e.printStackTrace();
}
}
}
JSP和APPLET如何通讯
JSP如何与EJB SessionBean通讯
下面的代码段作了很好的示范
<%@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" %>
<%!
//定义一个对SessionBeanHome接口实例的全局引用
AccountHome accHome=null; public void jspInit() {
//获得Home接口实例
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
//实例化SessionBean
Account acct = accHome.create();
//调用远程方法
acct.doWhatever(...);
// 如此等等
%>
当我使用一个结果集时,如何防止字段为"null"的字域显示在我的HTML输入文本域中?
可以定义一个简单的函数来达到目的,如下:
<%!
String blanknull(String s) {
return (s == null) ? "" : s;
}
%> 然后在JSP的FORM中,可以这样使用
<input type="text" name="shoesize" value="<%=blanknull(shoesize)%>">
如何中SERVLET或JSP下载一个文件(如:binary,text,executable)?
现提供两个解决方案:
A:使用HTTP,如
点击下载网络恐龙图片(这个地址是假的) B:在Servlet中,通过设置ContentType和使用java.io包的Stream等类可作到.例如:
response.setContentType("application/x-msword");
然后想输出缓冲中写一些东东即可。 使用useBean标志初始化BEAN时如何接受初始化参数
使用如下两标签即可:
<jsp:getProperty name="wenBean" property="someProperty"/>
<jsp:setProperty name="wenBean" property="someProperty" value="somevalue"/>
首先对mysql的jsbc驱动包进行路径设置!通常有classpath,web-inf/lib2种。
其次对测试的jsp代码中的URL,username,password进行正确设置。
检查机器上mysql的版本(alpha版本不能正常配合jsp运行)及端口号(例如防火墙对3306的屏蔽)。
以上具体细节均可在csdn搜索获得。
以上只是初学者一点心得还请各位大虾多多指点!
一个关于大型数据分页的实现方案·(******非常适合数据量大*******)
import java.servlet.http.HttpSessionEvent;
import java.servlet.http.HttpSessionListener;public class counterListenerExam implements HttpSessionListener{ private static int count = 0;
private static int activeCount = 0; public void sessionCreate(HttpSessionEvent evt){
long time = evt.getSession().getCreationTime();
System.out.println("session 建立的时间" + new Date(time)); count ++;
activeCount ++;
} public void sessionDestroyed(HttpSessionEvent evt){
activeCount --
} public static String getCounteInfo(){ return "建立总数:" + count + "\n" +
"活动总数:" + activeCount;
}
}
2. 监听器的配置: 通过WEB应用程序的XML部署符WEB.XNL实现,在WEB.XML中添加一个<listener>元素,并嵌套<listner-class>元素(对应监听器的名称) web.xml
...
..
<listener>
<listener-class>Bean.Sample</listener-class>
</listener>
...3. JSP页应用 <%@page import="Bean.Sample"%>
<%
Sample.getCounterInfo();
%>
http://expert.csdn.net/Expert/topic/2313/2313381.xml?temp=.8516199
PPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPPP
Thanks!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!
double myNumber=12345.0199;
//转换数字格式为货币格式;
String myString = NumberFormat.getCurrencyInstance().format(myNumber);
System.out.println(myString);控制台输出为:
¥12,345.02
DecimalFormat to= new DecimalFormat("0.00");
System.out.println(to.format(d)); 控制台输出:
1.26