gpt4 book ai didi

jsp - 将自定义对象从 servlet 传递到 JSP

转载 作者:行者123 更新时间:2023-12-03 05:08:58 25 4
gpt4 key购买 nike

我想将 Student 类型的自定义对象从 servlet 传递到 JSP。我创建了一个学生 bean 类。 Student 包含 2 个属性firstname 和lastName。

学生 bean :

import java.io.Serializable;

public class Student implements Serializable {

public Student() {
}

String firstName;
String lastName;

public String getFirstName() {
return firstName;
}

public void setFirstName(String firstName) {
this.firstName = firstName;
}

public String getLastName() {
return lastName;
}

public void setLastName(String lastName) {
this.lastName = lastName;
}

}

用于从用户处获取名字和姓氏的 HTML 文件:

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
</head>
<body>
<form id="myForm" method="POST" action="MyFormServlet">
FirstName<input type="text" id="firstName" name="FirstName"/><br>
LastName<input type="text" id="lastName" name="LastName"/><br>
<button type="submit" />Submit</button>
</form>
</body>
</html>

Servlet 代码:

import javax.servlet.RequestDispatcher;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;



public class MyFormServlet extends HttpServlet {

@Override
protected void doPost(HttpServletRequest request,
HttpServletResponse response) {

Student s = new Student();
s.setFirstName(request.getParameter("FirstName"));
s.setLastName(request.getParameter("LastName"));

HttpSession session =request.getSession();
session.setAttribute("student", s);

try {
RequestDispatcher rd = getServletContext().getRequestDispatcher("/myJsp.jsp");
rd.forward(request, response);
} catch (Exception e) {
e.printStackTrace();
}
}

}

myJsp.jsp

<%@ 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">
</head>
<body>
<%
// I want to do something like this :
//Student student =(Student)session.getAttribute("student");
//String fullName=student.firstName + student.lastName;
%>
<h1><%=fullName%></h1>
</body>
</html>

我想要获取“student”对象,访问其属性并将其存储在 JSP 变量中以供进一步处理。

最佳答案

setAttribute()方法request , sessionservletContext已经将其作为 JSP 提供。/EL通过属性名称变量。

在您的特定情况下,在 servlet 中使用以下行,

session.setAttribute("student", s);

它在 JSP/EL 中可用 ${student} 。所以,应该这样做:

<body>
<h1>${student.firstName} ${student.lastName}</h1>
</body>

如果您想将其存储为 JSP 中的另一个变量以便可以多次重复使用它,请使用 JSTL <c:set> .

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
...
<body>
<c:set var="fullName" value="${student.firstName} ${student.lastName}" />
<h1>${fullName}</h1>
</body>

关于jsp - 将自定义对象从 servlet 传递到 JSP,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10296098/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com