서블릿에서 JSP로 Student 유형의 맞춤 객체를 전달하려고합니다. 학생용 빈 클래스를 만들었습니다. 학생은 firstname과 lastName이라는 2 개의 속성을 포함합니다.서블릿에서 JSP로 사용자 정의 객체 전달
학생 콩 :
<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>
서블릿 코드 :
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>
사용자로부터 이름 및 성을내어
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 파일
'student'객체를 가져 와서 속성에 액세스하고 추가 처리를 위해 JSP 변수에 저장하려고합니다.