如何在JSP中嵌入HTML?

8

我搜索过这个问题,有些答案,但不完全符合我的问题。所以,这是我的jsp代码:

<body>
    <%
        if (manager.isValid(request.getParameter("username"),request.getParameter("password"))){
            out.print("<h1> Welcome ");
            out.print(request.getParameter("username") + "</h1>");
        } else {
            out.print("<h1> Please Try Again </h1> <br />");
            out.print("Either your username or password is incorrect. Please Try again <br /> <br />");
                        }
    %>
    <%@ include file="LoginForm.html" %>
    

但是我希望只在"else"块中包含"loginForm.html",该如何实现呢?当然,这并不起作用,但您可以猜到我的意思:

<%
        if (manager.isValid(request.getParameter("username"),request.getParameter("password"))){
            out.print("<h1> Welcome ");
            out.print(request.getParameter("username") + "</h1>");
        } else {
            out.print("<h1> Please Try Again </h1> <br />");
            out.print("Either your username or password is incorrect. Please Try again <br /> <br />");
            include file="LoginForm.html" ;
        }
    %>
2个回答

21

我想给您展示一种方法,请尝试以下方式。您可以使用else而不是if

<body>
        <%
            int x = 10;
            if(x>10) {
        %>
        <%@include  file="some.html" %>
        <%
            }
        %>

</body>

0
您还可以在JSP文件函数中包含可重用的HTML,并在需要打印时调用它。例如,config.jsp 包含:
<%!
  public void printMenu()
  {
   %>
   HTML HERE
   <%!
  }
%>

home.jsp 包含

<%@include file="config.jsp"%>
<!DOCTYPE html>
<html>
  <body>
      <% printMenu(); %>
    <div id="PeopleTableContainer" style="width: 800px;"></div>

仅供未来的程序员参考,我尝试使用了这种方法,它的作用是第一行<%@include file="config.jsp"%>会将“HTML HERE”替换为实际内容。然后当<% printMenu(); %>出现时,它会像正常调用函数一样调用该函数。因此,在这里需要额外的行为,至少在我的经验中是如此。 - GioPoe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接