JavaBean 在Servlet 和JSP页面传递

使用Eclipse 创建一个动态页面工程,工程结构如下图。

JavaBean 在Servlet 和JSP页面传递_第1张图片

该工程实现的功能如下:

1.在首页输入数据

2.数据交给HelloSerlet servlet。

3.Servlet 将输入数据封装成JavaBean的格式,保存为Request的属性。

4.将页面转发到main.jsp.

5.main.jsp 用JSP:useBean Tag 使用Servlet 的封装的JavaBean。

6.JSP页面显示JavaBean的数据。


详细代码如下:

1.首页(index.jsp)

<%@ page language="java" contentType="text/html; charset=ISO--1"
    pageEncoding="ISO-8859-1"%>




First Name:


Last Name:






2.Servlet(HelloSerlet)

package com.tomcattest;


import java.io.IOException;


import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;




/**
 * Servlet implementation class HelloSerlet
 */
@WebServlet("/HelloSerlet")
public class HelloSerlet extends HttpServlet {
private static final long serialVersionUID = 1L;
StudentEntity student = new StudentEntity();
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public HelloSerlet() {
        super();
        // TODO Auto-generated constructor stub
    }


/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
student.setFirstName(request.getParameter("first_name"));
student.setSecondName(request.getParameter("last_name"));

RequestDispatcher dispatcher = request.getRequestDispatcher("main.jsp");
request.setAttribute("student", student);
dispatcher.forward(request, response);
}


/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}


}

3.JavaBean 类 (StudentEntity)

package com.tomcattest;


import java.io.Serializable;


public class StudentEntity implements Serializable {


/**

*/
private static final long serialVersionUID = 1L;

public String firstName;
public String secondName;
public String getFirstName() {
return firstName;
}
public void setFirstName(String firstName) {
this.firstName = firstName;
}
public String getSecondName() {
return secondName;
}
public void setSecondName(String secondName) {
this.secondName = secondName;
}




}


4.显示JavaBean信息页面(main.jsp)

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>





JSP Servlet JavaBean



Echo user input






  • First Name:
         



  • Last  Name:
       






你可能感兴趣的:(java)