JavaWeb学习笔记(四)三层架构

版权声明:本文为博主原创文章,遵循 CC 4.0 by-sa 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/weixin_37717513/article/details/90232210

JavaWeb的三层架构

  • Web层:与Web相关的内容(JSP、Servlet及相关API:request、respond、session、ServletContext)
  • 业务层:Service,只包含业务逻辑
  • 数据层:对数据库的所有操作
    JavaEE中称为表现层、业务层、持久层

简单得获取数据三层框架

数据库Dao层

package com.test.dao;

import com.test.domain.User;

/*
 *  1 操作数据库Dao层
 */
public class UserDao {

	// 添加数据addUser();
	// 删除数据deleteUser();
	// 更改数据updataUser();
	// ...

	// 查找数据
	public User getUser() {
		return new User("jia", "123");
	}

}

实体类

package com.test.domain;

/*
  *  数据库对应实体类
 */
public class User {
	private String name;
	private String password;

	@Override
	public String toString() {
		return "User [name=" + name + ", password=" + password + "]";
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public User(String name, String password) {
		super();
		this.name = name;
		this.password = password;
	}

}

业务层

package com.test.service;

import com.test.dao.UserDao;
import com.test.domain.User;

/*
 * Service业务层
 * Service业务层依赖与数据库Dao层,需要Dao对象
 */
public class UserService {
	UserDao userDao = new UserDao();

	// 查找用户信息
	public User find() {
		return userDao.getUser();
	}
	// 有的业务层逻辑需要进行多次数据库操作,在这里进行整理

}

Web层

package com.test.servlet;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.test.domain.User;
import com.test.service.UserService;

/*
 * Web层Servlet中依赖service,通过service完成功能,把结果保存到request中转发到jsp中
 */
@WebServlet(asyncSupported = true, urlPatterns = { "/UserServlet" })
public class UserServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;

	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		UserService userService = new UserService();
		User user = userService.find();

		request.setAttribute("user", user);
		request.getRequestDispatcher("/show.jsp").forward(request, response);

//		request.setAttribute("user", user);
//		request.getRequestDispatcher("/show.jsp").forward(request, response);
	}

}

显示页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
用户名:${user.name} 
密码: ${user.password}
</body>
</html>

最后访问http://localhost:8080/UserDirect/UserServlet就能得到数据

展开阅读全文

没有更多推荐了,返回首页