Answers to problems you may encounter in JSP
1. How to mix Jsp and SSI #include?
Pure HTML can be included in JSP as follows:
< !--#include file="data.inc"-- >
But if data.inc contains JSP CODE, we can use:
< <A href=" mailto:%@include">%@include</A > file="data.inc"% > </P>
2. How to execute a thread-safe JSP?
Just add the following command
< %@ page isThreadSafe="false" % > </P>
3. How does JSP process data in HTML FORM?
Just use the built-in request object, as follows:
<%
String item = request.getParameter("item");
int howMany = new Integer(request.getParameter("units")).intvalue();
% > </P>
4. How to include a static file in JSP?
Static inclusion is as follows: < %@ include file="copyright.html" % >
Dynamic inclusion is as follows: < jsp:include page="copyright.html" flush="true"/ > </P>
5. How to use comments in JSP?
There are four main methods:
1. < %-- and --% >
2. //
3. /**and**/
4. < !--and-- > </P>
6. How to perform browsing redirection in JSP?
Use the following method: response.sendRedirect(" <A href=" http://ybwen.home.chinaren.com/index.html">http://ybwen.home.chinaren.com/index.html</ A >");
You can also physically change the HTTP HEADER attribute, as follows:
<%
response.setStatus(HttpServletResponse.SC_MOVED_PERMANENTLY);
String newLocn="/newpath/index.html";
response.setHeader("Location",newLocn);
% > </P>
7. How to prevent the output in JSP or SERVLET from being saved in CACHE by BROWSER?
Just add the following script to the beginning of the JSP file:
<%
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
% > </P>
8. How to set COOKIE in JSP?
COOKIE is sent as part of the HTTP HEADER and can be set as follows:
<%
Cookie mycookie = new Cookie("aName","avalue");
response.addCookie(mycookie);
% > </P>
9. How to delete a COOKIE in JSP?
<%
Cookie killMyCookie = new Cookie("mycookie", null);
killMyCookie.setMaxAge(0);
killMyCookie.setPath("/");
response.addCookie(killMyCookie);
% > </P>
10. How to stop the execution of JSP during a JSP request processing is as follows:
<%
if (request.getParameter("wen") != null) {
//do something
} else {
return;
}
% > </P>
11. How to define methods in JSP You can define methods, but you cannot directly access the built-in objects of JSP, but pass them through parameter methods. as follows:
<%!
public String howBadFrom(HttpServletRequest req) {
HttpSession ses = req.getSession();
...
return req.getRemoteHost();
}
%>
<%
out.print("in general,lao lee is not baddie ");
%>
< %= howBadFrom(request) % > </P>
12. If BROWSER has turned off COOKIES, how can I open SESSION in JSP to track and use URL rewriting, as follows:
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 > </P>
hello2.jsp
< %@ page session="true" % >
<%
Integer i= (Integer )session.getvalue("num");
out.println("Num value in session is "+i.intvalue());
% > </P>
13. Can EMAIL be sent in JSP? You can use SUN's special package: sun.net.smtp package. The following script uses the SmtpClient class to send EMAIL.
< %@ page import="sun.net.smtp.SmtpClient, java.io.*" % >
<%
String from=" <A href=" mailto:[email protected]">[email protected]</A >";
String to=" <A href=" mailto:[email protected]">[email protected]</A >, <A href=" mailto:[email protected]">[email protected]. cn</A >";
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);
}
% > </P>
14. Can I call a JSP error page in SERVLET? Of course there is no problem. The following shows how to call a JSP error page in a SERVLET control logic unit.
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);
} </P>
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();
}
}
} </P>
15. How do JSP and APPLET communicate?
How JSP communicates with EJB SessionBean The following code snippet provides a good demonstration
< %@ page import="javax.naming.*, javax.rmi.PortableRemoteObject,
foo.AccountHome, foo.Account" % >
<%!
//Define a global reference to the SessionBeanHome interface instance
AccountHome accHome=null; </P>
public void jspInit() {
//Get Home interface instance
InitialContext cntxt = new InitialContext( );
Object ref= cntxt.lookup("java:comp/env/ejb/AccountEJB");
accHome = (AccountHome)PortableRemoteObject.narrow(ref,AccountHome.class);
}
%>
<%
//Instantiate SessionBean
Account acct = accHome.create();
//Call remote method
acct.doWhatever(...);
// and so on
% > </P>
16. How do I prevent fields with "null" fields from being displayed in my HTML input text fields when I use a result set?
A simple function can be defined to achieve the purpose, as follows:
<%!
String blanknull(String s) {
return (s == null) ? "" : s;
}
% > </P>
Then in the JSP FORM, you can use it like this
< input type="text" name="shoesize" value="< %=blanknull(shoesize)% >" > </P>
17. How to download a file (such as: binary, text, executable) in SERVLET or JSP?
Two solutions are now provided:
A: Use HTTP,
B: In Servlet, this can be done by setting the ContentType and using the Stream and other classes of the java.io package. For example:
response.setContentType("application/x-msword");
Then just write something in the output buffer. </P>
18. How to accept initialization parameters when initializing BEAN using the useBean flag? Just use the following two tags:
< jsp:getProperty name="wenBean" property="someProperty"/ >
< jsp:setProperty name="wenBean" property="someProperty" value="somevalue"/ > </P>
19. How to obtain customer browser information using JSP?
Just use request.getHeader(String)</P>
20. Can JSP be called like a subroutine?
Of course you can, use< jsp:include page="relativeURL" flush="true"/ > </P>
21. After I recompile a class used by my JSP, why does the JVM continue to use my old CLASS? </P>
What is the difference between < <A href=" mailto:%@include">%@include</A > file="abc.jsp"% > and < jsp:include page="abc.jsp"/ >?
The former one is static inclusion, while the latter one is dynamic inclusion</P>
22. Disadvantages of JSP?
1. There are no good things about debugging JAVA programs
2. Because most servlet engines do not support connection pooling
3. There is no standard for Servlet engines
4. Interaction between JSP and other scripting languages</P>
23. Can JSP make recursive calls?
Of course you can, if you submit the form to this page</P>
34. How to realize the internationalization of JSP?
Just provide resource bundles property files for various versions</P>
25. How to write text files in JSP?
Use PrintWriter object, such as:
< %@ page import="java.io.*" % >
<%
String str = "print me";
String nameOfTextFile = "/usr/anil/imp.txt";
try {
PrintWriter pw = new PrintWriter(new FileOutputStream(nameOfTextFile));
pw.println(str);
pw.close();
} catch(IOException e) {
out.println(e.getMessage());
}
% > </P>
26. How to include absolute path files in JSP?
Just use URLConnection. </P>
27. Can session objects be shared between servlets and JSP?
sure,
HttpSession session = request.getSession(true);
session.putvalue("variable","value"); </P>
28. Can Javascript variables be copied to JSP SESSION? </P>
29. How to set cookies to expire after a certain time?
Use Cookie.setMaxAge(int) </P>
30. How to get the current number of sessions?
You can use HttpSessionBindingListeners to track</P>
31. Can I set up some code to run on all my JSP files? If so, can it be shared?
Of course, you can define an alias for your JSP file: /jsp/=ybwen.genius.myPreprocessingServlet, and files prefixed with /jsp/ can be used</P>
32. For a JSP page, if multiple clients request it at the same time, is synchronization possible?
What are the benefits of using beanName in jsp:useBean syntax?
beanName uses Beans.instantiate() to initialize the Bean </P>
33. When I use < jsp:forward >, the address bar of the browser does not change?
Use response.sendRedirect("newURL") </P>
34. How to convert JSP 0.9 version files to JSP1.1?
Just use sed/awk</P>
35. Can you use JSP to set the focus of an input field in an HTML FORM without using Javascript?
No way</P>
36. What is the best way to connect to a database connection buffer pool using JSP?
1. Use the Driver with this service in JDBC2.0
2. Use the Application server that provides this service