Wednesday, 10 August 2011

Java :- Sending Data to Servlet From JSP

Sending Data from Jsp to Servlet or Communication between Jsp & Servlet , we need certain things like ;-



1. A Jsp File

2. Deployment Descriptor (web.xml)

3. A Servlet File (Normal Java File)





Jsp File (index.jsp)



<%@ page language="java" import="java.util.*" pageEncoding="ISO-8859-1"%>

<%

String path = request.getContextPath();

String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";

%>















My JSP 'index.jsp' starting page



































Servlet File (test1.java)



Note : Here doGet/doPost/service method can be used.But I used here doGet(),becacuse the form action method is GET in index.jsp. So , I used doGet() in this example. But service method can use for both POST/GET method .But you can use any of these.



public void doGet(HttpServletRequest request, HttpServletResponse response)

throws ServletException, IOException {



response.setContentType("text/html");

PrintWriter out = response.getWriter();

String name=request.getParameter("txtname");

out

.println("");

out.println("");

out.println(" A Servlet");

out.print("

Hi I am

");

out.print("

"+name+"

");

out.println(" ");

out.println("");

out.flush();

out.close();

}





Deployment Descriptor (Web.xml)









index.jsp





This is the description of my J2EE component

This is the display name of my J2EE component

test1

test1





test1

/test1











Note: In web.xml url-pattern is the path for browser ,so any name can be used (not /test1). we need & tag for run & map a servlet to the path. But, Url-pattern must match with the form action .







This is a simple Example for Communicate a servlet from jsp by passing a value Name or any Data.Enjoy..............the flavor of JAVA.



Posted By:- javadevelopersguide

Follow :- javadevelopersguide.blogspot.com