Jsp Q & A set 1

Source: Internet
Author: User

Author: ybwen

How to mix Jsp and SSI # include?
In JSP, you can use the following method to include pure HTML:

In JSP, how does one perform browser redirection?
Use the following method: response. sendRedirect ("http://ybwen.home.chinaren.com/index.html ");
The http header attribute can also be physically changed as follows:
<%
Response. setStatus (HttpServletResponse. SC _MOVED_PERMANENTLY );
String newLocn = "/newpath/index.html ";
Response. setHeader ("Location", newLocn );
%>


How can I prevent the output in JSP or SERVLET from being stored in the CACHE by BROWSER?
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
%>


In JSP, how do I set cookies?
COOKIE is sent as part of the http header. You can set it as follows:
<%
Cookie mycookie = new Cookie ("aName", "aValue ");
Response. addCookie (mycookie );
%>


In JSP, how does one delete a COOKIE?
<%
Cookie killMyCookie = new Cookie ("mycookie", null );
KillMyCookie. setMaxAge (0 );
KillMyCookie. setPath ("/");
Response. addCookie (killMyCookie );
%>


How to stop JSP execution during JSP request processing
For example:
<%
If (request. getParameter ("wen ")! = Null ){
// Do something
} Else {
Return;
}
%>


How to define methods in JSP
You can define methods, but you cannot directly access the built-in JSP objects, but pass through the parameter method. 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) %>


If the BROWSER has disabled COOKIES, how can I enable SESSION in JSP to track them?
Use the URL to rewrite it, as shown below:
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 ());
%>


Can I send an EMAIL in JSP?
You can use SUN's dedicated package: sun.net. smtp package. The following script uses the SmtpClient class to send an 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 ();
PrintStream message = client. startMessage ();
Message. println ("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 );
}
%>


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 );
}

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 ();
}
}
}


How to communicate with JSP and APPLET
How does JSP communicate with EJB SessionBean?
The following code snippet is a good example.
<% @ Page import = "javax. naming. *, javax. rmi. PortableRemoteObject,
Foo. AccountHome, foo. Account "%>
<%!
// Define a global reference to the SessionBeanHome interface instance
AccountHome accHome = null;

Public void jspInit (){
// Obtain the 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 the Remote Method
Acct. doWhatever (...);
// So on
%>


When I use a result set, how do I prevent the field "null" from being displayed in my HTML input text field?
A simple function can be defined as follows:
<%!
String blanknull (String s ){
Return (s = null )? "": S;
}
%>

Then in the FORM of JSP, you can use
<Input type = "text" name = "shoesize" value = "<% = blanknull (shoesize) %>">


How can I download an object (such as binary, text, and executable) from a SERVLET or JSP )?
Two solutions are available:
A: Use HTTP, as shown in figure
Click to download the online dinosaur image (this address is false)

B: In Servlet, you can set ContentType and use the Stream class of java. io package. For example:
Response. setContentType ("application/x-msword ");
Then you can write something in the output buffer.

How to accept initialization parameters when using useBean flag to initialize beans
Use the following two tags:
<Jsp: getProperty name = "wenBean" property = "someProperty"/>
<Jsp: setProperty name = "wenBean" property = "someProperty" value = "someValue"/>
Jsp q & A set II

Author: ybwen

How can I obtain information about the customer's browser Using JSP?
Use request. getHeader (String ).


Can I call JSP like a subroutine?
Of course, you can use <jsp: include page = "relativeURL" flush = "true"/>


After I recompile a CLASS used by my JSP, why does the JVM continue to use my old CLASS?


What is the difference between <% @ include file = "abc. jsp" %> and <jsp: include page = "abc. jsp"/>?
The first is static, and the other is dynamic.


What are the disadvantages of JSP?
1. Debugging JAVA programs is not good.
2. Because most servlet engines do not support connection pooling
3. No Servlet Engine Standard
4. Interaction between JSP and other scripting languages


Can JSP be recursively called?
Yes, of course. For example, if you submit a form to this page


How to internationalize JSP?
Provide resource bundles attribute files for various versions.

In JSP, how do I write text files?
Use a PrintWriter object, such:
<% @ 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 ());
}
%>


How to include absolute path files in JSP?
Use URLConnection.


Can session objects be shared between servlets and JSP?
Of course,
HttpSession session = request. getSession (true );
Session. putValue ("variable", "value ");


Can JavaScript variables be copied to JSP sessions?


How do I set the cookie to expire after a certain time?
Use Cookie. setMaxAge (int)


How to obtain the current number of sessions?
You can use HttpSessionBindingListeners for tracking.


Can I set some code to run on all my JSP files? If yes, can it be shared?
Of course, you can define an alias for your JSP file:/jsp/= ybwen. genius. myPreprocessingServlet. Files prefixed with/jsp/can use


If multiple clients request a JSP page at the same time, is synchronization possible?
What are the advantages of using beanName in jsp: useBean syntax?
BeanName uses Beans. instantiate () to initialize Bean


When I use <jsp: forward>, the address bar of the browser does not change?
Use response. sendRedirect ("newURL ")


How to convert JSP 0.9 files to JSP1.1?
You can use sed/awk.


Can JSP be used to set the focus of the input field in html form, without JavaScript?
No way


What is the best way to connect to the buffer pool Using JSP?
1. Use JDBC2. Driver with this service in 0
2.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.