如何链接一个JSP,servlet和一个Java视图bean? [英] How to link a JSP ,servlet and a Java view bean?
问题描述
如何链接JSP,servlet和Java视图bean? 我不想在JSP中有任何脚本.我怎样才能让我的JSP调用servlet来设置Implicit请求和响应对象,然后在jsp上显示view bean的属性.
How to link a JSP ,servlet and a Java view bean? I donot want to have any scriplet in JSP. How can i ask my JSP to invoke servlet to set the Implicit request and response objects and then display the properties from view bean on the jsp.
我需要将请求和响应对象从jsp传递到servlet,然后要将在view bean中定义的属性显示到JSP页面.
I need to pass request and response objects from jsp to servlet and then i want to display the properties defined in view bean to a JSP page.
JSP-> Servlet-> View Bean-> JSP
JSP -> Servlet -> View Bean -> JSP
如何实现这一目标?
推荐答案
无需将请求和响应传递给 bean/model 因为您的模型类是在JSPs
或Servlets
中实例化的.
No need to pass request and response to the bean/model because your model classes are instantiated either in JSPs
or Servlets
.
您必须选择以servlet为中心的方法.
ViewBean.java
ViewBean.java
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;}
}
ViewServlet.java
ViewServlet.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);
}
}
view.jsp
<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>
index.jsp
index.jsp
<h1>
<a href="view">View Employee details</a>
</h1>
这篇关于如何链接一个JSP,servlet和一个Java视图bean?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!