I'm currently learning Java Server Side programming with JSP and Servlet. I have created a simple dynamic web project and deployed it in apache tomcat. Basically, there's only one page(jsp) as the front-end that is dynamically altered with the servlet based on what the user selects(form/radio buttons).
The directory structure:
| index.jsp
|
+---img
| apples.jpg
| oranges.jpg
| salad.jpg
| strawberries.jpg
|
\---WEB-INF
| web.xml
|
\---classes
DynamicServlet.class
DynamicServlet.java
I have configured the web.xml to launch index.jsp @(http://localhost:port/contextname)
<web-app>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
Relevent code from the index.jsp:
...<head>...<style>
.jumbotron {
background-image: linear-gradient( rgba(0, 0, 0, ${grad}), rgba(0, 0, 0, ${grad}) ), url('${pageContext.request.contextPath}/img/${img}');
background-size: cover;
color: ${color};
}
...<body>
<div class="container"> <!-- jumbotron-container -->
<div class="jumbotron">
<h1>Hello, World!</h1> <!-- <====This line====> -->
</div> <!-- /jumbotron -->
</div> <!-- /jumbotron container -->
<div class="container"> <!-- form-container -->
<form action="${pageContext.request.contextPath}/magic" method="get">
<label class="form-label">Pick your favorite:</label>
<div class="input-group form-group col-xs-6">
<span class="input-group-addon">
<input type="radio" name="option" value="apples">
</span>
<input type="text" class="form-control" disabled="disabled" placeholder="Apples">
</div> <!-- /apples -->
<div class="...
</div> <!-- /oranges -->
<div class="...
</div> <!-- /strawberries -->
<div class="...
</div> <!-- /salad -->
<input type="submit" class="btn btn-primary" value="Submit">
</form> <!-- /form -->
</div> <!-- /form-container -->
The result is something like this:
Now, when a user makes a selection and submits, the servlet updates the jumbotron cover with an image based on user selection. I have used EL for this as you can see.
Servlet code:
...doGet(HttpServletRequest.....{
String option = request.getParameter("option");
try {
switch (option) {
case "apples":
request.setAttribute("img", "apples.jpg");
break;
case "oranges":....and so on
}...
...request.getRequestDispatcher("index.jsp").forward(request, response);
And it works as expected. What I haven't been able to figure out is how to CHANGE the jumbotron text based on the selection. I'm looking for a way to somehow replace the line <h1>Hello, World!</h1>
in index.jsp with custom text(something like <h1>Yay, Apples!</h1>
) based on user selection from the servlet preferably using the getRequestDispatcher(). Any hints for achieving this?
Note:
1. The landing page must have a static jumbotron text(Hello, World!)
2. The change must reflect on the same page. I don't intend to create a
separate jsp.
I'm a beginner so please be considerate if I have missed an obvious solution. Thanks.