How to start with Servlets, Write a servlet program to print the name coming from a HTML form.
Before we start with servlets , make sure you have following software installed.
- Apache Tomcat 7.0
- Java 1.7 or higher
Create a folder structure as shown below under C:\Program Files\Apache Software Foundation\Tomcat 7.0\webapps directory.
- Create a file say HelloWorld.java and placed it in the classes folder.
- compile the HelloWorld.java file.
- edit the web.xml file as given below.
- Create a Hello.html file and place it in HelloWorld i.e. root folder.
- Run the Tomcat Server.
- Navigate to the following URL.
http://localhost:8080/HelloWorld/Hello.html
You should see the Hello.html web page on your browser.Hello.html - Enter your Name in the text field and click submit.
- You should see the result something like below.
import javax.servlet.http.*; import javax.servlet.*; import java.io.*; public class HelloWorld extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response)throws ServletException, IOException { String name=request.getParameter("t1"); response.setContentType("text/html"); PrintWriter ps=response.getWriter(); ps.print("Hello "+name); } }
<?xml version="1.0" encoding="ISO-8859-1"?> <!-- Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --> <web-app xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" version="3.0" metadata-complete="true"> <display-name>Welcome to Tomcat</display-name> <description>Welcome to Tomcat</description> <servlet> <servlet-name>FirstSer</servlet-name> <servlet-class>HelloWorld</servlet-class> </servlet> <servlet-mapping> <servlet-name>FirstSer</servlet-name> <url-pattern>/DisplayName.do</url-pattern> </servlet-mapping> </web-app>
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd"> <html> <head> <title> First App</title> </head> <body> <form action="DisplayName.do"> <center> <h1>Please enter your name </h1> <input type="text" name="t1"><input type="submit" value="Submit"> </center> </form> </body> </html>
If you run into any error, please feel free to reach us.
No comments:
Post a Comment