2016-11-30 81 views
-1

有人能够向我简要介绍一下如何传递一个对象并在稍后的JSP中使用它。在使用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; 
    } 



} 

回答

0

您需要导入在你的类存在
<%@页面进口=“com.servlet.java页面。*“%>

相关问题