Create a Dynamic Web Application in eclipse
Java Servlet Tutorial
In java, to develop a dynamic web application, servlets are used. Servlets are server side programs.
ServletsHome
Create Web Application
Go to File Menu select New → Dynamic Web Application → Enter project name → click Finish.
Create Servlet
Right click on project that you created and select New → Servlet
It opens " CreateServlet" window and enter the servlet name and click New → New → Finish
It creates a servlet with following code with
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; /** * * @author somanew */ public class FirstServlet extends HttpServlet { /** * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods. * @param request servlet request * @param response servlet response * @throws ServletException if a servlet-specific error occurs * @throws IOException if an I/O error occurs */ protected void processRequest(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); try { out.println("Hello World"); } finally { out.close(); } }
Now you will see import errors
Hover on the error line. a popup menu displayed..
Select "Fix project setting.." Option.
Next it opens another popup window, now click on the link shown in the popup.
It opens a Java Build Path window. Check out JRE Libraries, and Web App Libraries as shown in video in page 9.(0.32 timeline)
Next, select Libraries tab. Add External Jars from rightsize. Now locate the tomcat folder open up lib folder select servlet.api.jar, jsp.api.jar(optional) click on open.
Now imports errors disappear.
Add the code in service method and next add the given import statements in the below
java.io.IOException;
java.io.Printwriter;
classes to servlet save it
Register Servlet in Deployment Descriptor(web.xml)
Now open web.xml file which is in WebContents folder in the project and the code given below.
<?xml version="1.0" encoding="ISO-8859-1"?> <we-app> <servlet> <servlet-name>FirstServlet</servlet-name> <servlet-class>FirstServlet</servlet-class> </servlet> <servlet-mapping> <servlet-name>FirstServlet</servlet-name> <url-pattern>/FirstServlet</url-pattern> </servlet-mapping> </web-app>
Save it.
Run the Project
From run button, select run on server.
Select the server, say next and finish.
Select the project from left pane click on Add button, so it is now shifted to right pane. Now click finish
Server started automatically.
Open Servlet in Browser
http://localhost:8080/FirstWebApplication/FirstServlet
You will see the output on the browser.
Here is the Demo:
Comments
Post a Comment