Ingo Reschke » Posts for tag 'servlet'

Ein Servlet

Ein Beispielcode für eine sehr einfaches Servlet.

import java.io.IOException;
import java.io.PrintWriter;
 
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
 
 
public class SomeServlet extends HttpServlet{
 
	@Override
	public void doGet(HttpServletRequest request,HttpServletResponse response)throws ServletException, IOException {
 
		// Use "request" to read incoming HTTP headers (e.g. cookies)
		// and HTML form data (e.g. data the user entered and submitted)
 
		// Use "response" to specify the HTTP response line and headers
		// (e.g. specifying the content type, setting cookies).
 
		PrintWriter out = response.getWriter();
		// Use "out" to send content to browser
		response.setContentType("text/html");
		out.println("Hello servlet");
	}
}

Um es aufzurufen muß man dem Webserver Bescheid sagen.
Dies tut man in der web.xml
Hier ein Beispiel für den web.xml – Eintrag

<servlet>
  <servlet-name>bspServlet</servlet-name> 
  <description></description> 
  <servlet-class>SomeServlet</servlet-class> 
  <init-param>
	<param-name>trimSpaces</param-name>
	<param-value>true</param-value>
  </init-param>
</servlet>
 
<servlet-mapping>
  <servlet-name>bspServlet</servlet-name> 
  <url-pattern>/go/*</url-pattern> 
</servlet-mapping>

Alles was jetzt über die Domain: localhost:8080/go/*.* aufgerufen wird, leitet der Toncat an das Servlet SomeServlet weiter.

Quelle:

http://openbook.galileocomputing.de/javainsel8/javainsel_20_012.htm#mje80170e7a450724e448fba4cd314d91a

Posted in Java
Tags: , ,