⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 servlet.xtp

📁 RESIN 3.2 最新源码
💻 XTP
📖 第 1 页 / 共 2 页
字号:
<document>  <header>    <product>resin</product>    <title>Servlets</title>    <type>contents</type>    <description>      <p>Servlets are Java classes which service HTTP requests.  The only        requirement for writing a servlet is that it implements the        javax.servlet.Servlet interface.</p>      <p>Servlets are loaded from the classpath like all Java classes.        Normally, users put servlets in <var>WEB-INF/classes</var> so Resin will          automatically reload them when they change.</p>            <p><a href="jsp.xtp">JSP</a> pages are implemented as        Servlets, and tend to be more efficient for pages with lots of text.</p>    </description>  </header>  <body><localtoc/><s1 title="Configuration"><s2 title="Configuring the web.xml"><p>The following is a complete working web.xml to run this example.</p><p>The <var>servlet-mapping</var> tells Resin that the URL<var>/hello</var> should invoke the <var>hello-world</var> servlet.</p><p>The <var>servlet</var> tells Resin that <var>hello-world</var> uses the<var>test.HelloWorld</var> class and that the value of the <var>greeting</var>init parameter is <var>Hello World</var>.</p><example title="Example: WEB-INF/resin-web.xml">&lt;web-app xmlns="http://caucho.com/ns/resin"&gt;  &lt;servlet servlet-name='hello-world'           servlet-class='test.HelloWorld'&gt;    &lt;init-param greeting='Hello, World'/&gt;  &lt;/servlet&gt;  &lt;servlet-mapping url-pattern='/hello'                   servlet-name='hello-world'/&gt;&lt;/web-app&gt;</example><p>The Java code, <var>HelloWorld.java</var> belongs in</p><def>$app-dir/WEB-INF/classes/test/HelloWorld.java</def><p>Or, if you're compiling the servlet yourself, the class file belongs in</p><def>$app-dir/WEB-INF/classes/test/HelloWorld.class</def><p>Following is the actual servlet code.  It just prints a trivialHTML page filled with the greeting specified in the web.xml.</p><p><var>init()</var> and <var>destroy()</var> are included mostly forillustration.  Resin will call <var>init()</var> when it starts the servletand <var>destroy</var> before Resin destroys it.</p><example>package test;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class HelloWorld extends HttpServlet {  private String greeting;  public void init()    throws ServletException  {    greeting = getInitParameter("greeting");  }  public void doGet(HttpServletRequest request,                    HttpServletResponse response)    throws ServletException, IOException  {    PrintWriter out = response.getWriter();    out.println("&lt;title&gt;" + greeting + "&lt;/title&gt;");    out.println("&lt;h1&gt;" + greeting + "&lt;/h1&gt;");  }    public void destroy()  {    // nothing to do  }}</example></s2><s2 title="Servlet Example for JSP Programmers"><p>Because Resin compiles JSP pages into servlets, programmers familiarwith JSP can start writing servlets fairly easily.  The following templatecan be used to see how to write a servlet for someone familiar with JSP.</p><example>package test;import java.io.*;import javax.servlet.*;import javax.servlet.http.*;public class HelloWorld extends HttpServlet {  public void service(HttpServletRequest request,                      HttpServletResponse response)    throws ServletException, IOException  {    PrintWriter out = response.getWriter();    ServletContext application = getServletContext();    HttpSession session = request.getSession();    try {      // <var>code goes here</var>      // The equivalent of jsp:include:      // request.getRequestDispatcher("/inc.jsp").include(request, response);    } catch (ServletException e) {      throw e;    } catch (Exception e) {      throw new ServletException(e);    }  }}</example></s2><s2 title="Using Databases from a Servlet"><p>The following is a sample design pattern for getting new databaseconnections.  The <var>try ... finally</var> block is very important.  Withoutthe close in the finally block, Resin's database pool can loose connections.</p><p>Configuring the database is described in the<a href="config-database.xtp">database configuration</a> page.</p><example title="TestDatabase.java">package test;import java.io.*;import java.sql.*;import javax.servlet.*;import javax.servlet.http.*;import javax.naming.*;import javax.sql.*;public class TestDatabase extends HttpServlet {  DataSource pool;  public void init()    throws ServletException  {    try {      Context env = (Context) new InitialContext().lookup("java:comp/env");      pool = (DataSource) env.lookup("jdbc/test");      if (pool == null)        throw new ServletException("`jdbc/test' is an unknown DataSource");    } catch (NamingException e) {      throw new ServletException(e);    }  }  public void doGet(HttpServletRequest request,                    HttpServletResponse response)    throws IOException, ServletException  {    response.setContentType("text/html");    PrintWriter out = response.getWriter();    Connection conn = null;    try {      conn = pool.getConnection();      // <var>code for the servlet using the database goes here</var>      rs.close();      stmt.close();    } catch (SQLException e) {      throw new ServletException(e);    } finally {      try {        if (conn != null)          conn.close();      } catch (SQLException e) {      }    }  }}</example></s2></s1><s1 title="Servlet Configuration"><s2 title="init" version="Resin 2.1.3" type="defun"><p>Configures servlets using bean-style initialization.Each entry in an &lt;init&gt; tag will configure a <code>setFoo</code>method in a Servlet. JSP EL expressions are allowed.</p><p>The <code>init(config)</code> method is called afterall the bean setters are called.</p><example title="Bean-style Configuration">&lt;web-app xmlns="http://caucho.com/ns/resin">&lt;servlet servlet-name='test.HelloWorld'&gt;  &lt;init&gt;    &lt;greeting&gt;Hello, ${host.url}&lt;/greeting&gt;  &lt;/init&gt;&lt;/servlet&gt;&lt;/web-app></example><example title="HelloWorld bean">public HelloWorld extends GenericServlet {  private String _greeting;  public void setGreeting(String greeting)  {    _greeting = greeting;  }  public void service(ServletRequest req,                      ServletResponse res)    throws IOException, ServletException  {    PrintWriter out = res.getWriter();    out.println("Greeting: " + _greeting);  }}</example></s2><s2 title="init-param" type="defun"><p>Initializes servlet variables. <code>servlet-param</code>defines initial values for <code>getServletConfig().getInitParameter("foo")</code>.</p><p>The full servlet 2.2 syntax is supported and allows a simple shortcut.</p><example>&lt;web-app id='/'&gt;&lt;servlet servlet-name='test.HelloWorld'&gt;  &lt;init-param foo='bar'/&gt;  &lt;init-param&gt;    &lt;param-name&gt;baz&lt;/param-name&gt;    &lt;param-value&gt;value&lt;/param-value&gt;  &lt;/init-param&gt;&lt;/servlet&gt;&lt;/web-app&gt;</example></s2><s2 title="load-on-startup" type="defun"><p>If present, starts the servlet when the server starts.</p><example>&lt;web-app id='/'&gt;&lt;servlet servlet-name='hello'         servlet-class='test.HelloWorld'&gt;  &lt;load-on-startup/&gt;&lt;/servlet&gt;&lt;/web-app&gt;</example></s2><s2 title="run-at" version="Resin 1.1" type="defun"><p>If present, calls the servlet's <var>service()</var> methodat the specified times.&lt;run-at&gt; lets servlet writers execute periodic tasks without worryingabout creating a new Thread.</p><p>The value is a list of 24-hour times when theservlet should be automatically executed.  To run the servlet every 6hours, you could use:</p><example>&lt;servlet servlet-name='test.HelloWorld'&gt;  &lt;run-at&gt;0:00, 6:00, 12:00, 18:00&lt;/run-at&gt;&lt;/servlet&gt;</example><p>If the hour is omitted, the servlet runs every hour at thespecified minute.  To run the server every 15 minutes, you could use:</p><example>&lt;servlet servlet-name='test.HelloWorld'&gt;  &lt;run-at&gt;:00, :15, :30, :45&lt;/run-at&gt;&lt;/servlet&gt;</example></s2><s2 title="servlet" type="defun"><p>Defines a servlet alias for later mapping.</p><deftable><tr><th>Attribute</th><th>Description</th></tr><tr><td>servlet-name</td><td>The servlet's name (alias)</td></tr><tr><td>servlet-class</td><td>The servlet's class (defaults to servlet-name)</td></tr><tr><td>init-param</td><td>Initialization parameters</td></tr><tr><td>load-on-startup</td><td>Initializes the servlet when the server starts.</td></tr><tr><td>run-at</td><td>Times to execute the servlet automatically</td></tr></deftable><p>The following example defines a servlet alias 'hello'</p><example>&lt;web-app id='/'&gt;&lt;servlet-mapping url-pattern='/hello.html'                 servlet-name='hello'/&gt;&lt;servlet servlet-name='hello'         servlet-class='test.HelloWorld'&gt;  &lt;init-param title='Hello, World'/&gt;&lt;/servlet&gt;&lt;servlet servlet-name='cron'         servlet-class='test.DailyChores'&gt;  &lt;run-at&gt;3:00&lt;/run-at&gt;&lt;/servlet&gt;&lt;/web-app&gt;</example></s2><s2 title="servlet-class" type="defun"><p>Class of the servlet.  The CLASSPATH for servlets includesthe WEB-INF/classes directory and all jars in the WEB-INF/lib directory.</p></s2><s2 title="servlet-name" type="defun"><p>Alias of the servlet, uniquely naming a servlet configuration.Several &lt;servlet&gt; configurations might configure the sameservlet class with different &lt;init-param&gt; values.  Each willhave a separate servlet-name.</p><example title="Multiple Servlets">&lt;web-app&gt;  &lt;servlet servlet-name='foo-a'&gt;    &lt;servlet-class&gt;test.FooServlet&lt;/servlet-class&gt;    &lt;init-param name='foo-a sample'/&gt;  &lt;/servlet&gt;  &lt;servlet servlet-name='foo-b'&gt;    &lt;servlet-class&gt;test.FooServlet&lt;/servlet-class&gt;    &lt;init-param name='foo-b sample'/&gt;  &lt;/servlet&gt;&lt;/web-app&gt;</example></s2><s2 title="servlet-mapping" type="defun"><p>Maps from a URL to the servlet to execute.  The servlet-mappinghas a url-pattern to match the URL and a servlet-name to match theconfigured servlet.</p><example title="typical servlet-mapping">&lt;servlet&gt;  &lt;servlet-name&gt;hello&lt;/servlet-name&gt;  &lt;servlet-class&gt;test.HelloServlet&lt;/servlet-class&gt;&lt;/servlet&gt;&lt;servlet-mapping&gt;  &lt;url-pattern&gt;/hello/*&lt;/url-pattern&gt;  &lt;servlet-name&gt;hello&lt;/servlet-name&gt;&lt;/servlet-mapping&gt;</example><p>Resin allows for a shortcut combining the servlet andthe servlet mapping:</p><example title="shortcut servlet-mapping">&lt;servlet-mapping url-pattern="/hello/*"                 servlet-class="test.HelloServlet"/&gt;</example></s2><s2 title="url-pattern" version="Servlet 2.2" type="defun"><p>Matches a set of URLs for servlet-mapping.</p><deftable><tr><th width="25%">Pattern</th><th>Description</th></tr><tr><td>/foo/bar.html</td><td>Matches exactly the /foo/bar.html URL.</td></tr><tr><td>/foo/*</td><td>Matches /foo and any children</td></tr><tr><td>*.foo</td><td>Matches any URL with a .foo extension</td></tr><tr><td>/</td><td>Replaces the default servlet.</td></tr></deftable><p><var>/</var> defines a default handler and <var>/*</var> defines a prefix handler.<var>/*</var> will override extension handlers like <var>*.foo</var>. <var>/</var>will only be used if no other pattern matches.</p><p>No default.  Either url-pattern or url-regexp is required.</p></s2></s1><s1 title="ErrorStatusServlet"><p>Sends an HTTP error code and optionally an error message backto the client.</p>  <deftable-parameters><tr><td>status-code</td><td>the HTTP status code to send</td><td>404</td></tr><tr><td>message</td><td>the message to send</td><td>no message</td></tr></deftable-parameters><p>This servlet is particularily useful for blocking access to portions of yourweb-app that contain files not meant to be accessible to users. In thisexample, the default 404 (meaning "Not Found") is used as the errormessage; the user cannot even determine if the file they are trying to accessexists.</p><example title="Blocking access to files using the ErrorStatusServlet">&lt;web-app&gt;  &lt;servlet&gt;    &lt;servlet-name&gt;block-access&lt;/servlet-name&gt;    &lt;servlet-class&gt;com.caucho.servlets.ErrorStatusServlet&lt;/servlet-class&gt;  &lt;servlet&gt;  &lt;servlet-mapping&gt;    &lt;servlet-name&gt;block-access&lt;/servlet-name&gt;    &lt;url-pattern&gt;/config/*&lt;/url-pattern&gt;  &lt;/servlet-mapping&gt;  &lt;servlet-mapping&gt;    &lt;servlet-name&gt;block-access&lt;/servlet-name&gt;    &lt;url-pattern&gt;*.properties&lt;/url-pattern&gt;  &lt;/servlet-mapping&gt;  ...&lt;/web-app&gt;</example><p>See <a href="javadoc|com.caucho.servlets.ErrorStatusServlet|"/>.</p></s1><s1 title="LoadBalanceServlet"><p>Configures a front-end Resin instance to load-balance requests tobackend Resin instances.  Each LoadBalanceServlet instance willdistribute the requests to a configured cluster.</p><p>The urls that get load balanced are the ones that are mapped to the LoadBalancedServlet, using the usual servlet-mapping. </p><p>LoadBalanceServlet supports sticky-sessions. If the request already has asession, the backend server matching that session will be used.  Otherwise, theleast busy backend server will be used as counted bynumber of active requests.  If several backend servers areequally busy, the selection uses a round-robin to distribute the load.</p><deftable-parameters><tr><td>cluster-id</td><td>the cluster that gets the matching requests</td><td>required</td></tr><tr><td>sticky-sessions</td><td>whether or not sessions should be sticky</td><td>true</td></tr><tr><td>strategy</td><td>the load balancing strategy, `round-robin' or `least-connection'</td><td>least-connection</td></tr></deftable-parameters>

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -