物件導向程式設計

 

 

第十章、JSP/Servlet開發

 

 


授課教師:陳慶瀚

WWW : http://www.miat.ee.isu.edu.tw/java

E-mail : pierre@isu.edu.tw   

 


3. 使用JSP:Request物件

3.1 擷取URL資訊

Some reasons you may need to look at the URL information:

  • form submission
  • selecting sections of a manual
  • displaying different stories on a news site
  • displaying comments on a discussion group
  • sort preferences for the discussion site
  • search results

RequestURI

getRequestURI() returns the full path, excluding any query string.

ServletPath

getServletPath() returns the URI prefix that matches the servlet. In the case of a JSP, it will return everything up to the *.jsp.

The servlet path is useful for servlets like JSP, XTP, or SSI that read and transform files.

PathInfo

getPathInfo() returns everything after the ServletPath.

A discussion board servlet could use PathInfo to select stories and comments.

QueryString

getQueryString() returns the query string, everything after the '?'

Often, query strings are the result of form submissions but it's also useful for database-driven sites. For example, you might encode "story 15, comment 7" of a discussion as /comment.xtp?story=15&comment7.

http://localhost:8080/test/env.jsp/tail?a=b
env.jsp
<table>
<tr><td>URI         <td><%= request.getRequestURI() %>
<tr><td>ServletPath <td><%= request.getServletPath() %>
<tr><td>PathInfo    <td><%= request.getPathInfo() %>
<tr><td>QueryString <td><%= request.getQueryString() %>
<tr><td>a           <td><%= request.getParameter("a") %>
</table>
URI          /test/env.jsp/tail
ServletPath  /test/env.jsp
PathInfo     /tail
QueryString  a=b
a            b

3.2 擷取Form資訊

Forms are, of course, the most important way of getting information from the customer of a web site. In this section, we'll just create a simple color survey and print the results back to the user.

First, create the entry form. Our HTML form will send its answers to form.jsp for processing.

For this example, the name="name" and name="color" are very important. You will use these keys to extract the user's responses.

form.html

<form action="form.jsp" method="get">

<table>
<tr><td><b>Name</b>
    <td><input type="text" name="name">

<tr><td><b>Favorite color</b>
    <td><input type="text" name="color">
</table>

<input type="submit" value="Send">

</form>

Resin keeps the browser request information in the request object. The request object contains the environment variables you may be familiar with from CGI programming. For example, it has the browser type, any HTTP headers, the server name and the browser IP address.

You can get form values using request.getParameter object.

The following JSP script will extract the form values and print them right back to the user.

form.jsp
Name: <%= request.getParameter("name") %> <br>
Color: <%= request.getParameter("color") %> 


3.3 設計檔案上傳功能

Multipart forms let browsers upload files to the website. They also have better handling for internationalization.

Default form handling uses the application/x-www-form-urlencoded content type. Multipart forms use the multipart/form-data encoding.

form.html

<form action="multipart.jsp" method="POST"
      enctype="multipart/form-data">

<input type="file" name="file"><br>

<input type="submit">
</form>

Resin's file uploading stores the uploaded file in a temporary directory. A servlet can get the filename for the temporary file by retrieving the form parameter. In the example, getParameter("file") gets the filename.

Servlets will generally copy the contents of the file to its permanent storage, whether stored on disk or in a database.

multipart.jsp
<%
String fileName = request.getParameter("file");
FileInputStream is = new FileInputStream(fileName);

int ch;
while ((ch = is.read()) >= 0)
  out.print((char) ch);

is.close();
%>

User Comments
Why it can't work? by anonymous on Tue, 02 Oct 2001 21:19:50 -0700 (PDT)
I try this program on my computer, but getParameter(" file") retun null.

My computer is Windows 2000 Pro(Simplified Chinese version) with SP2.

I find a free bean jspSmart from www.jspsmart.com. It does work! Does another bean need?

or some wrong with me?

It needs to be enabled by anonymous on Wed, 03 Oct 2001 05:51:55 -0700 (PDT)
you need to make sure you add <multipart-form upload-max='-1'/> to your web.xml or resin.conf for your web application to turn on multipart processing.
Unicode Support Problem by anonymous on Tue, 09 Oct 2001 04:02:08 -0700 (PDT)
If I the form and response file are encoded by UTF-8, and the file name include Chinese char, the name got is wrong, and should encode by program as below.

<%

String fileName = request.getParameter("FILE.filename");

String s = fileName.substring(1 + fileName.lastIndexOf("\\"));

s = new String(s.getBytes("ISO-8859-1"), "UTF-8");

// real name of file uploaded

out.println("
" + s);

%>

upload files to database by anonymous on Tue, 20 Nov 2001 23:26:40 -0800 (PST)
I am trying to use upload's classes from www.jspsmart.com.Which directory should i put in my tomcat 3.2.3? When I run it, it state pakage jspsmartupload not imported.
use resin by anonymous on Fri, 30 Nov 2001 09:56:11 -0800 (PST)
This is Caucho's site - they make a web server/servlet container called Resin. Sounds like your using Tomcat and are asking your question on the wrong site.
original Filename by anonymous on Fri, 30 Nov 2001 12:26:24 -0800 (PST)

Once the form is posted how can I get the original file name? On the server side a request.getParameter("form_input_name") returns the name of the temporary file on the server. I need the original name of the file on the client side. Anyone know how to get this?
mimetype of uploaded file by anonymous on Fri, 30 Nov 2001 13:00:36 -0800 (PST)
As per the previous request for the original filename, is there a mechanism for retrieving the mimetype of the file? The filename and content-type of the file are in the request right after the boundary. Are they accessable somewhere?
filename and mime-type by anonymous on Fri, 30 Nov 2001 15:50:30 -0800 (PST)
Found this after I posted the question about the filename, and the answer to the mime-type was there too. From the reson docs:

For an uploaded file with a form name of foo, the parameter value contains the path name to a temporary file containing the uploaded file. foo.filename contains the uploaded filename, and foo.content-type contains the content-type of the uploaded file.

 

 


3.4 擷取Browser資訊

Sophisticated servlets can use browser headers to tailor the returned page to the browser. For example, a high-quality site can detect a Palm Pilot browser and simplify its site design to match the browser capabilities.

Each browser request sends headers along with the URL. The headers include the browser type (User-Agent) and language preferences (Accept-Language and Accept-Charset). The full list is in the official HTTP/1.1 spec, but those three are the most important.

Servlet and JSPs grab headers with request.getHeader.

The following, like env.jsp in the examples, gets all the headers and prints them. Little "snoop" servlets like this are useful to see what headers browsers are sending.

test.HeaderServlet.java
package test;

import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class HeaderServlet extends HttpServlet {
  public void doGet(HttpServletRequest request,
                    HttpServletResponse response)
    throws IOException, ServletException
  {
    PrintWriter out = response.getWriter();

    out.println("<table>");

    Enumeration e = request.getHeaderNames();
    while (e.hasMoreElements()) {
      String name = (String) e.nextElement();

      out.println("<tr><td>" + name);
      out.println("<td>" + request.getHeader(name));
    }

    out.println("</table>");
  }
}
Connection       Keep-Alive 
User-Agent       Mozilla/4.74 [en] (X11; U; Linux 2.4.0-test1 i686) 
Host             localhost:8080 
Accept           image/gif, image/jpeg, image/pjpeg, image/png, */* 
Accept-Encoding  gzip 
Accept-Language  en 
Accept-Charset   iso-8859-1,*,utf-8 
Cookie           JSESSIONID=7tXlVCaALedCHHkdXy 

 


 

物件導向程式設計

義守大學電機系 陳慶瀚

2002.1.9