如何链接 JSP、servlet 和 Java 视图 bean?我不想在 JSP 中有任何脚本。我如何要求我的 JSP 调用 servlet 来设置隐式请求和响应对象,然后在 jsp 上显示来自视图 bean 的属性。
我需要将请求和响应对象从 jsp 传递到 servlet,然后我想将视图 bean 中定义的属性显示到 JSP 页面。
JSP -> Servlet -> 查看 Bean -> JSP
如何做到这一点?
无需向 bean/model 传递请求和响应,因为您的模型类是在或中实例化的。JSPs
Servlets
您必须选择以 servlet 为中心的方法。
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
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);
}
}
视图.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>
索引.jsp
<h1>
<a href="view">View Employee details</a>
</h1>