更新時間:2016年06月10日17時24分 來源:傳智播客Java培訓學院 瀏覽次數(shù):
/** * 把數(shù)據(jù)庫中查詢出的結(jié)果保存到這個對象中。 * @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中的數(shù)據(jù)查詢出來之后,封裝到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完成功能,把結(jié)果保存到request中 * 轉(zhuǎn)發(fā)到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> |