本节目录:
1、如何从Servlet向JSP传送数据:(setAtrribute和getAtrribute)
2、jsp如何输入表达数据以及传数据到servlet(FormAction去向和InputType输入)
1、如何从Servlet向JSP传送数据:
Servlet中的doget和dopost中设置:(使用request.setAttribute和 request.getRequestDispatcher说明传递的数据和要传递的页面)
//CatServlet的servlet
public class CatServlet extends HttpServlet {
private BaseDAO baseDAO = new BaseDAO();
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
request.setAttribute("catList", baseDAO.list(" from Cat "));
request.getRequestDispatcher("/listCat.jsp").forward(request, response);
}
}
表示将baseDAO.list(" from Cat ")的数据存到一个名为catList的变量中;
然后跳转到 listCat.jsp页面,同时将数据catList也传统过来啦。
然后在listCat.jsp中就可以使用catList的数据了(使用request.getAttribute);
${ msg } --%>所有 Cat 列表 [添加 Cat][Cat 列表]
ID | Name | Description | Mother | Operation |
---|
List catList = (List) request.getAttribute("catList");//将数据catList取出来的命令;存在本页面;然后才有后续的操作;for(Cat cat : catList) {
out.write("
");out.write("
" + cat.getId() + "");out.write("
" + cat.getName() + "");out.write("
" + cat.getDescription() + "");String motherString= "";
Cat mother=cat.getMother();while(mother != null){if(motherString.trim().length() == 0)
motherString=mother.getName();elsemotherString= mother.getName() + " / " +motherString;
mother=mother.getMother();
}
out.write("
" + motherString + "");out.write("
");out.write(" 删除");
out.write(" 修改");
out.write("
");out.write("
");}%>
2、jsp如何输入表达数据以及传数据到servlet:一般就是在JSP页面的Form
(1)比如下面这种,Form表示下面的表单,作用范围是
**** 包含的区域(2)Form Action=给出了数据转向的方向,可以是servlet程序,也可以是另外一个jsp文件;
比如下面的将表单填写的数据给到servlet程序去处理:
Name: | |
Mother: | ---请选择--- List catList = (List) request.getAttribute("catList");for(Cat cat : catList) { out.write(" "); String name=cat.getName(); Cat mother=cat.getMother();while(mother != null){ name= mother.getName() + " / " +name; mother=mother.getMother(); } out.write("" + name + ""); out.write(""); }%> |
Description: | ${ cat.description } |