如果我在实现servlet中任意分配一个'id'值,它就可以工作;但是,如果我没有正确地从抽象类继承id值并跳过'if'语句转发到'then'语句中提供的url。是什么赋予了?可以告诉'id'变量有什么问题:
抽象servlet snipet:
protected Integer id = null;
private void _doProcess(final HttpServletRequest request, final HttpServletResponse response)
throws IOException, ServletException {
try {
response.setContentType("text/html");
writer = response.getWriter();
final String idString = request.getParameter("id");
if(StringUtil.isNotEmptyStringTrimmed(idString)){
try {
id = Integer.parseInt(idString.trim());
} catch (NumberFormatException e) {
id = null;
}
}
doProcess(request,response);
} finally {
id = null;
}
try {
writer.close();
} catch (Exception e) {
// no-op
}
}
实现servlet snipet:
public void doProcess(final HttpServletRequest request, final HttpServletResponse response)
throws IOException, ServletException {
// set page title
final HttpSession session = request.getSession();
session.setAttribute("pageTitle", "Training Project 5: Author");
if (id == null){
request.setAttribute("authorNamesList", printAuthorNames());
request.getRequestDispatcher("authorList.jsp").include(request,response);
}else{
final Author author = BEAN_FACTORY.getMember(id);
session.setAttribute("authorId",author.getId());
session.setAttribute("name", author.getName());
session.setAttribute("bio", author.getBio());
session.setAttribute("picture",author.getPicture());
session.setAttribute("bookTitles", printBookTitles(author.getId()));
request.getRequestDispatcher("authorPage.jsp").include(request,response);
}
}
当上面的servlet“else”代码不在条件语句中时,下面的jsp代码可以工作:
<div id="right">
<table class="display" summary="Author Information">
<tr>
<td><span class="brown">Author Id: <c:out value="${authorId}"/></span></td>
</tr>
<tr>
<td><span class="brown">Name: <c:out value="${name}"/></span></td>
</tr>
<tr>
<td><span class="brown">Bio: <c:out value="${bio}"/></span></td>
</tr>
<tr>
<td>
<p>
<span class="brown"><img src="<c:out value="${picture}"/>" alt= ""/></span>
</p>
</td>
</tr>
答案 0 :(得分:3)
除非id
是一个类字段,否则您不会向我们展示所有代码。目前还不清楚你的意思是“它不起作用”。预期的内容是空的?你得到一个例外吗?
答案 1 :(得分:1)
'Id'将始终为null或未定义,而不是未初始化。
答案 2 :(得分:0)
找出问题所在。 。 。对不起的家伙(和加尔斯)我没有给每个人足够的信息来解决问题。有一个authorList.jsp页面打印每个人都选择的列表(见下文)。用户在authorList.jsp页面中选择他们想要查看信息的作者,然后将作者id参数转发回servlet,该servlet将用户转发到authorPage.jsp,该页面显示各个作者信息。
基本上,我使用了以下jsp页面(authorPage.jsp)的确切.jsp名称,而不是web.xml上的servlet映射名称(listAuthor)。我有:
<table summary="Author List">
<c:forEach items="${authorNamesList}" var="name">
<tr>
<td><span class="brown"><a href="authorPage.jsp?id=${name.key}">${name.value}</a></span></td>
</tr>
</c:forEach>
应该是:
<table summary="Author List">
<c:forEach items="${authorNamesList}" var="name">
<tr>
<td><span class="brown"><a href="listAuthor?id=${name.key}">${name.value}</a></span></td>
</tr>
</c:forEach>
</table>
有时最好离开,稍后回来看看它新鲜!感恩节快乐大家:)