Servlet,JSP传递属性

时间:2016-06-22 07:03:27

标签: jsp servlets

我试图将属性从servlet传递给JSP。我想在JSP中显示Hello World。它总是返回null。它永远不会得到属性x,它表示应该显示hello world的次数。 我不知道自己做错了什么。这是我在servlet中的代码。

   public class HelloIbaServlet extends HttpServlet {

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {

        int x = 1;
        if (req.getParameter("x") != null) {
            try {
                x = Integer.parseInt(req.getParameter("x"));
            } catch (NumberFormatException ex) {
                x = 1;
            }
        }
        req.setAttribute("x", x);
        req.getRequestDispatcher("/index.jsp").forward(req, resp);
    }

}

这是我的JSP。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@page import="com.mycompany.servlets.HelloIbaServlet"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html>

    <html>
        <head>
            <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        </head>
        <body>
            <c:forEach begin="1" end="${x}">
                <h1>Hello world!</h1>
            </c:forEach>
        </body>
    </html>

我的依赖是

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.1.2</version>
        </dependency>
        <dependency>
            <groupId>taglibs</groupId>
            <artifactId>standard</artifactId>
            <version>1.1.2</version>
        </dependency>  
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>servlet-api</artifactId>
            <version>2.5</version>
            <scope>provided</scope>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
        </dependency>

我的web.xml

<web-app version="2.4" xmlns="http://java.sun.com/xml/ns/j2ee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee  http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">
    <servlet>
        <servlet-name>HelloIbaServlet</servlet-name>
        <servlet-class>com.mycompany.servlets.HelloIbaServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>HelloIbaServlet</servlet-name>
        <url-pattern>/sayhello</url-pattern>
    </servlet-mapping>
</web-app>

0 个答案:

没有答案