Sunday, June 14, 2009

Using JSPs in Google App Engine

In the earlier post we output the HTML for our user interface directly from Javaservlet code .

For this tutorial we will use JSPs to implement the user interface . JSPs are part of the servlet standard. App Engine compiles JSP files in the application's WAR automatically, and maps them to URL paths.

We will enhance the hello world application to use the JSP to output the HTML .

Add new jsp file i.e index.jsp under war folder as shown below .

Add new java class HelloWorldAppServletUsingJSP under com.tutorials by right click on com.tutorials new-->class .directory structure is as shown below The code for the servlet is

package com.tutorials;
import java.io.IOException;
import javax.servlet.*;
import javax.servlet.http.*;

public class HelloWorldAppServletUsingJSP extends HttpServlet{
 public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {
  req.setAttribute("hellostring", "Hello From the JSP");
  RequestDispatcher dispatcher = getServletContext().getRequestDispatcher("/index.jsp");
  try {
   dispatcher.forward(req, resp);
  } catch (ServletException e) {
  // TODO Auto-generated catch block
   e.printStackTrace();
  }
 }

}

The simple code for the JSP is


<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>

<%= request.getAttribute("hellostring")%>

Modify the web.xml appropriately as shown below



 
  HelloWorldApp
  com.tutorials.HelloWorldAppServlet
 
 
  HelloWorldAppUsingJSP
  com.tutorials.HelloWorldAppServletUsingJSP
 
 
  HelloWorldApp
  /helloworldapp
 
 
  HelloWorldAppUsingJSP
  /helloworldappusingjsp
 
 
  index.html
 

and add entry in the index.html and run the server .

restart the server and access the application as shown below

Click on the HelloWorldAppUsingJSP link as shown below

2 comments:

  1. Hi this works fine on local host but error is there when i try to deploy it on app engine "Cannot get the System Java Compiler. Please use a JDK, not a JRE." , Please help.

    ReplyDelete
  2. Add -vm C:\Program Files\Java\jdk1.7.0\bin\javaw.exe to eclipse.ini file in your eclipse folder. Ensure -vm is on a separate line. Put this in the beginning of the file.

    ReplyDelete