JavaEE开发-第四节 JUint、Tomcat部署原理

JUint

  1. 单元测试使用的场景:
    1. 如果一个类中有n个函数,我们想单独测试这些函数怎么办呢?通常我们可以在这个类中新增main方法,在main方法中调用相应的函数。
    2. 缺点:每个类都要写,而且侵入源代码
    3. 那么此时就出现了一种能够解决这种缺点的方法—单元测试
  2. JUnit是Java中最常用的单元测试开源框架,当前使用的是4.13版本
  3. 所需要的jar包
    1. junit-4.13
    2. ham crest-core-2.2
    3. ham crest-2.2
  4. 建议单元测试类的命名格式为:XxTest

常用注解

@Test:正常的测试方法,建议格式是public void testXx()
@Before:在每个@Test方法执行之前执行,建议格式是public void before()
@After:在每个@Test方法执行之后执行,建议格式是public void after()
@BeforeClass:在第一个@Test方法执行之前执行,建议格式是public static void beforeClass()
@AfterClass:在最后一个@Test方法执行之后执行,建议格式是public static void afterClass()

断言类Assert的常用方法

assertTrue
assertFalse
assertEquals
assert Not Equals
assertNotNull
assertNull

代码举例

  1. 新建一个test文件夹与src同级文件夹
    1. 右击击项目文件名->new -> Directory
    2. 这仅仅是一个普通文件夹,不会进行编译
  2. 右击test文件夹->Mar Directory as ->Test Sources Root,表示该文件仅仅是用来测试,不需要打包
  3. 在这个文件夹中添加测试类CustomerDaoTest,专门用于测试CustomerDao类的成员方法

     //左边会有个三角形,点击会执行这个类中所有带@Test的方法
     public class CustomerDaoTest {
         private static CustomerDao dao;
        
         @Before
         public void before() {
             System.out.println("before");
         }
        
         @After
         public void after() {
             System.out.println("after");
         }
            
         //通常方资源的初始化
         @BeforeClass
         public static void beforeClass() {
             dao = new CustomerDao();
             System.out.println("beforeClass");
         }
        
         @AfterClass
         public static void afterClass() {
             System.out.println("afterClass");
         }
        
        
         @Test
         public void testSave() {
             Customer customer = new Customer();
             customer.setName("张武");
             customer.setAge(20);
             customer.setHeight(1.89);
        
             Assert.assertTrue(dao.save(customer));
         }
        
         //用来测试,左边会有个执行三角形,点击即可执行
         @Test
         public void testList() {
             List<Customer> customers = dao.list();
             Assert.assertTrue(customers.size() > 0);
         }
     }
    

封装7

  1. 添加与编辑页面可以使用一个,将update.jsp修改为save.jsp
  2. save.jsp代码如下:

     <%@ page contentType="text/html;charset=UTF-8" language="java" %>
     <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
     <!DOCTYPE html>
     <html lang="zh">
     <head>
         <meta charset="UTF-8">
         <c:choose>
             <c:when test="${empty customer}">
                 <title>添加客户</title>
             </c:when>
             <c:otherwise>
                 <title>编辑客户</title>
             </c:otherwise>
         </c:choose>
         <%--
          <c:if test="${empty customer}">
             <title>添加客户</title>
         </c:if>
         <c:if test="${not empty customer}">
             <title>编辑客户</title>
         </c:if>
         --%>
        
        
     </head>
     <body>
        
     <form action="/crm/customer/save" method="post">
         <c:if test="${not empty customer}">
             <input type="hidden" name="id" value="${customer.id}">
         </c:if>
         <div>姓名 <input type="text" name="name" value="${customer.name}"></div>
         <div>年龄 <input type="text" name="age" value="${customer.age}"></div>
         <div>身高 <input type="text" name="height" value="${customer.height}"></div>
         <div>
             <button type="submit">
                 <c:choose>
                     <c:when test="${empty customer}">添加</c:when>
                     <c:otherwise>更新</c:otherwise>
                 </c:choose>
             </button>
         </div>
     </form>
        
     </body>
     </html>
    
  3. list.jsp中修改

     <a href="/crm/page/save.jsp">添加</a>
    
  4. CustomerServlet改造(删除update方法,改造save方法)

     public void save(HttpServletRequest request, HttpServletResponse response) throws Exception{
            
     //获取客户端发送的参数
     Customer customer = newCustomer(request);
     if (dao.save(customer)){
         //重定向到list
         response.sendRedirect("/crm/customer/list");
     }else {
         //重定向到失败
         forwardError(request,response,"保存用户信息失败");
         }
     }
     public void edit(HttpServletRequest request, HttpServletResponse response) throws Exception{
         Integer id = Integer.valueOf(request.getParameter("id"));
         Customer customer = dao.find(id);
         //转发给jsp
         request.setAttribute("customer",customer);
         request.getRequestDispatcher("/page/save.jsp").forward(request,response);
     }
    
  5. CustomerDao改造

     public class CustomerDao {
         //保存或者更新用户信息
         public  boolean save(Customer customer){
             List<Object> args = new ArrayList<>();
             args.add(customer.getName());
             args.add(customer.getAge());
             args.add(customer.getHeight());
             Integer id = customer.getId();
             String sql;
             if (id == null || id < 1){ //添加
                 sql = "INSERT INTO customer(name, age, height) VALUES(?, ?, ?)";
             }else {//更新
                 sql = "UPDATE customer SET name = ?, age = ?, height = ? WHERE id = ?";
                 args.add(id);
             }
             return Dbs.getTpl().update(sql,args.toArray()) >0;
         }
         //获取用户信息
         public List<Customer> list(){
             String sql = "SELECT id ,name, age, height FROM customer";
             //告诉BeanPropertyRowMapper对象,将rs映射成Customer对象,本质是利用反射
             return Dbs.getTpl().query(sql,new BeanPropertyRowMapper<>(Customer.class));
         }
        
         /**
          * 删除Customer
          * @param id
          * @return
          */
         public boolean remove(Integer id){
             String sql = "DELETE FROM customer WHERE id = ?";
             return Dbs.getTpl().update(sql,id)>0;
         }
         /**
          * 删除Customer
          * @param id
          * @return
          */
         public Customer find(Integer id){
             String sql = "SELECT id ,name, age, height FROM customer WHERE id = ?";
             //直接映射成Customer对象
             return Dbs.getTpl().queryForObject(sql,new BeanPropertyRowMapper<>(Customer.class),id);
         }
     }
    

Tomcat部署原理

  1. 我们用idea创建一个项目,然后添加web模块,然后点击idea的Tomact将这个项目部署到Tomact上,然后运行,就可以访问web项目的内容了,那么它是如何部署的呢?
  2. 我们如何将一个项目不通过idea部署到Tomact上呢?

Tomact部署项目的4种方式

  1. 将web项目整个文件夹,放在%TOMCAT_HOME%/webapps目录中,文件夹名作为ContextPath
    1. %TOMCAT_HOME%/:Tomcat的安装目录根路径
    2. web项目编译后的文件夹:比如06_crm项目,IDEA编译(build->build artifacts->选择06_crm_war_exploded->build)之后在out/artifacts文件夹下/06_crm_war_exploded文件夹,将该文件夹拖到Tomcat安装目录下的webapps文件夹中
    3. 启动Tomcat:cd到bin目录执行命令sh startup.sh,windows直接双击startup.bat
    4. 浏览器访问:http://localhost:8080/06_crm_war_exploded/customer/list
  2. 将web项目打包成war,放在%TOMCAT_HOME%/webapps目录中,war文件名作为ContextPath
    1. 如何打成war包?
      1. 方法一:手动直接将06_crm_war_exploded文件内容(不包含06_crm_war_exploded文件夹)压缩成zip,然后直接修改后缀名为war,比如crm.war,然后拖入到webapps文件夹中
      2. 方法二:通过Idea打包
        1. 点击Project Structure->Artifacts->点击+->Web Appliaction:Archive(Web Appliaction:exploded这么打出来的包就是06_crm_war_exploded文件夹)->06crm:war exploded->点击OK
        2. 点击build->build artifacts->选择06_crm_war->build
        3. 此时out/artifacts文件夹下生成一个06_crm_war文件夹,内部有个06_crm_war.war文件,可以将文件夹名称改为crm.war
        4. 将该文件拖到Tomcat安装目录下的webapps文件夹中
    2. 步骤同1的3,4
      1. 注意会发现,将crm.war放进去后,自动会解压war,成为crm文件夹
      2. 一旦手动删除crm.war,crm文件夹会自动删除
    3. 浏览器访问:http://localhost:8080/crm/customer/list
  3. %TOMCAT_HOME%/conf/server.xml的Host标签中添加以下内容 (ContextPath是path属性值)
    1. <Context docBase="项目路径"path="/xxx"/>
    2. 比如:

       <Context docBase="/Users/mac/Desktop/JavaStudy/Codes/JavaProject/out/artifacts/06_crm_war_exploded/"  path="/crm"/>
      
    3. 启动Tomcat
    4. 浏览器访问:http://localhost:8080/crm/customer/list
  4. %TOMCAT_HOME%/conf/Catalina/localhost中新建一个xml文件, xml文件名作为ContextPath
    1. <Context docBase="项目路径"/>
    2. 比如:
      1. %TOMCAT_HOME%/conf/Catalina/localhost中新建一个crm.xml
      2. 内容输入:<Context docBase="/Users/mac/Desktop/JavaStudy/Codes/JavaProject/out/artifacts/06_crm_war_exploded/" />
    3. 启动Tomcat
    4. 浏览器访问:http://localhost:8080/crm/customer/list

IDEA是如何实现自动部署?

  1. 运行06_crm项目
  2. 查看server日志:

     CATALINA_BASE:[/Users/mac/Library/Caches/JetBrains/IntelliJIdea2020.1/tomcat/Tomcat_9_0_34_JavaProject_3]
    
  3. cd 进入上面的路径,然后open ./可以看到 conf/Catalina/localhost/crm.xml文件
  4. 本质是告诉Tomcat将安装目录下的文件夹conf路径换到上面的路径了
Table of Contents