【发布时间】:2016-03-04 02:22:05
【问题描述】:
我目前正在学习使用 JSP 和 Servlet 进行 Java 服务器端编程。我创建了一个简单的动态 Web 项目并将其部署在 apache tomcat 中。基本上,只有一个页面(jsp)作为前端,它会根据用户选择的内容(表单/单选按钮)随 servlet 动态更改。
The directory structure:
| index.jsp
|
+---img
| apples.jpg
| oranges.jpg
| salad.jpg
| strawberries.jpg
|
\---WEB-INF
| web.xml
|
\---classes
DynamicServlet.class
DynamicServlet.java
我已将 web.xml 配置为启动 index.jsp @(http://localhost:port/contextname)
<web-app>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
相关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 -->
现在,当用户做出选择并提交时,servlet 会根据用户选择使用图像更新 jumbotron 封面。如您所见,我为此使用了EL。
Servlet 代码:
...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);
它按预期工作。我无法弄清楚的是如何根据选择CHANGE jumbotron 文本。我正在寻找一种方法以某种方式替换 index.jsp 中的<h1>Hello, World!</h1> 行,基于用户从servlet 中选择的自定义文本(类似于<h1>Yay, Apples!</h1>),最好使用getRequestDispatcher()。实现这一目标的任何提示?
注意:
1. 登陆页面必须有一个静态的jumbotron text(Hello, World!)
2. 更改必须反映在同一页面上。我不打算创建一个
单独的jsp。
我是初学者,所以如果我错过了一个明显的解决方案,请体谅。谢谢。
【问题讨论】:
-
只需设置一个请求属性并像在 doGet() 中一样转发到 JSP 吗?
-
@BalusC:我想到了,但不知道在 HTML 中放什么,因为我最初想要一个静态文本,然后从 servlet 中更改它。所以真的不能像我为 img 所做的那样决定把 EL 放在哪里。抱歉听起来有点糊涂。