Servlets are usually used for more complex database applications. Many application will use servlets instead of JSP and others will use servlets in conjunction with JSP. Experienced JSP programmers use servlets in conjunction with JSP to create clearer and simpler applications. The servlets handle Java processing: form handing, calculation and database queries. JSP formats the results. Using Servlets, you can collect input from users through web page forms, present records from a database or another source, and create web pages dynamically. Apache Tomcat is a popular tool for developing server side apps. It is an open source implementation of several Java EE (Enterprise Edition) specifications, the Java Servlet, JavaServer Pages, Java Expression Language and Java WebSocket technologies. See Server-Side Development on Mac OS X: Servlets and Tomcat - Developer.com |
// Import required java libraries - I haven't tested this import java.io.*; import javax.servlet.*; import javax.servlet.http.*; // Extend HttpServlet class public class HelloServlet extends HttpServlet { private String message; public void init() throws ServletException { // Do required initialization message = "Hello World"; } public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { // Set response content type response.setContentType("text/html"); // Actual logic goes here. PrintWriter out = response.getWriter(); out.println("<h1>" + message + "</h1>"); } public void destroy() { // do nothing. } }Links: Servlets - Examples | TutorialsPoint.com Resin : Tutorials : A Hello, World Servlet Java How to get started with server-side Java | JavaWorld Verify Java Version Java Downloads for All Operating Systems | Java.com Java SE - Downloads | Oracle Technology Network | Oracle.com "Professional Java Web Applications: Featuring WebSockets, Spring Framework, JPA Hibernate and Spring Security" |
<!DOCTYPE html> <html> <body> <servlet> <servlet-name>HelloServlet</servlet-name> <servlet-class>com.wrox.HelloServlet</servlet-class> </servlet> <load-on-startup>1</load-on-startup> </body> </html> Create a web.xml file in your WEB-INF directory Example: WEB-INF/web.xml <?xml version="1.0" encoding="UTF-8"?> <web-app xmlns="http://java.sun.com/xml/ns/j2ee" version="2.4" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http:/java.sun.com/dtd/web-app_2_3.dtd"> <servlet> <servlet-name>hello</servlet-name> <servlet-class>test.HelloServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>hello</servlet-name> <url-pattern>/hello</url-pattern> </servlet-mapping> </web-app> or a simple form <!DOCTYPE html> <html> <body> <FORM METHOD="POST" ACTION="/servlet/HelloServlet"> <label><b>Please enter your name</b></label> <INPUT TYPE="text" NAME="name" SIZE=30 > <input type="submit" value="Submit" /> </form> </body> </html> |
|