Java Code Examples for javax.servlet.ServletOutputStream

Original Post: http://www.programcreek.com/java-api-examples/index.php?api=javax.servlet.ServletOutputStream

The following code examples are extracted from open source projects. You can click  up the examples you like. Your votes will be used in an intelligent system to get more and better code examples.

Code Example 1:

From project accumulo, under directory /server/src/main/java/org/apache/accumulo/server/monitor/servlets/.

Source DefaultServlet.java

private void getResource(HttpServletRequest req,HttpServletResponse resp) throws IOException {
  try {
    String path=req.getRequestURI();
    if (path.endsWith(".jpg"))     resp.setContentType("image/jpeg");
    if (path.endsWith(".html"))     resp.setContentType("text/html");
    path=path.substring(1);
    InputStream data=BasicServlet.class.getClassLoader().getResourceAsStream(path);
    ServletOutputStream out=resp.getOutputStream();
    try {
      if (data != null) {
        byte[] buffer=new byte[1024];
        int n;
        while ((n=data.read(buffer)) > 0)         out.write(buffer,0,n);
      }
 else {
        out.write(("could not get resource " + path + "").getBytes());
      }
    }
  finally {
      data.close();
    }
  }
 catch (  Throwable t) {
    log.error(t,t);
    throw new IOException(t);
  }
}

Code Example 2:

From project aether-core, under directory /aether-connector-asynchttpclient/src/test/java/org/eclipse/aether/connector/async/.

Source Generate.java

public boolean execute(HttpServletRequest request,HttpServletResponse response,Map<Object,Object> ctx) throws Exception {
  if ("GET".equals(request.getMethod())) {
    String path=request.getPathInfo();
    Long length=lengths.get(path);
    if (length != null) {
      response.setContentType("application/octet-stream");
      response.setContentLength(length.intValue());
      ServletOutputStream out=response.getOutputStream();
      for (int i=length.intValue(); i > 0; ) {
        int n=Math.min(i,bytes.length);
        i-=n;
        out.write(bytes,0,n);
      }
      out.close();
      return false;
    }
  }
  return true;
}

Code Example 3:

From project agileBase, under directory /gtpb_server/src/com/gtwm/pb/servlets/.

Source ReportDownloader.java

private void serveTemplate(HttpServletRequest request,HttpServletResponse response,BaseReportInfo report,String templateName) throws ServletException {
  String rinsedTemplateName=templateName.replaceAll("\\..*$","").replaceAll("\\W","") + ".vm";
  try {
    AuthManagerInfo authManager=this.databaseDefn.getAuthManager();
    if (!authManager.getAuthenticator().loggedInUserAllowedTo(request,PrivilegeType.MANAGE_TABLE,report.getParentTable())) {
      throw new DisallowedException(authManager.getLoggedInUser(request),PrivilegeType.MANAGE_TABLE,report.getParentTable());
    }
    CompanyInfo company=this.databaseDefn.getAuthManager().getCompanyForLoggedInUser(request);
    String pathString=this.databaseDefn.getDataManagement().getWebAppRoot() + "WEB-INF/templates/uploads/" + company.getInternalCompanyName()+ "/"+ report.getInternalReportName()+ "/"+ rinsedTemplateName;
    FileReader fr=new FileReader(pathString);
    BufferedReader br=new BufferedReader(fr);
    List<String> lines=new LinkedList<String>();
    String s;
    while ((s=br.readLine()) != null) {
      lines.add(s);
    }
    fr.close();
    response.setHeader("Content-disposition","attachment; filename=" + rinsedTemplateName);
    response.setHeader("Cache-Control","no-cache");
    response.setContentType("text/html");
    ServletOutputStream sos=response.getOutputStream();
    for (    String line : lines) {
      sos.println(line);
    }
    sos.flush();
  }
 catch (  AgileBaseException abex) {
    logger.error("Problem serving template: " + abex);
    throw new ServletException("Problem serving template: " + abex);
  }
catch (  IOException ioex) {
    logger.error("Problem serving template: " + ioex);
    throw new ServletException("Problem serving template: " + ioex);
  }
}

Code Example 4:

From project airlift, under directory /rack/src/test/java/io/airlift/rack/.

Source TestRackServlet.java

private String performRequest(String queryString,String path,final String postBody,String method) throws IOException, ServletException {
  HttpServletRequest request=mock(HttpServletRequest.class);
  when(request.getInputStream()).thenReturn(new ServletInputStream(){
    int index=0;
    @Override public int read() throws IOException {
      if (index < postBody.length())       return postBody.charAt(index++);
      return -1;
    }
    @Override public void reset(){
      index=0;
    }
  }
);
  when(request.getScheme()).thenReturn("http");
  when(request.getMethod()).thenReturn(method);
  when(request.getRequestURI()).thenReturn(path);
  when(request.getQueryString()).thenReturn(queryString);
  when(request.getServerName()).thenReturn("TestServer");
  when(request.getServerPort()).thenReturn(new Random().nextInt());
  when(request.getHeaderNames()).thenReturn(Collections.enumeration(ImmutableList.<String>of()));
  final StringBuilder outputBuilder=new StringBuilder();
  ServletOutputStream outputStream=new ServletOutputStream(){
    @Override public void write(    int i) throws IOException {
      outputBuilder.append(new String(new int[]{i},0,1));
    }
  }
;
  HttpServletResponse response=mock(HttpServletResponse.class);
  when(response.getOutputStream()).thenReturn(outputStream);
  servlet.service(request,response);
  return outputBuilder.toString();
}

Code Example 5:

From project akvo-flow, under directory /GAE/src/org/waterforpeople/mapping/app/web/.

Source TestHarnessServlet.java

private void writeImageToResponse(HttpServletResponse resp,String urlString){
  resp.setContentType("image/jpeg");
  try {
    ServletOutputStream out=resp.getOutputStream();
    URL url=new URL(urlString);
    InputStream in=url.openStream();
    byte[] buffer=new byte[2048];
    int size;
    while ((size=in.read(buffer,0,buffer.length)) != -1) {
      out.write(buffer,0,size);
    }
    in.close();
    out.flush();
  }
 catch (  Exception ex) {
  }
}

Code Example 6:

From project alfresco, under directory /root/modules/wcmquickstart/wcmquickstartwebsite/source/java/org/alfresco/wcm/client/view/.

Source StreamedAssetView.java

/** 
 * @see org.springframework.web.servlet.view.AbstractView#renderMergedOutputModel(java.util.Map,javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
 */
@Override protected void renderMergedOutputModel(Map<String,Object> model,HttpServletRequest request,HttpServletResponse response) throws Exception {
  boolean render=headerHelper.setHeaders(asset,attach,request,response);
  ServletOutputStream out=null;
  if (render) {
    ContentStream contentStream=null;
    if (renditionName != null) {
      Map<String,Rendition> renditions=asset.getRenditions();
      contentStream=renditions.get(renditionName);
    }
 else {
      contentStream=asset.getContentAsInputStream();
    }
    if (contentStream != null) {
      String mimeType=contentStream.getMimeType();
      response.setContentType(mimeType == null ? "application/octet-stream" : mimeType);
      response.setContentLength((int)contentStream.getLength());
      out=response.getOutputStream();
      contentStream.output(out);
    }
  }
}

Code Example 7:

From project alfresco, under directory /root/projects/remote-api/source/java/org/alfresco/repo/web/util/.

Source HttpRangeProcessor.java

/** 
 * Process a single range request.
 * @param res        HttpServletResponse
 * @param reader     ContentReader to retrieve content
 * @param range      Range header value
 * @param mimetype   Content mimetype
 * @return true if processed range, false otherwise
 */
private boolean processSingleRange(HttpServletResponse res,ContentReader reader,String range,String mimetype) throws IOException {
  boolean processedRange=false;
  Range r=null;
  try {
    r=Range.constructRange(range,mimetype,reader.getSize());
  }
 catch (  IllegalArgumentException err) {
    if (getLogger().isDebugEnabled())     getLogger().debug("Failed to parse range header - returning 416 status code: " + err.getMessage());
    res.setStatus(HttpServletResponse.SC_REQUESTED_RANGE_NOT_SATISFIABLE);
    res.setHeader(HEADER_CONTENT_RANGE,"\"*\"");
    res.getOutputStream().close();
    return true;
  }
  res.setStatus(HttpServletResponse.SC_PARTIAL_CONTENT);
  res.setContentType(mimetype);
  String contentRange="bytes " + Long.toString(r.start) + "-"+ Long.toString(r.end)+ "/"+ Long.toString(reader.getSize());
  res.setHeader(HEADER_CONTENT_RANGE,contentRange);
  res.setHeader(HEADER_CONTENT_LENGTH,Long.toString((r.end - r.start) + 1L));
  if (getLogger().isDebugEnabled())   getLogger().debug("Processing: Content-Range: " + contentRange);
  InputStream is=null;
  try {
    ServletOutputStream os=res.getOutputStream();
    is=reader.getContentInputStream();
    streamRangeBytes(r,is,os,0L);
    os.close();
    processedRange=true;
  }
 catch (  IOException err) {
    if (getLogger().isDebugEnabled())     getLogger().debug("Unable to process single range due to IO Exception: " + err.getMessage());
    throw err;
  }
 finally {
    if (is != null)     is.close();
  }
  return processedRange;
}

Code Example 8:

From project Alitheia-Core, under directory /alitheia/core/src/main/java/eu/sqooss/impl/service/webadmin/.

Source AdminServlet.java

/** 
 * Sends a resource (stored in the jar file) as a response. The mime-type is set to @p mimeType . The @p path to the resource should start with a / . Test cases: - null mimetype, null path, bad path, relative path, path not found, - null response TODO: How to simulate conditions that will cause IOException
 */
protected void sendResource(HttpServletResponse response,Pair<String,String> source) throws ServletException, IOException {
  InputStream istream=getClass().getResourceAsStream(source.first);
  if (istream == null) {
    throw new IOException("Path not found: " + source.first);
  }
  byte[] buffer=new byte[1024];
  int bytesRead=0;
  int totalBytes=0;
  response.setContentType(source.second);
  ServletOutputStream ostream=response.getOutputStream();
  while ((bytesRead=istream.read(buffer)) > 0) {
    ostream.write(buffer,0,bytesRead);
    totalBytes+=bytesRead;
  }
}

Code Example 9:

From project alkacon-oamp, under directory /com.alkacon.opencms.formgenerator/src/com/alkacon/opencms/formgenerator/dialog/.

Source CmsFormRfsFileDownloadDialog.java

/** 
 * Generates the output of the file.<p>
 * @throws IOException if something goes wrong 
 */
public void generateOutput() throws IOException {
  HttpServletResponse res=CmsFlexController.getController(getJsp().getRequest()).getTopResponse();
  File downloadFile=getDownloadFile(getParamResource());
  String mimeType=OpenCms.getResourceManager().getMimeType(downloadFile.getName(),null,"application/octet-stream");
  res.setContentType(mimeType);
  res.setHeader("Content-Disposition",new StringBuffer("attachment; filename=\"").append(downloadFile.getName()).append("\"").toString());
  res.setContentLength((int)downloadFile.length());
  ServletOutputStream outStream=res.getOutputStream();
  InputStream in=new BufferedInputStream(new FileInputStream(downloadFile));
  try {
    int bit=in.read();
    while ((bit) >= 0) {
      outStream.write(bit);
      bit=in.read();
    }
  }
  finally {
    if (outStream != null) {
      try {
        outStream.flush();
        outStream.close();
      }
 catch (      SocketException soe) {
      }
    }
    in.close();
  }
}

Code Example 10:

From project alkacon-oamp, under directory /com.alkacon.opencms.v8.formgenerator/src/com/alkacon/opencms/v8/formgenerator/dialog/.

Source CmsFormRfsFileDownloadDialog.java

/** 
 * Generates the output of the file.<p>
 * @throws IOException if something goes wrong 
 */
public void generateOutput() throws IOException {
  HttpServletResponse res=CmsFlexController.getController(getJsp().getRequest()).getTopResponse();
  File downloadFile=getDownloadFile(getParamResource());
  String mimeType=OpenCms.getResourceManager().getMimeType(downloadFile.getName(),null,"application/octet-stream");
  res.setContentType(mimeType);
  res.setHeader("Content-Disposition",new StringBuffer("attachment; filename=\"").append(downloadFile.getName()).append("\"").toString());
  res.setContentLength((int)downloadFile.length());
  ServletOutputStream outStream=res.getOutputStream();
  InputStream in=new BufferedInputStream(new FileInputStream(downloadFile));
  try {
    int bit=in.read();
    while ((bit) >= 0) {
      outStream.write(bit);
      bit=in.read();
    }
  }
  finally {
    if (outStream != null) {
      try {
        outStream.flush();
        outStream.close();
      }
 catch (      SocketException soe) {
      }
    }
    in.close();
  }
}

Code Example 11:

From project 3Dto2DApplet, under directory /src/java/nl/dannyarends/www/http/.

Source Webserver.java

public ServletOutputStream getOutputStream(){
synchronized (out) {
    if (rout == null) {
      if (pw != null)       throw new IllegalStateException("Already returned as a writer");
      rout=out;
    }
  }
  return rout;
}

Code Example 12:

From project accumulo, under directory /server/src/main/java/org/apache/accumulo/server/monitor/servlets/.

Source DefaultServlet.java

private void getDocResource(HttpServletRequest req,final HttpServletResponse resp) throws IOException {
  final String path=req.getRequestURI();
  if (path.endsWith(".html"))   resp.setContentType("text/html");
  final String aHome=System.getenv("ACCUMULO_HOME");
  PermissionCollection pc=new Permissions();
  pc.add(new FilePermission(aHome + "/docs/-","read"));
  AccessControlContext acc=new AccessControlContext(new ProtectionDomain[]{new ProtectionDomain(null,pc)});
  IOException e=AccessController.doPrivileged(new PrivilegedAction<IOException>(){
    @Override public IOException run(){
      InputStream data=null;
      try {
        File file=new File(aHome + path);
        data=new FileInputStream(file.getAbsolutePath());
        byte[] buffer=new byte[1024];
        int n;
        ServletOutputStream out=resp.getOutputStream();
        while ((n=data.read(buffer)) > 0)         out.write(buffer,0,n);
        return null;
      }
 catch (      IOException e) {
        return e;
      }
 finally {
        if (data != null) {
          try {
            data.close();
          }
 catch (          IOException ex) {
            log.error(ex,ex);
          }
        }
      }
    }
  }
,acc);
  if (e != null)   throw e;
}

Code Example 13:

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source DefaultServlet.java

/** 
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
 * @param resourceInfo The resource information
 * @param ostream The output stream to write to
 * @exception IOException if an input/output error occurs
 */
protected void copy(CacheEntry cacheEntry,InputStream is,ServletOutputStream ostream) throws IOException {
  IOException exception=null;
  InputStream resourceInputStream=null;
  if (cacheEntry.resource != null) {
    byte buffer[]=cacheEntry.resource.getContent();
    if (buffer != null) {
      ostream.write(buffer,0,buffer.length);
      return;
    }
    resourceInputStream=cacheEntry.resource.streamContent();
  }
 else {
    resourceInputStream=is;
  }
  InputStream istream=new BufferedInputStream(resourceInputStream,input);
  exception=copyRange(istream,ostream);
  istream.close();
  if (exception != null)   throw exception;
}

Code Example 14:

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source DefaultServlet.java

/** 
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
 * @param resourceInfo The ResourceInfo object
 * @param ostream The output stream to write to
 * @param range Range the client wanted to retrieve
 * @exception IOException if an input/output error occurs
 */
protected void copy(CacheEntry cacheEntry,ServletOutputStream ostream,Range range) throws IOException {
  IOException exception=null;
  InputStream resourceInputStream=cacheEntry.resource.streamContent();
  InputStream istream=new BufferedInputStream(resourceInputStream,input);
  exception=copyRange(istream,ostream,range.start,range.end);
  istream.close();
  if (exception != null)   throw exception;
}

Code Example 15:

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source DefaultServlet.java

/** 
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
 * @param resourceInfo The ResourceInfo object
 * @param ostream The output stream to write to
 * @param ranges Enumeration of the ranges the client wanted to retrieve
 * @param contentType Content type of the resource
 * @exception IOException if an input/output error occurs
 */
protected void copy(CacheEntry cacheEntry,ServletOutputStream ostream,Iterator ranges,String contentType) throws IOException {
  IOException exception=null;
  while ((exception == null) && (ranges.hasNext())) {
    InputStream resourceInputStream=cacheEntry.resource.streamContent();
    InputStream istream=new BufferedInputStream(resourceInputStream,input);
    Range currentRange=(Range)ranges.next();
    ostream.println();
    ostream.println("--" + mimeSeparation);
    if (contentType != null)     ostream.println("Content-Type: " + contentType);
    ostream.println("Content-Range: bytes " + currentRange.start + "-"+ currentRange.end+ "/"+ currentRange.length);
    ostream.println();
    exception=copyRange(istream,ostream,currentRange.start,currentRange.end);
    istream.close();
  }
  ostream.println();
  ostream.print("--" + mimeSeparation + "--");
  if (exception != null)   throw exception;
}

Code Example 16:

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source DefaultServlet.java

/** 
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
 * @param istream The input stream to read from
 * @param ostream The output stream to write to
 * @return Exception which occurred during processing
 */
protected IOException copyRange(InputStream istream,ServletOutputStream ostream){
  IOException exception=null;
  byte buffer[]=new byte[input];
  int len=buffer.length;
  while (true) {
    try {
      len=istream.read(buffer);
      if (len == -1)       break;
      ostream.write(buffer,0,len);
    }
 catch (    IOException e) {
      exception=e;
      len=-1;
      break;
    }
  }
  return exception;
}

Code Example 17:

From project agile, under directory /agile-framework/src/main/java/org/apache/catalina/servlets/.

Source DefaultServlet.java

/** 
 * Copy the contents of the specified input stream to the specified output stream, and ensure that both streams are closed before returning (even in the face of an exception).
 * @param istream The input stream to read from
 * @param ostream The output stream to write to
 * @param start Start of the range which will be copied
 * @param end End of the range which will be copied
 * @return Exception which occurred during processing
 */
protected IOException copyRange(InputStream istream,ServletOutputStream ostream,long start,long end){
  if (debug > 10)   log("Serving bytes:" + start + "-"+ end);
  try {
    istream.skip(start);
  }
 catch (  IOException e) {
    return e;
  }
  IOException exception=null;
  long bytesToRead=end - start + 1;
  byte buffer[]=new byte[input];
  int len=buffer.length;
  while ((bytesToRead > 0) && (len >= buffer.length)) {
    try {
      len=istream.read(buffer);
      if (bytesToRead >= len) {
        ostream.write(buffer,0,len);
        bytesToRead-=len;
      }
 else {
        ostream.write(buffer,0,(int)bytesToRead);
        bytesToRead=0;
      }
    }
 catch (    IOException e) {
      exception=e;
      len=-1;
    }
    if (len < buffer.length)     break;
  }
  return exception;
}

Code Example 18:

From project airlift, under directory /http-server/src/main/java/io/airlift/http/server/.

Source TimingFilter.java

@Override public ServletOutputStream getOutputStream() throws IOException {
  Preconditions.checkState(printWriter == null,"getWriter() has already been called");
  if (outputStream == null) {
    outputStream=new TimedServletOutputStream(super.getOutputStream());
  }
  return outputStream;
}

Code Example 19:

From project alfresco, under directory /root/projects/jndi-client/source/java/org/alfresco/filter/.

Source ByteResponseWrapper.java

public ServletOutputStream getOutputStream() throws java.io.IOException {
  if (print_writer_ == null) {
    if (servlet_output_ == null) {
      servlet_output_=captured_output_;
    }
    return servlet_output_;
  }
  throw new IllegalStateException();
}

Code Example 20:

From project alfresco, under directory /root/projects/remote-api/source/java/org/alfresco/repo/web/util/.

Source HttpRangeProcessor.java

/** 
 * Stream a range of bytes from the given InputStream to the ServletOutputStream
 * @param r       Byte Range to process
 * @param is      InputStream
 * @param os      ServletOutputStream
 * @param offset  Assumed InputStream position - to calculate skip bytes from
 * @return current InputStream position - so the stream can be reused if required 
 */
private void streamRangeBytes(final Range r,final InputStream is,final ServletOutputStream os,long offset) throws IOException {
  final Log logger=getLogger();
  final boolean trace=logger.isTraceEnabled();
  if (r.start != 0L && r.start > offset) {
    long skipped=offset + is.skip(r.start - offset);
    if (skipped < r.start) {
      return;
    }
  }
  long span=(r.end - r.start) + 1L;
  long bytesLeft=span;
  int read=0;
  byte[] buf=new byte[((int)bytesLeft) < CHUNKSIZE ? (int)bytesLeft : CHUNKSIZE];
  while ((read=is.read(buf)) > 0 && bytesLeft != 0L) {
    os.write(buf,0,read);
    bytesLeft-=(long)read;
    if (bytesLeft != 0L) {
      int resize=((int)bytesLeft) < CHUNKSIZE ? (int)bytesLeft : CHUNKSIZE;
      if (resize != buf.length) {
        buf=new byte[resize];
      }
    }
    if (trace)     logger.trace("...wrote " + read + " bytes, with "+ bytesLeft+ " to go...");
  }
}
Advertisements

JSP (Java) sending HttpRequest and receiving HttpResponse

JSP (Java) sending HttpRequest and receiving HttpResponse

Sending response:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

try{
response.getOutputStream().write(“<reply>1</reply>”.getBytes());
}
catch(Exception e){e.printStackTrace();}

Reading:
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class TtPaymentCheck extends Action  {

public ActionForward execute(ActionMapping mapping, ActionForm form,
HttpServletRequest request,
HttpServletResponse response)
{
String xForward=request.getHeader(“X-Forwarded-For”);
String via=request.getHeader(“Via”);
String remoteAddress=request.getRemoteAddr();
String applicationSN=request.getParameter(“applicationSN”);
try
{
URL url = new URL(“http://IP:PORT/kuetfromteletalk.php?user=&password=&appl_serial=”+applicationSN);
URLConnection uc = url.openConnection();
BufferedReader in = new BufferedReader(new InputStreamReader(uc.getInputStream()));
String inputLine;
String inputLine1=””;
while ((inputLine = in.readLine()) != null)
{
System.out.println(inputLine);
if(inputLine!=null)
inputLine1+=inputLine;
}
in.close();
if(inputLine1!=null && !inputLine1.equalsIgnoreCase(“<reply>0</reply>”))
{
String[] tmp1 = inputLine1.split(“\\|”);
String[] tmp2 = tmp1[0].split(“>”);
tmp1[0] = tmp2[1];
}
try {response.getWriter().write(inputLine1);}
catch (Exception e) {e.printStackTrace();}
}
catch(Exception e)
{
e.printStackTrace();
}
return null;
}
}

Java Servlets: HttpRequest

Original Post: http://tutorials.jenkov.com/java-servlets/httprequest.html

The HttpServlet class request processing methods take two parameters.

  1. javax.servlet.http.HttpRequest
  2. javax.servlet.http.HttpResponse

For instance, here is the signature of the HttpServlet.doGet() method:

protected void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
      throws ServletException, IOException {

}

In this text I will look at the HttpRequest object.

The purpose of the HttpRequest object is to represent the HTTP request a browser sends to your web application. Thus, anything the browser may send, is accessible via the HttpRequest.

The HttpRequest object has a lot of methods, so I will just cover the most commonly used here. The rest you can read about in the JavaDoc, if you are interested.

Parameters

The request parameters are parameters that are sent from the browser along with the request. Request parameters are typically sent as part of the URL (in the “query string”), or as part of the body of an HTTP request. For instance:

http://jenkov.com/somePage.html?param1=hello¶m2=world

Notice the “query string” part of the URL: ?param1=hello¶m2=world This part contains two parameters with parameter values:

param1=hello
param2=world

You can access these parameters from the HttpRequest object like this:

protected void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
      throws ServletException, IOException {

    String param1 = request.getParameter("param1");
        String param2 = request.getParameter("param2");

}

You would use the same code, if the request parameters were sent in the body part of the HTTP request. If no parameter exists with the given name, null is returned.

In general, if the browser sends an HTTP GET request, the parameters are included in the query string in the URL. If the browser sends an HTTP POST request, the parameters are included in the body part of the HTTP request.

Headers

The request headers are name, value pairs sent by the browser along with the HTTP request. The request headers contain information about e.g. what browser software is being used, what file types the browser is capable of receiving etc. In short, at lot of meta data around the HTTP request.

You can access the request headers from the HttpRequest object like this:

String contentLength = request.getHeader("Content-Length");    

This example reads the Content-Length header sent by the browser.

The Content-Length header contains the number of bytes sent in the HTTP request body, in case the browser sends an HTTP POST request. If the browser sends an HTTP GET request, the Content-Length header is not used, and the above code will return null.

In general, If no header exists with the name passed to getHeader(), null is returned.

InputStream

If the browser sends an HTTP POST request, request parameters and other potential data is sent to the server in the HTTP request body. It doesn’t have to be request parameters that is sent in the HTTP request body. It could be pretty much any data, like a file or a SOAP request (web service request).

To give you access to the request body of an HTTP POST request, you can obtain an InputStream pointing to the HTTP request body. Here is how it is done:

InputStream requestBodyInput = request.getInputStream();    

NOTE: You will have to call this method before calling any getParameter() method, because calling the getParameter() method on an HTTP POST request will cause the servlet engine to parse the HTTP request body for parameters. Once parsed, you cannot access the body as a raw stream of bytes anymore.

What you do with the data read from the InputStream is up to you. The servlet engine does not help you parse or interprete that data. You just get it raw.

Session

It is possible to obtain the session object from the HttpRequest object too.

The session object can hold information about a given user, between requests. So, if you set an object into the session object during one request, it will be available for you to read during any subsequent requests within the same session time scope.

Here is how you access the session object from the HttpRequest object:

HttpSession session = request.getSession();

I will not get into more detail about the session object here. It is covered in more detail in its own text.

ServletContext

You can access the ServletContext object from the HttpRequest object too. The ServletContext contains meta information about the web application. For instance, you can access context parameters set in the web.xml file, you can forward the request to other servlets, and you can store application wide parameters in the ServletContext too.

Here is how you access the ServletContext object from the HttpRequest object:

ServletContext context = request.getSession().getServletContext();            

As you can see, you have to first get the session object, to get access to the ServletContext object.

I will not get into more detail about the ServletContext object here. It will be covered in more detail in its own text.

Java Servlets: HttpResponse

Original Post: http://tutorials.jenkov.com/java-servlets/httpresponse.html

The HttpServlet class request processing methods take two parameters.

  1. javax.servlet.http.HttpRequest
  2. javax.servlet.http.HttpResponse

For instance, here is the signature of the HttpServlet.doGet() method:

protected void doGet(
    HttpServletRequest request,
    HttpServletResponse response)
      throws ServletException, IOException {

}

In this text I will look at the HttpResponse object.

The purpose of the HttpResponse object is to represent the HTTP response your web application sends back to the browser, in response to the HTTP request the browser send to your web application.

The HttpResponse object has a lot of methods, so I will just cover the most commonly used here. The rest you can read about in the JavaDoc, if you are interested.

Writing HTML

To send HTML back to the browser, you have to obtain the a PrintWriter from the HttpResponse object. Here is how:

PrintWriter writer = response.getWriter();

writer.write("<html><body>GET/POST response</body></html>");

Headers

Just like the request object, the HttpRequest can contain HTTP headers. Headers must be set before any data is written to the response. You set a header on the response object like this:

response.setHeader("Header-Name", "Header Value");

As you can see, a response header is a name, value pair.

Content-Type

The Content-Type header is a response header that tells the browser the type of the content you are sending back to it. For instance, the content type for HTML is text/html. Similarly, if what you send back to the browser is plain text, you use the content type text/plain.

Here is how you set the Content-Type header on the HttpResponse object:

response.setHeader("Content-Type", "text/html");

Writing Text

You can write text back to the browser instead of HTML, like this:

response.setHeader("Content-Type", "text/plain");

PrintWriter writer = response.getWriter();
writer.write("This is just plain text");

First the Content-Type header is set to text/plain. Then a plain text string is written to the writer obtained from the response object.

Content-Length

The Content-Length header tells the browser how many bytes your servlet is sending back. If you are sending binary data back you need to set the content length header. Here is how:

response.setHeader("Content-Length", "31642");

Writing Binary Data

You can also write binary data back to the browser instead of text. For instance, you can send an image back, a PDF file or a Flash file or something like that.

Again, you will first have to set the Content-Type header to the type matching the data you are sending back. For instance, the content type for a PNG image is image/png.

You can search for “mime types” in your favourite search engine to find a list of mime types (content types), so you can find the mime type for the content you are sending back.

In order to write binary data back to the browser you cannot use the Writer obtained from response.getWriter(). Afterall, Writer‘s are intended for text.

Instead you have to use the OutputStream obtained from the response.getOutputStream() method. Here is how:

OutputStream outputStream = response.getOutputStream();

outputStream.write(...);

Redirecting to a Different URL

You can redirect the browser to a different URL from your servlet. You cannot send any data back to the browser when redirecting. Here is how you redirect:

response.sendRedirect("http://jenkov.com");

How can I configure Tomcat with multiple virtual hosts?

Original Post/ Curtsy: 

http://www.ramkitech.com/2012/03/virtual-host-apache-httpd-server-tomcat.html

Thanks to Mr. 

Understanding Virtual Host Concept in Tomcat

Hi in this post we will see how to setup virtual host in Apache Tomcat server. Virtual Host is in-built feature that allows to deploy multiple website(domains) in single instance of tomcat server. The main benefit in this way is its cost effective.

Scenario:

I am going to deploy 3 website with following domain names in single tomcat


http://www.ramki.com
http://www.krishnan.com
http://www.blog.ramki.com

The following diagram is my outline.

Outline structure of Virtual Host Concept in Tomcat

Here my tomcat IP address 192.168.1.15. or any IP address allocated my ISP. but it should be public IP address.

How all domain names are pointing to my Tomcat?
When we purchase the domain name we need to update the our tomcat IP address to it. like

or we can simulate same DNS Setup through hosts file in both Linux and Windows. In Linux tha file is located at /etc/hosts

Now How Setup Virtual Host Concept?

Before going to setup the virtual host. first take look at the server.xml file in conf folder in tomcat directory.

server.xml

  1. <server port=“8005” shutdown=“SHUTDOWN”>
  2.   <service name=“Catalina”>
  3.        <engine defaulthost=“localhost” name=“Catalina”>
  4.             <host appbase=“webapps” autodeploy=“true” name=“localhost” unpackwars=“true”>
  5.             </host>
  6.        </engine>
  7.    </service>
  8. </server>

here <Engine> tag specified which engine is responsible for executing servlet. Here Catalina is the Engine.
<Host> tag  specify the domain name and web apps base location. here default domain name is localhost and web apps base location is webapps folder in tomcat directory. here name attribute to specify the domain name and appbase attribute to specify the location of domain specific web apps folder path.

Now we need to add more <Host> tags to represent to our domains

<Host name=“www.ramki.com” appbase=“ramki_webapps”/>
<Host name=“www.krishnan.com” appbase=“krishnan_webapps” />
<Host name=“www.blog.ramki.com” appbase=“blog_webapps” />


Then we need to copy the webapps folder in tomcat and paste it anywhere and rename it to ramki_webapps, krishnan_webapps, blog_webapps and update the path in <Host> tag

Modifies server.xml file

  1. <server port=“8005” shutdown=“SHUTDOWN”>
  2.   <service name=“Catalina”>
  3.       <engine defaulthost=“localhost” name=“Catalina”>
  4.          <host appbase=“webapps” autodeploy=“true” name=“localhost” unpackwars=“true”></host>
  5.          <host appbase=“ramki_webapps” autodeploy=“true” name=“www.ramki.com” unpackwars=“true”></host>
  6.          <host appbase=“krishnan_webapps” autodeploy=“true” name=“www.krishnan.com” unpackwars=“true”></host>
  7.          <host appbase=“blog_webapps” autodeploy=“true” name=“www.blog.ramki.com” unpackwars=“true”></host>
  8.     </engine>
  9.   </service>
  10. </server>

Simulate the DNS
Open the /etc/hosts file through root privilege and add following entry

192.168.1.15       http://www.ramki.com
192.168.1.15       http://www.krishnan.com
192.168.1.15       http://www.blog.ramki.com

deploy the websites to respective web apps folder and start the tomcat.

Test:
now open the browser and type http://www.ramki.com then its shows the ramk website content. Other two sites http://www.krishnan.com and http://www.blog.ramki.com works respective webapps.

In above diagram represent when we access http://www.ramki.com the tomcat server consult with server.xml file and serves the files from ramki_webapps directory.

How is Virtual Host Works
Here big question all websites are pointed to same tomcat. How tomcat can distinguished the request. (i.e) how tomcat knows browser requested ramki.com or http://www.krishnan.com

The answer is based Host header field in HTTP request.
when we accssed http://www.ramki.com then browser make HTTP request. and the request look like this

GET / HTTP/1.1 
Host: http://www.ramki.com 
Proxy-Connection: keep-alive 
User-Agent: Mozilla/5.0 (Windows NT 6.2) AppleWebKit/535.11 (KHTML, like Gecko) Chrome/17.0.963.56 Safari/535.11 
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8 
Accept-Encoding: gzip,deflate,sdch 
Accept-Language: en-US,en;q=0.8


here Host Field contain domain name
Host: http://www.ramki.com

when tomcat receive the request from any browser, it read the Host field and understand which domain we requested, then consult the server.xml file and delegate to appropriate Host process thread

check my screen cast for setup

How to setup virtualhost in Tomcat

I recently had to configure a couple of different tomcat web applications as virtual hosts each one with its own domain. I was accessing these applications using the URL http://localhost:8080/app1 and http://localhost:8080/app2. The basic intention behind the virtual host setup was to avoid the web application name from the url (app1/app2) and the applications to be accessed using http://www.domain1.com and http://www.domain2.com/ . If there was only one web application I could have achieved it by keeping the web application inside webapps/ROOT folder.

Though I am using Apache as front server which was used to forward the dynamic content request to tomcat, I am not describing the Apache-Tomcat configuration in this article. I have described the Apache-Virtualhost-Tomcat-configuration in another article.

Step 1: Configuring Tomcat server.xml

Add the following entry in server.xml (TOMCAT_HOME/conf/server.xml). This should be added below to <Host name=”localhost” ..>…….</Host>

<Host name="www.domain1.com" appBase="/opt/tomcat/www.domain1.com" unpackWARs="true" autoDeploy="true" xmlValidation="false" xmlNamespaceAware="false"/>

<Host name=”www.domain2.com” appBase=”/opt/tomcat/www.domain2.com” unpackWARs=”true” autoDeploy=”true” xmlValidation=”false” xmlNamespaceAware=”false”/>

Step 2: Deploying the applications

Create folders http://www.domain1.com and http://www.domain2.com inside TOMCAT_HOME. Copy the webapp1 to http://www.domain1.com and webapp2 to http://www.domain2.com. Rename both webapp1 and webapp2 to ROOT (ensure ROOT should be in uppercase).

The following should exist after the completion of step2.

TOMCAT_HOME/www.domain1.com/ROOT/webapp1_contents
TOMCAT_HOME/www.domain2.com/ROOT/webapp2_contents

Step 3: Enabling Tomcat Manager Console for the new hosts

The default tomcat manager console (http://localhost:8080/manager/html) will not be available for the new hosts. Manager Console needs to be enabled for the application deployed under each virtual host. This can be done by following the below steps.

Create folders http://www.domain1.com and http://www.domain2.com under TOMCAT_HOME/conf/Catalina/. Copy manager.xml from TOMCAT_HOME/conf/Catalina/localhost/ to TOMCAT_HOME/conf/Catalina/www.domain1.com/ and TOMCAT_HOME/conf/Catalina/www.domain1.com/.

The tomcat manager console for the hosts http://www.domain1.com and http://www.domain2.com can be accessed using the URLs http://www.domain1.com:8080/manager/html and http://www.domain2.com:8080/manager/html respectively.

Step 4: Adding host entry for each virtualhost

In production/staging environments normally the domain would be mapped to the IP of the machine. However in development environments we need to map the IP with the virtualhost. This can be done by adding a host entry in the host file. The ‘hosts’ file is typically located at C:\WINDOWS\system32\drivers\etc\hosts on windows and /etc/hosts on UNIX

Machine-IP http://www.domain1.com
Machine-IP http://www.domain2.com

Step 5: verifying the virtualhosts

Restart the Tomcat Server and check whether the webapp1 and webapp2 are accessible using the URLs http://www.domain1.com:8080 and http://www.domain2.com:8080 respectively.

If you are using Apache web server and Tomcat, you can leave Tomcat running on port 8080. Otherwise simply change the port of tomcat from 8080 to 80.

With Tomcat running on JVM Host dedicated JVM you have full control over configuration files. You may host multiple domains and map them to particular web applications. First step is to map a domain or a directory under it to the Tomcat (this is done with mod_jk or mod_proxy_ajp using our JVMCP control panel), second step is to add virtual host in server.xml. See the below example.

You have 2 domains: primary domain domain1.com and addon domain domain2.com. Your ~/appservers/apache-tomcat/webapps directory:

$ls -al
docs
domain1
domain2
examples
manager
host-manager
ROOT

Please put JSP files into domain1 and domain2 directories. Alternatively you can put domain1.war and domain2.war in webapps directory and Tomcat will deploy the wars.

  1. Domain1.com is the main domain (the main domain can point to different directory such as ROOT, anyway this is only example).
  2. Domain2.com is the domain that we want to add to Tomcat.
  3. You need create domain2.com as addon domain in cPanel.
  4. Please make sure you use correct nameservers for domain2.com.
  5. Create mappings – default mappings are enough. Use custom JVM control panel JVMCP for this.
  6. Configure $CATALINA_HOME/conf/server.xml file.

Please edit $CATALINA_HOME/conf/server.xml

 <Host name="domain1.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain1.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain1" debug="0" reloadable="true"/> 
 </Host>

 <Host name="domain2.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain2.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain2" debug="0" reloadable="true"/> 
 </Host>

Restart Tomcat using JVMCP or shell and your are done.

– See more at: http://www.jvmhost.com/articles/how-to-configure-tomcat-with-multiple-virtual-hosts#sthash.Yw1C4fx0.dpuf

With Tomcat running on JVM Host dedicated JVM you have full control over configuration files. You may host multiple domains and map them to particular web applications. First step is to map a domain or a directory under it to the Tomcat (this is done with mod_jk or mod_proxy_ajp using our JVMCP control panel), second step is to add virtual host in server.xml. See the below example.

You have 2 domains: primary domain domain1.com and addon domain domain2.com. Your ~/appservers/apache-tomcat/webapps directory:

$ls -al
docs
domain1
domain2
examples
manager
host-manager
ROOT

Please put JSP files into domain1 and domain2 directories. Alternatively you can put domain1.war and domain2.war in webapps directory and Tomcat will deploy the wars.

  1. Domain1.com is the main domain (the main domain can point to different directory such as ROOT, anyway this is only example).
  2. Domain2.com is the domain that we want to add to Tomcat.
  3. You need create domain2.com as addon domain in cPanel.
  4. Please make sure you use correct nameservers for domain2.com.
  5. Create mappings – default mappings are enough. Use custom JVM control panel JVMCP for this.
  6. Configure $CATALINA_HOME/conf/server.xml file.

Please edit $CATALINA_HOME/conf/server.xml

 <Host name="domain1.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain1.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain1" debug="0" reloadable="true"/> 
 </Host>

 <Host name="domain2.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain2.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain2" debug="0" reloadable="true"/> 
 </Host>

Restart Tomcat using JVMCP or shell and your are done.

– See more at: http://www.jvmhost.com/articles/how-to-configure-tomcat-with-multiple-virtual-hosts#sthash.Yw1C4fx0.dpuf

http://www.jvmhost.com/articles/how-to-configure-tomcat-with-multiple-virtual-hosts

How to create virtual host for app on Tomcat.

NB! I will say right away, that my Tomcat is running on Ubuntu Server 10.10 under VMWare Workstation 7.
So here it goes. Recently I installed YouTrack issue tracker on my local server, that runs on Tomcat. Very soon I got tired from typing every time (ip_address/webapp_name:port). So I looked up how to create a very simple VirtualHost for Tomcat.

To create Tomcat VirtualHost you just need to edit tomcat_dir/conf/server.xml and inside Engine tag place following code:

1
2
3
4
5
<Host name="virtual_host_name" appBase="webapps/your_app_name" unpackWars="false" autoDeploy="false">
    <Logger className="org.apache.catalina.logger.FileLogger" directory="logs" prefix="virtual_log." suffix=".txt" timestamp="true" />
    <Context path="" docBase="path_to_your_webapp_from_root" debug="0" reloadable="true" />
    <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs" prefix="virtual_log." suffix=".txt" pattern="common" />
</Host>

So in the end you will have to add this virtual_host_name to your windows hosts file and link to your VM ip address. Then you will be abble to access your like: virtual_host_name:8080.

With Tomcat running on JVM Host dedicated JVM you have full control over configuration files. You may host multiple domains and map them to particular web applications. First step is to map a domain or a directory under it to the Tomcat (this is done with mod_jk or mod_proxy_ajp using our JVMCP control panel), second step is to add virtual host in server.xml. See the below example.

You have 2 domains: primary domain domain1.com and addon domain domain2.com. Your ~/appservers/apache-tomcat/webapps directory:

$ls -al
docs
domain1
domain2
examples
manager
host-manager
ROOT

Please put JSP files into domain1 and domain2 directories. Alternatively you can put domain1.war and domain2.war in webapps directory and Tomcat will deploy the wars.

  1. Domain1.com is the main domain (the main domain can point to different directory such as ROOT, anyway this is only example).
  2. Domain2.com is the domain that we want to add to Tomcat.
  3. You need create domain2.com as addon domain in cPanel.
  4. Please make sure you use correct nameservers for domain2.com.
  5. Create mappings – default mappings are enough. Use custom JVM control panel JVMCP for this.
  6. Configure $CATALINA_HOME/conf/server.xml file.

Please edit $CATALINA_HOME/conf/server.xml

 <Host name="domain1.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain1.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain1" debug="0" reloadable="true"/> 
 </Host>

 <Host name="domain2.com" autoDeploy="true" appBase="webapps" unpackWARs="true">
 <Alias>www.domain2.com</Alias>
 <Valve className="org.apache.catalina.valves.AccessLogValve" directory="logs"   
                prefix="localhost_access_log." suffix=".txt" 
                pattern="%h %l %u %t "%r" %s %b" resolveHosts="false"/>
 <Context path="" docBase="domain2" debug="0" reloadable="true"/> 
 </Host>

Restart Tomcat using JVMCP or shell and your are done.

– See more at: http://www.jvmhost.com/articles/how-to-configure-tomcat-with-multiple-virtual-hosts#sthash.Yw1C4fx0.dpuf

Install Open Java on Debian

1. Setup Debian 6 (squeeze) with Minimal features

2. update:  nano  /etc/apt/sources.list

deb http://ftp.debian.org/debian/ squeeze  main
deb http://ftp.de.debian.org/debian sid main

3. If you have proxy:  export http_proxy=http://172.16.200.1:3128/

4. apt-get update

5. now follow the bellow:

java -version   (to test is Java installed?)

Using Java in Debian

To install the default JRE (Java Runtime Environment) on your system, run:

apt-get install default-jre

To install the default JDK (Java Development Kit) on your system, run:

apt-get install default-jdk

How To Install and Configure Apache Tomcat on a Debian Server

1. nano /etc/apt/sources.list

deb http://ftp.debian.org/debian/ squeeze  main
deb http://ftp.de.debian.org/debian sid main

2. Details

Apache Tomcat is an application server that can be used to serve Java applications to web users. It is an open implementation of the Java Servlet and JavaServer Pages specs that were developed by Sun Microsystems.

If you develop Java applications, Tomcat is a quick and easy way to serve them in a full server environment specifically designed for that purpose.

In this guide, we will install Tomcat and do some basic configuration on a Debian 7 VPS. To complete this tutorial, you will have to have a normal user with sudo privileges. Follow this guide to learn how to create users on a Debian system.

Install Apache Tomcat

In this guide, we will install Tomcat version 7 and its associated packages. Luckily, these are included in the default Debian repositories.

To get the basic package, we can update our package source list and then install the main package:

export http_proxy=http://172.16.200.1:3128/  (if you have proxy)
apt-get update  or sudo apt-get update
(to use sudo ) apt-get install sudo
apt-get install tomcat7  or sudo apt-get install tomcat7

This is all we need to do to get to the default Tomcat page. Our installation is not complete yet, but you can take a look at the default Tomcat page by going to your IP address or domain followed by :8080 in your web browser:

your_domain_or_ip:8080

DigitalOcean Tomcat default page

In order to take advantage of more of Tomcat’s features, we will install some additional Tomcat packages.

These will allow us to use a web interface to control Tomcat. It will install some documentation and examples that we can also access through the web interface as well.

sudo apt-get install tomcat7-admin tomcat7-examples tomcat7-docs    (or)
apt-get install tomcat7-admin tomcat7-examples tomcat7-docs

Install Java Development Tools

In order to use Tomcat to develop Java applications on your server, you will need to download and install a few things.

The first thing we need to do is install a compatible Java Development Kit. We can install the one that Debian selected as default with the following command:

sudo apt-get install default-jdk or
apt-get install default-jdk

This will install openjdk-6-jdk which will work well in our environment.

The Tomcat documentation also suggests that you install Apache Ant, which is a build tool for Java applications, and a version control system of some sort. We will choose git:

sudo apt-get install ant git  or
apt-get install ant git  

These will help you build your Java applications and keep the code organized.

Configure Tomcat Web Interface

Before we can begin using some of the features we installed, we need to configure our server with a user and password. Tomcat does not do this by default for security reasons.

The configuration is very simple. We need to edit a file called tomcat-users.xml. Open it with an editor like this:

sudo nano /etc/tomcat7/tomcat-users.xml    or
nano /etc/tomcat7/tomcat-users.xml 

Inside, you will find a heavily commented user configuration file. In fact, the only portions of the file that are not comments are:

<tomcat-users>
</tomcat-users>

As you might expect, we need to define a user between these two lines. We will give this user access to the web interfaces. We can define a user like this:

<tomcat-users>
    <user username="admin" password="password" roles="manager-gui,admin-gui"/>
</tomcat-users>

Choose whatever username and password you would like. This will provide you with login credentials that allow you to access the management panels.

Save and close the file when you are finished.

We should restart Tomcat in order to implement our changes:

sudo service tomcat7 restart   or
service tomcat7 restart

Test the Web Interface

Once you have installed Tomcat and configured the user login, you can access the main page by going to your server IP address or domain name followed by :8080 like this:

your_domain_or_ip:8080

You will see the same default Tomcat page that you saw earlier (if you checked):

DigitalOcean Tomcat landing

Because we have installed and configured more components, however, we will have access to more functionality.

You can access the Tomcat documentation in the browser by clicking the link you see on the page or accessing this page:

your_domain_or_ip:8080/docs

DigitalOcean Tomcat docs

This should be your first stop when you have questions about how to do something with Tomcat.

We also now have access to some example applications that are implemented using a few different technologies. These can be reached from a link on the same initial landing page, or by visiting:

your_domain_or_ip:8080/examples

DigitalOcean Tomcat examples

Clicking through these items gives us an idea of how different functionality can be implemented in this environment. Most examples include the source code that you can use for reference.

The main functionalities that you will want access to are the manager webapp and the host-manager webapp.

Again, you can access those from the initial landing page, or by visiting:

your_domain_or_ip:8080/manager/html

And:

your_domain_or_ip:8080/host-manager/html

The first site will allow you to manage your Java applications. It will let you start, stop, deploy, and reload your apps easily. It can also find memory leaks caused by your running applications:

DigitalOcean Tomcat Manager Webapp

From the other page, you can test, adjust, and add virtual hosts in order to server your applications. This allows you to set up access to your deployed apps easily:

DigitalOcean Tomcat Host Manager Webapp

Conclusion

As you can see, Tomcat provides a nice platform for controlling and serving your Java applications in a web environment. You can easily deploy .war files and have them up and running in very little time.