ToB企服应用市场:ToB评测及商务社交产业平台

标题: 4.Java Web开发模式(javaBean+servlet+MVC) [打印本页]

作者: 祗疼妳一个    时间: 2024-7-28 01:48
标题: 4.Java Web开发模式(javaBean+servlet+MVC)
Java Web开发模式

一、Java Web开发模式

1.javaBean简介

   JavaBeans是Java中一种特殊的类,可以将多个对象封装到一个对象(bean)中。特点是可序列化,提供无参构造器,提供getter方法和setter方法访问对象的属性。名称中的“Bean”是用于Java的可重用软件组件的惯用叫法。 --from 维基百科
  JavaBean是一种可重复使用、且跨平台的软件组件。JavaBean可分为两种:

1)特点:

2.开发模式分类


1)模式一特点


2)模式二特点

   模式 二 体系布局联合使用 JSP 页面、Servlet和 JavaBean 来开发 Web 应用步伐
  二、MVC模式

1.简介

MVC是英文“Model-View-Controller”的缩写,最初是在Smalltalk-80中被用来构建用户界面的。此中M代表模型Model,V代表视图View,C代表控制器Controller。
   通过模型视图控制器来
  采用MVC模式的目的,就是为了增长代码的重用率,淘汰数据表达、数据描述和提高应用操作的偶合度。同时也使得软件的可维护性、可修复性、可扩展性、机动性以及封装性大大提高。
2.MVC模式布局

MVC,把一个应用的输入、处理、输出流程按照Model、View、Controller的方式举行分离,这样一个应用将被分成三层:模型层、视图层、控制层。
        controller负责处理客户端发送的请求,颠末service层业务处理并间接调用mapper接口层的数据库操作,后将效果返回给视图层
   客户端请求>>controller>>service>>mapper
   


1)Model层

分为: DAO层、service层
2)View层

   负责处理用户界面的表现细节,以及怎样向用户展示业务处理的效果(页面效果)
  1. <%@ page import="com.woniuxy.hrms.entity.Hr" %>
  2. <%@ page import="java.util.List" %>
  3. <%@ page contentType="text/html;charset=UTF-8" language="java" %>
  4. <%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
  5. <%
  6.     String path = request.getContextPath();
  7.     String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/";
  8. %>
  9. <base href="<%=basePath%>"/>
  10. <!DOCTYPE html>
  11. <head>
  12.     <meta charset="UTF-8">
  13.     <title>Title</title>
  14. </head>
  15. <link rel="stylesheet" type="text/css" href="static/bootstrap/css/bootstrap.min.css">
  16. <script type="text/javascript" src="static/bootstrap/js/bootstrap.min.js"></script>
  17. <script type="text/javascript" src="static/bootstrap/js/jquery.min.js"></script>
  18. <script type="text/javascript">
  19.     function check(id) {
  20.         var flag = confirm("确认要删除吗?");
  21.         if (flag) {
  22.             //删除确认,服务器请求跳转至delete方法处理数据库数据
  23.             location.href = "hr/delete?id=" + id;
  24.         }
  25.     }
  26. </script>
  27. <body>
  28. <div class="container" style="padding-top: 40px;">
  29.     <div class="form-group">
  30.         <div class="row">
  31.             <div class="col-md-8">
  32.                 <form id="searchForm" action="hr/queryByUsername" method="post">
  33.                     <input type="text" class="form-control" id="selectUserName" name="username"
  34.                            placeholder="请输入用户名"/>
  35.                     <button type="submit" class="btn btn-danger search" id="searchBtn">搜索</button>
  36.                 </form>
  37.             </div>
  38.             <div class="col-md-3">
  39.                 <a class="btn btn-round btn-square btn-default" href="manage/hr/add.jsp">添加<i
  40.                         class="mdi mdi-eye"></i></a>
  41.                 <!--  <button class="btn btn-default add" data-toggle="modal" data-target="#addModel">增加</button>-->
  42.             </div>
  43.         </div>
  44.     </div>
  45.     <%
  46.         List<Hr> list = (List<Hr>) request.getAttribute("list");
  47.     %>
  48.     <table class="table table-bordered text-center">
  49.         <tr>
  50.             <td>编号</td>
  51.             <td>姓名</td>
  52.             <td>用户名</td>
  53.             <td>电话</td>
  54.             <td>地址</td>
  55.             <td>操作</td>
  56.         </tr>
  57.         <%--        迭代集合--%>
  58.         <%
  59.             for (Hr hr : list) {
  60.         %>
  61.         <tr>
  62.             <td><%=hr.getId()%>
  63.             </td>
  64.             <td><%=hr.getRealName()%>
  65.             </td>
  66.             <td><%=hr.getUsername()%>
  67.             </td>
  68.             <td><%=hr.getPhone()%>
  69.             </td>
  70.             <td><%=hr.getAddress()%>
  71.             </td>
  72.             <td>
  73.                 <%--                点击编辑链接,传递当前对象id,并向服务器发送请求--%>
  74.                 <%-- href="hrms/queryById?id=<%=hr.getId()%        查询字符串以?字符开始       --%>
  75.                 <%--                <%=hr.getId()%>jsp脚本表达式    --%>
  76.                 <a class="btn btn-round btn-square btn-info" href="hr/queryById?id=<%=hr.getId()%>">编辑<i
  77.                         class="mdi mdi-eye"></i></a>
  78.                 <a class="btn btn-round btn-square btn-warning" href="javascript:check(<%=hr.getId()%>)">删除<i
  79.                         class="mdi mdi-eye"></i></a>
  80.             </td>
  81.         </tr>
  82.         <%
  83.             }
  84.         %>
  85.     </table>
  86. </div>
  87. </body>
  88. </html>
复制代码
3)Cotroller层

   处理客户端请求
    叫做控制层,重要的功能是处理用户发送的请求。
  负责协调视图与模型,在两者之间处于桥梁和纽带的位置
  1. public class BaseServlet extends HttpServlet {
  2.     //HttpServlet生命周期: 初始化init(),服务运行service(),销毁destroy()
  3.     //1.init()仅加载一次
  4.     //2.service()随时响应客户端请求,每次获取请求对象调用此方法
  5.     //3.destroy()仅调用一次, 释放servlet所占用的资源。如关闭文件输入输出流,关闭与数据库的连接。
  6.     //多次调用,每次服务器获取请求对象调用service方法,随时响应客户端请求
  7.     @Override
  8.     protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  9.         //获取请求路径
  10.         String requestURI = req.getRequestURI();
  11.         //检索请求路径最后的方法名
  12.         String methodName = requestURI.substring(requestURI.lastIndexOf("/") + 1);
  13.         Method declaredMethod;
  14.         try {
  15.             //动态调用对象方法
  16.             declaredMethod = this.getClass().getDeclaredMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
  17.             declaredMethod.invoke(this, req, resp);
  18.         } catch (NoSuchMethodException | InvocationTargetException | IllegalAccessException e) {
  19.             throw new RuntimeException(e);
  20.         }
  21.     }
  22. }
复制代码
  1. @WebServlet(value = "/hr/*", loadOnStartup = 1)
  2. public class HrServlet extends BaseServlet {
  3.     HrService hrService;
  4.     @Override
  5.     public void init(ServletConfig config) throws ServletException {
  6.         ClassPathXmlApplicationContext applicationContext = new ClassPathXmlApplicationContext("spring-config.xml");
  7.         //config.getServletContext()创建ServletContext对象,用来存储applicationContext对象,整个Web应用范围内访问它
  8.         config.getServletContext().setAttribute("applicationContext", applicationContext);
  9.         hrService = applicationContext.getBean("hrService", HrService.class);
  10.     }
  11.     protected void queryByUsername(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  12.         String username = req.getParameter("username");
  13.         List<Hr> list = hrService.queryByUsername(username);
  14.         list.forEach(System.out::println);
  15.         req.setAttribute("list", list);
  16.         req.getRequestDispatcher("../manage/hr/show.jsp").forward(req, resp);
  17.     }
  18.     protected void queryAll(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  19.         List<Hr> list = hrService.queryAll();
  20.         req.setAttribute("list", list);
  21.         req.getRequestDispatcher("../manage/hr/show.jsp").forward(req, resp);
  22.     }
  23.     protected void add(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  24. //        req.setCharacterEncoding("utf-8");
  25.         Hr hr = new Hr();
  26.         hr.setRealName(req.getParameter("realName"));
  27.         hr.setUsername(req.getParameter("username"));
  28.         hr.setAddress(req.getParameter("address"));
  29.         hr.setPhone(req.getParameter("phone"));
  30.         System.out.println(hr);
  31.         int i = hrService.insertSelective(hr);
  32.         //数据库添加数据,并重新调用queryAll走页面展示流程
  33.         queryAll(req, resp);
  34.     }
  35.     protected void queryById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  36.         String id = req.getParameter("id");
  37.         Hr hr = hrService.selectByPrimaryKey(Long.parseLong(id));
  38.         req.setAttribute("hr", hr);
  39. //        跳转页面,带着对象forward(),地址栏不变
  40.         req.getRequestDispatcher("../manage/hr/update.jsp").forward(req, resp);
  41. //        单纯跳转页面,并不能携带对象,地址栏更新
  42. //        resp.sendRedirect("/hr/update.jsp");
  43.     }
  44.     protected void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  45. //        req.setCharacterEncoding("utf-8");
  46.         Hr hr = new Hr();
  47.         //更新必须有id,负责更新所有内容,依据id更新
  48.         //  where dept_id = #{deptId,jdbcType=INTEGER}
  49.         //获取页面update.jsp请求对象传递的参数
  50.         hr.setId(Integer.parseInt(req.getParameter("id")));
  51.         hr.setRealName(req.getParameter("realName"));
  52.         hr.setUsername(req.getParameter("username"));
  53.         hr.setAddress(req.getParameter("address"));
  54.         hr.setPhone(req.getParameter("phone"));
  55.         int update = hrService.updateByPrimaryKeySelective(hr);
  56.         //更新完显示全部数据(查询全部数据反馈给show.jsp)
  57.         queryAll(req, resp);
  58.     }
  59.     protected void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  60.         String id = req.getParameter("id");
  61.         hrService.deleteByPrimaryKey(Long.parseLong(id));
  62.         queryAll(req, resp);
  63.     }
  64.     protected void login(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
  65.         //负责处理login.jsp提交
  66.         //获取提交对象的username和password
  67.         String username = req.getParameter("username");
  68.         String password = req.getParameter("password");
  69.         Hr hr = hrService.login(username, password);
  70.         //
  71.         HttpSession session = req.getSession();
  72.         session.setAttribute("hr", hr);
  73.         if (hr != null) {
  74.             //本地存储,在浏览器存储数据
  75.             Cookie[] cookies = req.getCookies();
  76.             boolean flag = false;
  77.             for (Cookie cookie : cookies) {
  78.                 String name = cookie.getName();
  79.                 if (name.equals("username")) {
  80.                     flag = true;
  81.                 }
  82.             }
  83.             if (!flag) {
  84.                 Cookie username1 = new Cookie("username", username);
  85.                 Cookie password1 = new Cookie("password", password);
  86.                 //设置cookie存储路径
  87.                 username1.setPath("/hrms");
  88.                 password1.setPath("/hrms");
  89.                 username1.setMaxAge(60 * 60 * 24);
  90.                 password1.setMaxAge(60 * 60 * 24);
  91.                 resp.addCookie(username1);
  92.                 resp.addCookie(password1);
  93.             }
  94.             //路径可以: ../或/hrms根路径下的页面
  95.             resp.sendRedirect("/hrms/admin.jsp");
  96.         } else {
  97.             resp.sendRedirect("../login.jsp");
  98.         }
  99.     }
  100. }
复制代码
3.MVC的长处:


4.MVC框架

规则。

4.MVC框架


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4