Create and test a basic servlet

A basic servlet displays a message in PolicyCenter. You call this servlet in the context of PolicyCenter.

About this task

For simplicity, this basic servlet overrides the service method of the HttpServlet class. A production servlet can override other methods of this class, such as doGet or doPost.

Procedure

  1. Write a Gosu class that extends the class javax.servlet.http.HttpServlet.
    For this example, create a class in configuration > gsrc > mycompany > test > servlets. Make the name of the class TestingServlet.
  2. On the line before your class definition, add the @Servlet annotation to specify the servlet query path for this servlet:
    @Servlet( \ path : String ->path.matches("/test(/.*)?"))
    If the Servlet text appears red in the Studio editor, press Alt+Enter to import the gw.servlet.Servlet class.
  3. Override the service method to do your actual work. Your service method takes a servlet request object (HttpServletRequest) and a servlet response object (HttpServletResponse) as parameters.
    Press Alt+Insert in the Studio editor to select the correct method to override.
  4. In your service method, specify the work that the servlet request object performs.
    Warning: You must add an authentication system to your servlets to protect information and data integrity. If you have questions about server security, contact Guidewire Customer Support.
    In your service method, remove any template code and write an HTTP response using the servlet response object. The following simple response sets the content MIME type and the status of the response (OK):
    resp.ContentType = "text/plain"
    resp.setStatus(HttpServletResponse.SC_OK)

    To write output text or binary data, use the Writer property of the response object.

    resp.Writer.append("I am the page " + req.PathInfo)
  5. Register the servlet class in the following file:
    PolicyCenter/configuration/config/servlet/servlets.xml

    Add one <servlet> element that references the fully qualified name of your class.

    <servlets 
      xmlns="http://guidewire.com/servlet">
      <servlet 
        class="mycompany.test.servlets.TestingServlet"/>
    </servlets>
  6. Start the QuickStart server in Guidewire Studio.
    If the server is already running, stop and restart the server.
  7. Test the servlet at the URL:
    http://localhost:8180/pc/service/test

    The text "/test" in the URL is the part that matches the servlet query path. The TestingServlet class specifies that path in the @Servlet annotation. If necessary, change the port number and the server name to match your PolicyCenter application.

    The following text appears on the page:

    I am the page /test

What to do next

See also