更新时间:2016年06月10日17时24分 来源:传智播客Java培训学院 浏览次数:
/** * 把数据库中查询出的结果保存到这个对象中。 * @author cxf * */ public class User { private String username; private String password; public User(String username, String password) { this.username = username; this.password = password; } public User() { super(); // TODO Auto-generated constructor stub } 此处省略username和password的get/set方法 @Override public String toString() { return "User [username=" + username + ", password=" + password + "]"; } } |
public class UserDao { /* * 把xml中的数据查询出来之后,封装到user对象中,然后返回 */ public User find() { return new User("zhangSan", "123"); } } |
public class UserService { // service层依赖dao层 private UserDao userDao = new UserDao(); /* * service的查询,需要使用dao来完成! */ public User find() { return userDao.find(); } } |
public class UserServlet extends HttpServlet { public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { /* * 在servlet中依赖service,然后通过service完成功能,把结果保存到request中 * 转发到jsp显示。 */ UserService userService = new UserService(); User user = userService.find(); request.setAttribute("user", user); request.getRequestDispatcher("/show.jsp").forward(request, response); } } |
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'index.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> <a href="<c:url value='/UserServlet'/>">点击这里查看</a> </body> </html> |
<%@ page language="java" import="java.util.*" pageEncoding="UTF-8"%> <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"> <html> <head> <title>My JSP 'show.jsp' starting page</title> <meta http-equiv="pragma" content="no-cache"> <meta http-equiv="cache-control" content="no-cache"> <meta http-equiv="expires" content="0"> <meta http-equiv="keywords" content="keyword1,keyword2,keyword3"> <meta http-equiv="description" content="This is my page"> </head> <body> 用户名:${user.username }<br/> 密 码:${user.password }<br/> </body> </html> |