使用Session与Servlet和JSP中的对象

时间:2016-11-30 09:19:04

标签: java spring servlets

有人可以简要地向我解释如何传递一个对象并稍后在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;
    }



}

1 个答案:

答案 0 :(得分:0)

您需要导入您班级所在的页面        &lt;%@ page import =&#34; com.servlet.java。*&#34;%&gt;