【问题标题】:Using objects in Session with Servlets and JSP在 Session 中使用 Servlet 和 JSP 中的对象
【发布时间】:2016-11-30 09:19:03
【问题描述】:

有人可以简单地向我解释一下如何在 JSP 中传递一个对象并稍后使用它。

我有这个 servlet,它能够创建一个新对象并将其存储到会话中。

    package application.servlets.test;

import java.io.IOException;
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 application.data.character.House;

/**
 * 
 * Servlet implementation class SessionTest
 */
@WebServlet("/persons")
public class SessionTest extends HttpServlet {
    private static final long serialVersionUID = 1L;

    /**
     * @see HttpServlet#HttpServlet()
     */
    public SessionTest() {
        super();
        // TODO Auto-generated constructor stub
    }

    /**
     * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
     */

    /**
     * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        House house = new House(34);
        HttpSession session = request.getSession();
        session.setAttribute("House", house);
        request.getRequestDispatcher("test.jsp").forward(request, response);




    }

}

这是第一个将我转发到该 servlet 的 JSP:

    <html>
<body>
<h2>Hello World!</h2>

<form method="post" action="persons">

    <input type="submit", value="Submit"/>

</form>

</body>
</html>

最后,servlet 会将我转发到这个 JSP。我现在如何向它展示 JSP getLevel() 方法。或者任何可以在对象 House 中的方法?如何打印出这些值?

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

    Hello this is just a test

    <h1>Hello ${sessionScope.House}!!!</h1>
    <% Object o = session.getAttribute("House");


    %>


</body>
</html>

以防万一这是我的家庭课程:

    package application.data.character;

public class House {

    private int level;

    public House(int level) {
        super();
        this.level = level;
    }

    public int getLevel() {
        return level;
    }

    public void setLevel(int level) {
        this.level = level;
    }



}

【问题讨论】:

    标签: java spring servlets


    【解决方案1】:

    您需要导入您的班级所在的页面

    【讨论】:

      猜你喜欢
      • 2014-01-09
      • 1970-01-01
      • 2016-05-08
      • 2015-02-15
      • 2020-05-28
      • 2014-06-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多