将自定义对象从servlet传递到JSP [英] Passing custom objects from servlet to JSP

查看:89
本文介绍了将自定义对象从servlet传递到JSP的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将Student类型的自定义对象从servlet传递到JSP. 我创建了一个Student 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>

我想获取学生"对象,访问其属性并将其存储在JSP变量中以进行进一步处理.

解决方案

requestsessionservletContext上的setAttribute()方法已经可以作为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>

I want to pass a custom object of type Student from a servlet to JSP. I have created a Student bean class. Student contains 2 properties firstname and lastName.

Student 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 file for taking FirstName and LastName from the user:

<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 Code:

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>

I want to get the 'student' object, access its attributes and store it in a JSP variable for further processing.

解决方案

The setAttribute() method on request, session and servletContext will already make it available as a JSP/EL variable by the attribute name.

In your particular case, with the following line in the servlet,

session.setAttribute("student", s);

it's available in JSP/EL as ${student}. So, just this should do:

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

If you want to store it as another variable in JSP so that you can reuse it multiple times, use 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>

这篇关于将自定义对象从servlet传递到JSP的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆