| ||||||||||||||||||||||||||||||||||
Resin 3.1 Documentation Examples Changes Overview Installation Configuration Quercus SOA/IoC JSP Servlets and Filters Admin (JMX) EJB Amber Security Performance Hessian XML and XSLT Third-party Troubleshooting/FAQ Servlets Servlet Lib WebDAV run-at Filters Filter Lib FAQ |
Servlets are Java classes which service HTTP requests. The only requirement for writing a servlet is that it implements the javax.servlet.Servlet interface. Servlets are loaded from the classpath like all Java classes. Normally, users put servlets in so Resin will automatically reload them when they change.JSP pages are implemented as Servlets, and tend to be more efficient for pages with lots of text. ExamplesConfiguring the web.xmlThe following is a complete working web.xml to run this example. The tells Resin that the URL should invoke the servlet.The tells Resin that uses the class and that the value of the init parameter is .<web-app> <servlet-mapping url-pattern='/hello' servlet-name='hello-world'/> <servlet servlet-name='hello-world' servlet-class='test.HelloWorld'> <init-param greeting='Hello, World'/> </web-app> The Java code, belongs in
Or, if you're compiling the servlet yourself, the class file belongs in
Following is the actual servlet code. It just prints a trivial HTML page filled with the greeting specified in the web.xml. and are included mostly for illustration. Resin will call when it starts the servlet and before Resin destroys it. 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("<title>" + greeting + "</title>"); out.println("<h1>" + greeting + "</h1>"); } public void destroy() { // nothing to do } } Servlet Example for JSP ProgrammersBecause Resin compiles JSP pages into servlets, programmers familiar with JSP can start writing servlets fairly easily. The following template can be used to see how to write a servlet for someone familiar with JSP.
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 {
//
// The equivalent of jsp:include:
// request.getRequestDispatcher("/inc.jsp").include(request, response);
} catch (ServletException e) {
throw e;
} catch (Exception e) {
throw new ServletException(e);
}
}
}
Using Databases from a ServletThe following is a sample design pattern for getting new database connections. The block is very important. Without the close in the finally block, Resin's database pool can loose connections.Configuring the database is described in the database configuration page.
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();
//
rs.close();
stmt.close();
} catch (SQLException e) {
throw new ServletException(e);
} finally {
try {
if (conn != null)
conn.close();
} catch (SQLException e) {
}
}
}
}
Servlet ConfigurationinitConfigures servlets using bean-style initialization.
Each entry in an <init> tag will configure a The <servlet servlet-name='test.HelloWorld'> <init> <greeting>Hello, ${host.url}</greeting> </init> </servlet> public HelloWorld extends GenericServlet { private String _greeting; public void setGreeting(String greeting) { _greeting = greetin; } public void service(ServletRequest req, ServletResponse res) throws IOException, ServletException { PrintWriter out = res.getWriter(); out.println("Greeting: " + _greeting); } } init-paramInitializes servlet variables. The full servlet 2.2 syntax is supported and allows a simple shortcut. <web-app id='/'> <servlet servlet-name='test.HelloWorld'> <init-param foo='bar'/> <init-param> <param-name>baz</param-name> <param-value>value</param-value> </init-param> </servlet> </web-app> load-on-startupIf present, starts the servlet when the server starts. <web-app id='/'> <servlet servlet-name='hello' servlet-class='test.HelloWorld'> <load-on-startup/> </servlet> </web-app> run-atIf present, calls the servlet's method at the specified times. <run-at> lets servlet writers execute periodic tasks without worrying about creating a new Thread.The value is a list of 24-hour times when the servlet should be automatically executed. To run the servlet every 6 hours, you could use: <servlet servlet-name='test.HelloWorld'> <run-at>0:00, 6:00, 12:00, 18:00</run-at> </servlet> If the hour is omitted, the servlet runs every hour at the specified minute. To run the server every 15 minutes, you could use: <servlet servlet-name='test.HelloWorld'> <run-at>:00, :15, :30, :45</run-at> </servlet> servletDefines a servlet alias for later mapping.
The following example defines a servlet alias 'hello' <web-app id='/'> <servlet-mapping url-pattern='/hello.html' servlet-name='hello'/> <servlet servlet-name='hello' servlet-class='test.HelloWorld'> <init-param title='Hello, World'/> </servlet> <servlet servlet-name='cron' servlet-class='test.DailyChores'> <run-at>3:00</run-at> </servlet> </web-app> servlet-classClass of the servlet. The CLASSPATH for servlets includes the WEB-INF/classes directory and all jars in the WEB-INF/lib directory. servlet-nameAlias of the servlet, uniquely naming a servlet configuration. Several <servlet> configurations might configure the same servlet class with different <init-param> values. Each will have a separate servlet-name. <web-app> <servlet servlet-name='foo-a'> <servlet-class>test.FooServlet</servlet-class> <init-param name='foo-a sample'/> </servlet> <servlet servlet-name='foo-b'> <servlet-class>test.FooServlet</servlet-class> <init-param name='foo-b sample'/> </servlet> </web-app> servlet-mappingMaps from a URL to the servlet to execute. The servlet-mapping has a url-pattern to match the URL and a servlet-name to match the configured servlet. <servlet> <servlet-name>hello</servlet-name> <servlet-class>test.HelloServlet</servlet-class> </servlet> <servlet-mapping> <url-pattern>/hello/*</url-pattern> <servlet-name>hello</servlet-name> </servlet-mapping> Resin allows for a shortcut combining the servlet and the servlet mapping: <servlet-mapping url-pattern="/hello/*" servlet-class="test.HelloServlet"/> url-patternMatches a set of URLs for servlet-mapping.
defines a default handler and defines a prefix handler. will override extension handlers like . will only be used if no other pattern matches. No default. Either url-pattern or url-regexp is required.
|