如何链接JSP,servlet和Java视图bean?

时间:2012-08-17 06:03:37

标签: java jsp servlets

如何链接JSP,servlet和Java视图bean? 我不想在JSP中有任何scriplet。我怎样才能让我的JSP调用servlet来设置隐式请求和响应对象,然后在jsp上显示view bean的属性。

我需要将请求和响应对象从jsp传递给servlet,然后我想将视图bean中定义的属性显示到JSP页面。

JSP - > Servlet - >查看Bean - > JSP

如何实现这一目标?

1 个答案:

答案 0 :(得分:4)

无需将请求响应传递给 bean / model ,因为您的模型类在JSPsServlets中实例化package in.abc.model; public class Employee{ private Integer id; private String name; public Employee() { id=0; name="";} public Employee(Integer id, String name) { this.id=id; this.name=name;} public Integer getId() { return id;} public String getName() { return name;} public void setId(Integer id) { this.id=id;} public void setName(String name) { this.name=name;} }

您必须选择以servlet为中心的方法。

ViewBean.java


package in.abc.servlets;

@WebServlet(name = "ViewServlet", urlPatterns = {"/view"})
public class ViewServlet extends HttpServlet{
  public doGet(HttpServletRequest request,
               HttpServletResponse response) 
                 throws ServletException, IOException {

         //Instantiate the model 
         Employee emp=new Employee(10,"Mr.A");

         //Insert "model" object to request
         request.setAttribute("emp",emp);

         //forward the request to view.jsp
         request.getRequestDispatcher("/view.jsp").
                  forward(request,response);
  }

 public doPost(HttpServletRequest request,
               HttpServletResponse response) 
                 throws ServletException, IOException {

         //Instantiate the model 
         Employee emp=new Employee();

         //Read the request
         try{
             emp.setId(Integer.parseInt(request.getParameter("id"));
         }catch(Exception ex) {}
         emp.setName(request.getParameter("name"));

         //Insert "model" object to request
         request.setAttribute("emp",emp);

         //forward the request to view.jsp
         request.getRequestDispatcher("/view.jsp").
                  forward(request,response);
  }
}

ViewServlet.java


<h3>Employee info</h3>
<p>ID : ${emp.id}</p>
<p>Name : ${emp.name}</p>

<form method="post" action="view">
   <br/> <input type="text" name="id"/> 
   <br/> <input type="text" name="name"/>
   <br/> <input type="submit"/>
</form>

view.jsp的


<h1>
  <a href="view">View Employee details</a>
</h1>

的index.jsp


{{1}}