Servlet-Snippets

Eine Snippet-Sammlung für Servlets.

Links:

JSP-Basics

Weitere Infos: http://www.torsten-horn.de/techdocs/jsp-grundlagen.htm

Syntax einer typischen JSP-Seite:

<%@page import="java.io.*, java.util.*"%>
<%@page contentType="text/html; charset=utf-8"%>
<%!
// Klassenweite Deklarationen
private int myMember = 0;

private String helperMethod() {
  return "helper stuff";
}
%>
<html>
<body>

<!-- HTML-Kommentar -->
<%-- JSP-Kommentar --%>

<%@ include file="some/path/file.jsp" %>

Hello <%= request.getParameter("name") %>

<%
// Code-Block
if ("true".equals(request.getParameter("debug"))) {
  %>
  <div>Debug-Info</div>
  <%
}
%>
</html>

Lokale Variablen in einer JSP:

Variable Typ
out PrintWriter
request HttpServletRequest
response HttpServletResponse
config ServletConfig
session HttpSession
application ServletContext - Shortcut zu getServletConfig().getContext()
page this (ist eigentlich unnötig)

Die wichtigsten Methoden:

Object attribute = request.getAttribute(String name);
Enumeration enum = request.getParameterNames();
String value = request.getParameter(String name);
String[] values = request.getParameterValues(String name);
String host = request.getRemoteHost();

out.println("Hallo !");
out.flush();

String id = session.getId();
Object value = session.getAttribute(String name);
session.setAttribute(String name, Object value);

String value = config.getInitParameter(String name);

application.log(String message);
application.log(String message, Throwable thr);
String type = application.getMimeType(String file);
String realPath = application.getRealPath(String virtualPath);
InputStream stream = application.getResourceAsStream(String path);
Object value = application.getAttribute(String name);
application.setAttribute(String name, Object value);

Unit-Testing von Servlets

Abhängigkeit in pom.xml eintragen:

<dependency>
  <groupId>org.mortbay.jetty</groupId>
  <artifactId>jetty-servlet-tester</artifactId>
  <version>6.1.16</version>
  <scope>test</scope>
</dependency>

Test schreiben:

public class MyTest extends TestCase {
  public void testStuff() throws IOException {
    // Execute the test
    HashMap<String, String> initParams = new HashMap<String, String>();
    initParams.put("my-param", "my-value");

    ServletTester tester = new ServletTester();
    tester.getContext().setInitParams(initParams);
    tester.addServlet(MyServlet.class, "/servlet-path/*");
    tester.start();

    // Prepare request and response helper
    HttpTester request = new HttpTester();
    HttpTester response = new HttpTester();
    request.setMethod("GET");
    request.setVersion("HTTP/1.0");

    // Execute the test
    request.setURI("/servlet-path?bla=blubb");
    response.parse(tester.getResponses(request.generate()));
    assertEquals(200, response.getStatus());
    assertEquals("Expected response", response.getContent());

    // Stop the servlet tester
    tester.stop();
  }
}

Pfade im HttpServletRequest

In der Klasse HttpServletRequest gibt es einige Getter für Pfad-Informationen.

Angenommen, wir haben einen Tomcat im Verzeichnis /usr/share/tomcat6/ auf Port 8080 laufen und darauf die Web-Applikation my-webapp.war deployed. Die Web-Applikation enthält ein Servlet, das in der web.xml auf das URL-Pattern /servlet-path/* gemappt wurde.

Anfrage: http://localhost:8080/my-webapp/servlet-path?test=otto:

Methode Rückgabewert
getScheme http
getRequestURI /my-webapp/servlet-path
getContextPath /my-webapp
getServletPath /servlet-path
getPathInfo null
getPathTranslated null
getQueryString test=otto

Anfrage: http://localhost:8080/my-webapp/servlet-path/:

Methode Rückgabewert
getScheme http
getRequestURI /my-webapp/servlet-path/
getContextPath /my-webapp
getServletPath /servlet-path
getPathInfo /
getPathTranslated /usr/share/tomcat6/webapp
getQueryString null

Anfrage: http://localhost:8080/my-webapp/servlet-path/some/path?test=otto:

Methode Rückgabewert
getScheme http
getRequestURI /my-webapp/servlet-path/some/path
getContextPath /my-webapp
getServletPath /servlet-path
getPathInfo /some/path
getPathTranslated /usr/share/tomcat6/webapp/some/path
getQueryString test=otto