[英]Use a created object in servlet in JSP/forward object from servlet to JSP
如标题所示,我试图使用在JSP的servlet中创建的相同对象。 该对象是一个模型(称为“客户”),用于保存值/数据。我正在servlet中设置值,并在我的JSP中获取/打印它们。
我尝试在JSP中创建一个新对象,但是该值变为null。
目前,customer类中的变量和get方法是静态的。 这可行,但我不希望它们是静态的。 为此,我必须在servlet中获取现有对象,然后在JSP中重新使用它。
在有人说我应该读书之前,请相信我。 我只是不正确地理解它,我希望有人来帮助我。 请。
据我所知:
Servlet:
String firstName = request.getParameter("förnamn");
Customer control = new Customer ();
control.setFirstName(firstName);
HttpSession session = request.getSession();
session.setAttribute("förnamn", firstName);
request.setAttribute("control", control);
RequestDispatcher view = request.getRequestDispatcher("result.jsp");
view.forward(request, response);
这是客户类别:
private static String firstName;
public static String getFirstName() {
return firstName;
}
public static void setFirstName(String firstName) {
Customer.firstName = firstName;
}
这是我的JSP:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!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=UTF-8">
<title>Your information in JSP Format:</title>
<%@ page import="Abdi.Customer" %>
<%HttpSessionListenerTest http = new HttpSessionListenerTest();%>
</head>
<body>
<ul>
<li><p><b>Last Name:</b>
<%= Customer.getFirstName() // i want to print it, without using static methods%>
</p></li>
</ul>
您的客户类别存在问题。 您已将所有实例变量设为私有静态,并可以访问它们的公共静态方法。 在您的情况下,无论您使用new Customer()创建了多少个客户对象,都将只有一个firstName变量。 静态表示每个类定义一个
将客户类中的变量设为私有,并使用公共设置器/获取器来改变状态。 完成此操作后,您可以简单地将它们作为属性添加到请求/会话/应用程序范围中的servlet中,转发到JSP并使用Expresssion Language(EL)或JSTL访问它们。 停止使用scriptlet,它们已经90了。
在您的Servlet中,
String firstName = request.getParameter("förnamn");
Customer customer = new Customer ();
customer.setFirstName(firstName);
HttpSession session = request.getSession();
session.setAttribute("customer", customer);
-转发到JSP ----
在您的JSP中,只需使用EL
${customer.firstName}
通常, ${yourAttributeName.yourPropertyNameFromPOJO}
请注意,我没有提到fName属性的范围。 它将搜索从页面->请求->会话->应用程序开始的所有有效范围
如果使用$不能解析这些值,则EL关闭。 您可以像这样在页面指令中使用isELIgnored属性启用它
<%@ page language="java" isELIgnored="false" %>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.