Here we will illustrate calling a Servlet application from
a JSP and vice versa.
Remarks
The sample will have:
An initial JSP which will display the list of Countries
in a Combo box and a button called 'Get Cities'. When the user selects a Country
and clicks on the button, the same JSP is called which forwards the request
to a Servlet to fetch the cities for the country from the database.
The Servlet uses a Bean method to fetch the Cities
from the database and passes the values to another JSP through the Request
object. The JSP in turn renders the data for the client.
Code from Countries.jsp
<%@ page import="CountriesCitiesBean" %> <%-- This jsp sample displays list of Countries in a drop down list. The jsp calls a java Bean: CountriesCitiesBean within <jsp: useBean> tag. The bean queries the countries table in the database and displays country names. There is button 'Find Cities', which when pressed will list list of cities for the selected country.
Basically, when the button is pressed, that countryId is passed as the value
of the input parameter. Now, Jsp -Servlet- Jsp interaction happens. When
countryId exists then the request is forwarded to the servlet, and the servlet
forwards it to another jsp i.e Cities.jsp to display servlet's output. --%>
<% // Store the input parameter: countryId into a variable String countryId=request.getParameter("countryId"); if (countryId!=null) session.putValue("countryId",countryId); %> <% // Use the Jsp UseBean tag to refer the CountriesCitiesBean class and set // the property of a bean attribute: searchCondition from the input // parameter: countryId. %> <jsp:setProperty
name="CountriesCitiesBean" property="searchCondition" value="<%=countryId%>" /> <% // If countryId is null then display list of countries as a drop down list. if (countryId==null) { %> <HTML> <HEAD> <TITLE> Oracle JSP - Servlet Interaction Sample - List of Countries </TITLE> </HEAD> <BODY BGCOLOR="white" background="../images/Background.gif"> <CENTER> <%= CountriesCitiesBean.getCountries() %><BR> </CENTER> </BODY> </HTML> <% } else { // If parameter countryId is not null, forward the result to // ServletWrapper, which calls another jsp: Cities.jsp to display // corresponding cities. %> <HTML> <BODY> <jsp:forward page="/servlet/ServletCallingJsp" /> </BODY> </HTML> <% } %>