【问题标题】:<c:out> tag is not showing up in JSP nor does it work<c:out> 标记没有出现在 JSP 中,也不起作用
【发布时间】:2021-04-14 09:37:35
【问题描述】:

不知何故,&lt;c:out&gt; 标签根本不起作用。它不显示任何警报,只是空白。就像我从未将标签添加到文件中一样。这是我的代码:

Connector.java:

package connect;

import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import products.Product;

/**
 * Servlet implementation class Connector
 */
@WebServlet("/Connector")
public class Connector extends HttpServlet {
    private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Connector() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */
    @SuppressWarnings({ "unchecked", "null", "unused" })
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        PrintWriter out = response.getWriter();  
        try {
            Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");  
            String url = "jdbc:sqlserver://\\\\.\\pipe\\MSSQL$SQLEXPRESS\\sql\\query:8888;databaseName=ShoppingDB";
            Connection con = DriverManager.getConnection(url,"sa","33887899");
            Statement stmt = con.createStatement();  
            ArrayList<Product> pro=new ArrayList<Product>();
            ResultSet rs=stmt.executeQuery("select * from Products");
            Product p = new Product();
            while(rs.next()) {
                p.setId(rs.getInt("product_id"));
                p.setName(rs.getString("product_name"));
                p.setDes(rs.getString("product_des"));
                p.setPrice(rs.getInt("product_price"));
                p.setSrc(rs.getString("product_img_source"));
                p.setType(rs.getString("product_type"));
                p.setBrand(rs.getString("product_brand"));
                p.setAmount(1000);
                pro.add(p);
            }
            Product re;
            String name=request.getParameter("search");
            for(int i =0;i<pro.size();i++) {
                if(pro.get(i).getName()==name) {
                    re=pro.get(i);
                    break;
                }
            }
            p=pro.get(0);
            ServletContext context=getServletContext();
            context.setAttribute("p", p);
        }catch(Exception e) {
            out.println(e);
        }
        
    }
    
    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        doGet(request, response);
    }

}

Home.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<link rel="stylesheet" href="Style.css">
</head>
<body style="background-color:#f5f5f5;">
    <h1 style="text-align:center">PRJ321X_202x</h1>
    <div id="nav">
        <button class="navbtn">Home</button>
        <button class="navbtn">Products</button>
        <button class="navbtn">About Us</button>
        <button class="navbtn" style="float:right;" onclick="location.href='Login.jsp'">Log in</button>
        <form style="float:right;" method="Post" action="Connector">
            <input name="search" id="search" type="text" placeholder="Search..">
            <input type="submit" style="display:none">
        </form>
        
    </div>
    <script src="Script.js"></script>
<div style="float:left;width:75%;margin-right:5px;" id="products">
    <div>
        <c:out value="${p.id}"/>
    </div>
</div>
<div style="float:left;width:24%">
    <div style="background-color:white;width:100%">
        <h3>Shopping cart</h3>
        <div style="height:2.5cm;background-color:#8f8d8d;width:100%">Your cart is currently empty</div>
    </div>
    <div style="background-color:white;width:100%">
        <h4>Popular products or banner</h4>
        <p>Iphone 11 Pro Max</p>
        <img src="11PM.jpg" style="width:50%">
        <p>Iphone 12 Pro Max</p>
        <img src="12PM.jpg" style="width:50%">
        <p>Samsung Galaxy S20</p>
        <img src="S20.jpg" style="width:50%">
    </div>
</div>

</body>
</html>

【问题讨论】:

    标签: java html jsp servlets


    【解决方案1】:

    在你的servlet中你正在做

    context.setAttribute("p", p);
    

    但是在你的 JSP 中你正在做:

    <c:out value="${s.id}"/>
    

    显然,你的名字必须匹配并且标签应该是:

    <c:out value="${p.id}"/>
    

    我注意到的另一件事是您没有分派到 JSP。你需要对你的 JSP 做一个requestDispatcher.forward()

    这是使一切正常的最小示例:

    小服务程序:

    package connect;
    
    import java.io.IOException;
    
    import javax.servlet.RequestDispatcher;
    import javax.servlet.ServletContext;
    import javax.servlet.ServletException;
    import javax.servlet.annotation.WebServlet;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    
    import products.Product;
    
    @WebServlet("/Connector")
    public class Connector extends HttpServlet {
        private static final long serialVersionUID = 1L;
    
        protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            Product p = new Product();
            p.setId(1234);
            
            ServletContext context = getServletContext();
            context.setAttribute("p", p);
    
            RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Home.jsp"); // <--- your path here
            requestDispatcher.forward(request, response);
        }
    }
    

    如果您的 Home.jsp 文件位于其他路径上,请相应更改以上内容。

    Home.jsp:

    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
    <c:out value="${p.id}" />
    

    话虽如此,你的控制器代码上有几个 cmets。

    首先,除非你知道自己在做什么,否则不要使用@SuppressWarnings。根据你的代码,你是初学者,所以这个注解可以隐藏很多你应该注意的问题。

    您在代码中使用输出流PrintWriter out = response.getWriter();,但仅在代码失败时将异常消息写入其中。如果您的代码有效,不仅您不使用您的 JSP,而且您也不使用此 out 对象来编写响应以发送给客户端。所以关于生成响应,你的 servlet 什么也没做,所以什么也没显示。

    如果您正在搜索产品,您可以编写 WHERE 子句并仅检索您正在搜索的内容,而不是获取数据库中的所有产品然后循环访问它们。确保在构建查询时使用 prepared statement parameters。不要连接字符串来构建您的 SQL 查询。这可能会导致SQL injection 漏洞。

    您正在循环浏览产品结果列表,但您在 while 循环之外声明您的产品对象。这样做的结果是您的数组将仅填充此引用对象,该引用对象将指向具有从数据库中检索到的最后一个值的对象。您需要将产品创建移动到 while 循环内,如下所示:

    while (rs.next()) {
        Product p = new Product();
        p.setId(rs.getInt("product_id"));
        // all the other props
        pro.add(p);
    }
    

    您正在使用Product re; 引用来搜索您的产品,但您从未使用它,因为您执行p=pro.get(0); 以从您的列表中获取第一个产品,并且您使用p 放置在上下文中JSP。我假设您的意思是改用re

    不要将字符串与== 进行比较。这段代码:

    if (pro.get(i).getName() == name) {
    

    应该是这样的:

    if (pro.get(i).getName().equalsIgnoreCase(name)) {
    

    更重要的是,您需要确保自己免受 NullPointerExceptions 的影响,以防getName() 也可以返回 null。如果您使用 WHERE SQL 子句,则无需再次循环并搜索产品。

    最后,您应该阅读一些有关您正在使用的概念和代码的书籍或文档。您可能最终能够在不完全了解发生了什么的情况下将某些东西放在一起,但这可能不一定是您所期望的。

    【讨论】:

    • 我试过这样做,但它也不起作用
    • 我仔细查看了您的代码,发现您没有使用您的 JSP。请参阅上面的更新。我还注意到其他一些问题,因此我将编辑我的答案以添加一些指针。
    • 谢谢,成功了,我欠你我的大学证书
    • 不客气。但是不要再支持我所有的答案了:)。你可能会因为这样做而阻止你的帐户...
    • 你认为一个 SO 帐户比大学证书更重要吗?此外,这只是一个克隆所以......但我会停下来,所以别担心
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-12-23
    • 1970-01-01
    • 2012-06-19
    相关资源
    最近更新 更多