ibm-information-center/dist/eclipse/plugins/i5OS.ic.rzatz_5.4.0.1/51/program/servres.htm

70 lines
2.8 KiB
HTML
Raw Normal View History

2024-04-02 14:02:31 +00:00
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
<head>
<META http-equiv="Content-Type" content="text/html; charset=utf-8">
<LINK rel="stylesheet" type="text/css" href="../../../rzahg/ic.css">
<title>Create the HTTP response</title>
</head>
<BODY>
<!-- Java sync-link -->
<SCRIPT LANGUAGE="Javascript" SRC="../../../rzahg/synch.js" TYPE="text/javascript"></SCRIPT>
<h6><A NAME="servres"></A>Create the HTTP response</h6>
<p>After the servlet request code, add the response code (in black text below):</p>
<pre>import java.io.*;
import java.util.*;
import javax.servlet.*;
import javax.servlet.http.*;
public class ServletSample extends HttpServlet
{
public void doGet (HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException
{
Enumeration keys;
String key;
String myName = &quot;&quot;;
keys = request.getParameterNames();
while (keys.hasMoreElements())
{
key = (String) keys.nextElement();
if (key.equalsIgnoreCase(&quot;myName&quot;)) myName = request.getParameter(key);
}
System.out.println(&quot;Name = &quot;);
if (myName == &quot;&quot;) myName = &quot;Hello&quot;;
response.setContentType(&quot;text/html&quot;);
response.setHeader(&quot;Pragma&quot;, &quot;No-cache&quot;);
response.setDateHeader(&quot;Expires&quot;, 0);
response.setHeader(&quot;Cache-Control&quot;, &quot;no-cache&quot;);
PrintWriter out = response.getWriter();
out.println(&quot;&lt;html&gt;&quot;);
out.println(&quot;&lt;head&gt;&lt;title&gt;Just a basic servlet&lt;/title&gt;&lt;/head&gt;&quot;);
out.println(&quot;&lt;body&gt;&quot;);
out.println(&quot;&lt;h1&gt;Just a basic servlet&lt;/h1&gt;&quot;);
out.println (&quot;&lt;p&gt;&quot; + myName + &quot;, this is a very basic servlet.&quot;);
out.println(&quot;&lt;/body&gt;&lt;/html&gt;&quot;);
out.flush();
}
}
</pre>
<p>The HttpServletResponse object generates a response to return to the requesting client. Its methods allow you to set the response header and the response body.</p>
<p>The first line of the Response header (response.setContentType(&quot;text/html&quot;);) identifies the MIME type of the response. The following three lines are often placed in servlet code to prevent Web browsers and proxy servers from caching dynamically-generated Web pages. If you want your dynamic Web page to be cached, remove these three lines of code.</p>
<p>The response object also has the getWriter() method to return a PrintWriter object. The print() and println() methods of the PrintWriter object write the servlet response back to the client.</p>
</body>
</html>