通过问答方式来认识学习JSP
来源:不详 时间:07-06-06 点击: 点击这里收藏本文
12、如果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());
%>
13、在JSP中能发送EMAIL吗
可以使用SUN的专用包:sun.net.smtp包。如下脚本使用SmtpClient类发送EMAIL。
<%@ page import="sun.net.smtp.SmtpClient, java.io.*" %>
<%
String from="ybwen@sina.com";
String to="hewenjun@yeah.net, lei@who.com.cn";
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("Im in genius.com");
message.println();
client.closeServer();
}
catch (IOException e){
System.out.println("ERROR SENDING EMAIL:"+e);
}
%>
14、在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();
}
}
}
15、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(...);
// 如此等等
%>
16、当我使用一个结果集时,如何防止字段为"null"的字域显示在我的HTML输入文本域中?
可以定义一个简单的函数来达到目的,如下:
<%!
String blanknull(String s) {
return (s == null) ? "" : s;
}
%>
然后在JSP的FORM中,可以这样使用
<input type="text" name="shoesize" value="<%=blanknull(shoesize)%>">
17、如何中SERVLET或JSP下载一个文件(如:binary,text,executable)?
现提供两个解决方案:
A:使用HTTP,
B:在Servlet中,通过设置ContentType和使用java.io包的Stream等类可作到.例如:
response.setContentType("application/x-msword");
然后想输出缓冲中写一些东东即可。
18、使用useBean标志初始化BEAN时如何接受初始化参数
使用如下两标签即可:
<jsp:getProperty name="wenBean" property="someProperty"/>
<jsp:setProperty name="wenBean" property="someProperty" value="someValue"/>
19、使用JSP如何获得客户浏览器的信息?
使用request.getHeader(String)即可
把此文章收藏到: