Apache Maven 高级应用(Part A)(下)

简介: Apache Maven 高级应用(Part A)

创建Mapper层、Service层和Controller层

根据item表的字段来创建Item实体类,新建entity包增加Item实体类

@Data
public class Item {
    private Integer id;
    private String name;
    private Double price;
    private String pic;
    private Date createTime;
    private String detail;
}
复制代码

创建ItemMapper接口,新增mapper文件夹以及ItemMapper接口

public interface ItemMapper {
}
复制代码

在resources目录下创建MyBatis全局配置文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
    <settings>
        <!--开启驼峰命名-->
        <setting name="mapUnderscoreToCamelCase" value="true"/>
    </settings>
</configuration>
复制代码

在resources目录下常见mappers文件夹,在mappers中创建MyBatis SQL Mapper XML文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.lilith.mapper.ItemMapper">
</mapper>
复制代码

在resources目录下创建数据库连接配置文件db.properties

jdbc_driver=com.mysql.cj.jdbc.Driver
jdbc_url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8&autoReconnect=true&useSSL=false&serverTimezone=Asia/Shanghai
jdbc_username=root
jdbc_password=root
复制代码

在resources目录下创建logback.xml配置文件,用于打印执行的SQL

<?xml version="1.0" encoding="UTF-8"?>
<configuration>
   <appender name="console" class="ch.qos.logback.core.ConsoleAppender">
       <encoder>
           <pattern>[%thread] %d{HH:mm:ss.SSS} %-5level %logger{36} - %msg%n</pattern>
       </encoder>
   </appender>
    <root level="debug">
        <appender-ref ref="console"/>
    </root>
</configuration>
复制代码

在WEB-INF下创建Spring MVC配置文件dispatcherServlet-servlet.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-4.3.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/mvc https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    <context:component-scan base-package="com.lilith" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--配置试图解析器,自动拼接页面地址,自动在jsp页面前增加/WEB-INF/pages/-->
    <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/pages/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
    <!-- 默认前端控制器是拦截所有资源(除过jsp),js文件就404了;要js文件的请求是交给tomcat处理的 -->
    <!-- 告诉SpringMVC,自己映射的请求就自己处理,不能处理的请求直接交给tomcat -->
    <!-- 静态资源能访问,动态映射的请求就不行 -->
    <mvc:default-servlet-handler/>
    <!-- springmvc可以保证动态请求和静态请求都能访问 -->
    <mvc:annotation-driven></mvc:annotation-driven>
</beans>
复制代码

在resources目录下创建Spring配置文件application.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context"
       xmlns:tx="http://www.springframework.org/schema/tx" xmlns:jdbc="http://www.springframework.org/schema/jdbc"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
        https://www.springframework.org/schema/beans/spring-beans.xsd
        http://www.springframework.org/schema/util
        http://www.springframework.org/schema/util/spring-util-4.3.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd http://www.alibaba.com/schema/stat http://www.alibaba.com/schema/stat.xsd http://www.springframework.org/schema/tool http://www.springframework.org/schema/tool/spring-tool.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/jdbc http://www.springframework.org/schema/jdbc/spring-jdbc.xsd">
    <!--扫描除了控制器之前的其他包-->
    <context:component-scan base-package="com.lilith">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <!--引用外部配置文件-->
    <context:property-placeholder location="classpath:db.properties"></context:property-placeholder>
    <!--数据库连接池配置-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc_driver}"/>
        <property name="url" value="${jdbc_url}" />
        <property name="username" value="${jdbc_username}"/>
        <property name="password" value="${jdbc_password}"/>
        <!--<property name="initialSize" value="${jdbc_initialSize}"/>-->
        <!--<property name="maxActive" value="${jdbc_maxActive}"/>-->
    </bean>
    <bean id="sqlSessionFactoryBean" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="configLocation" value="classpath:mybatis-config.xml"></property>
        <property name="dataSource" ref="dataSource"></property>
        <property name="mapperLocations" value="classpath:/mappers/*.xml"></property>
    </bean>
    <!--mapper层接口加入到Spring容器-->
    <bean id="mapperScannerConfigurer" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!--指定接口所在的包-->
        <property name="basePackage" value="com.lilith.mapper"></property>
    </bean>
</beans>
复制代码

配置web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--Spring-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:application.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <!--DispatchServlet-->
    <servlet>
        <servlet-name>dispatcherServlet</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>0</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcherServlet</servlet-name>
        <!--"/" 代表拦截所有请求,/*拦截所有请求包括jsp页面这些请求-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
    <!--解决POST请求中文乱码问题-->
    <filter>
        <filter-name>characterFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
    <!--Rest支持-->
    <filter>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
    </filter>
    <filter-mapping>
        <filter-name>hiddenHttpMethodFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
</web-app>
复制代码

在ItemMapper中新增insert和selectById两个方法

public interface ItemMapper {
    void insert(Item item);
    Item selectById(Integer id);
}
复制代码

在ItemMapper XML文件中增加对应的SQL语句,在mapper标签下新增以下内容

<sql id="itemColumsWithoutId">
    name,price,pic,create_time,detail
</sql>
<sql id="itemColums">
    id,name,price,pic,create_time,detail
</sql>
<insert id="insert" useGeneratedKeys="true" keyColumn="id" keyProperty="id">
    INSERT item
    (<include refid="itemColumsWithoutId" />)
    VALUES (#{name},#{price},#{pic},#{createTime},#{detail})
</insert>
<select id="selectById" resultType="com.lilith.entity.Item">
    SELECT
    <include refid="itemColums"></include>
    FROM item
    WHERE id=#{id}
</select>
复制代码

增加ItemMapperTest测试类,对方法进行测试

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:application.xml")
public class ItemMapperTest {
    @Autowired
    private ItemMapper itemMapper;
    @Test
    public void insert() {
        for (int i = 10; i < 20; i++) {
            Item item = new Item();
            item.setName("Mark " + i);
            item.setPrice(12.0);
            item.setDetail("IRON MAN ARMY");
            item.setCreateTime(new Date());
            itemMapper.insert(item);
        }
    }
    @Test
    public void selectById() {
        Item item = itemMapper.selectById(18);
        System.out.println("查询到的数据为:" + item);
    }
}
复制代码

测试insert方法

image.png

测试selectById方法

image.png

新增ItemService接口及实现类

public interface ItemService {
    void save(Item item);
    Item findById(Integer id);
}
复制代码
@Service
public class ItemServiceImpl implements ItemService {
    @Autowired
    private ItemMapper itemMapper;
    @Override
    public void save(Item item) {
        itemMapper.insert(item);
    }
    @Override
    public Item findById(Integer id) {
        return itemMapper.selectById(id);
    }
}
复制代码

service层配置切面和事务通知,在application.xml中增加配置

<!--配置事务通知-->
<tx:advice id="advice" transaction-manager="dataSourceTransactionManager">
    <tx:attributes>
        <tx:method name="save*" propagation="REQUIRED"/>
        <tx:method name="update*" propagation="REQUIRED"/>
        <tx:method name="delete*" propagation="REQUIRED"/>
        <tx:method name="find*" read-only="true" />
        <tx:method name="*" propagation="REQUIRED"/>
    </tx:attributes>
</tx:advice>
<!--配置切面-->
<aop:config>
    <aop:pointcut id="pointcut" expression="execution(* com.lilith.service.impl.*.*(..))"/>
    <aop:advisor advice-ref="advice" pointcut-ref="pointcut" />
</aop:config>
复制代码

生成ItemServiceTest测试类

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = "classpath:application.xml")
public class ItemServiceTest {
    @Autowired
    private ItemService itemService;
    @Test
    public void save() {
        Item item = new Item();
        item.setName("电脑");
        item.setPrice(9999.0);
        item.setCreateTime(new Date());
        itemService.save(item);
    }
    @Test
    public void findById() {
        Item item = itemService.findById(20);
        System.out.println("itemService查询到的数据为:" + item);
    }
}
复制代码

测试save方法

image.png

测试findById方法

image.png

编写ItemController

@Controller
@RequestMapping("/item")
public class ItemController {
    @Autowired
    private ItemService itemService;
    @GetMapping("/{id}")
    public String getItem(@PathVariable("id") Integer id, Model model){
        Item item = itemService.findById(id);
        model.addAttribute("item",item);
        return "item";
    }
}
复制代码

在WEB-INF下创建pages文件夹,新增item.jsp页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
         pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Insert title here</title>
</head>
<body>
<form>
    <table width="100%" border=1>
        <tr>
            <td>商品名称</td>
            <td> ${item.name } </td>
        </tr>
        <tr>
            <td>商品价格</td>
            <td> ${item.price } </td>
        </tr>
        <tr>
            <td>生成日期</td>
            <td> <fmt:formatDate value="${item.createTime}" pattern="yyyy-MM-dd HH:mm:ss"/> </td>
        </tr>
        <tr>
            <td>商品简介</td>
            <td>${item.detail} </td>
        </tr>
    </table>
</form>
</body>
</html>
复制代码

在Project Structure的Artifacts目录下将右侧的jar包全部导入左侧的新建的lib目录下

image.png

配置Tomcat并启动,浏览器输入地址 http://localhost:8080/item/20

image.png

成功查询到数据并显示在页面上


相关文章
|
消息中间件 数据挖掘 Kafka
Apache Kafka流处理实战:构建实时数据分析应用
【10月更文挑战第24天】在当今这个数据爆炸的时代,能够快速准确地处理实时数据变得尤为重要。无论是金融交易监控、网络行为分析还是物联网设备的数据收集,实时数据处理技术都是不可或缺的一部分。Apache Kafka作为一款高性能的消息队列系统,不仅支持传统的消息传递模式,还提供了强大的流处理能力,能够帮助开发者构建高效、可扩展的实时数据分析应用。
1095 5
|
安全 网络协议 应用服务中间件
AJP Connector:深入解析及在Apache HTTP Server中的应用
【9月更文挑战第6天】在Java Web应用开发中,Tomcat作为广泛使用的Servlet容器,经常与Apache HTTP Server结合使用,以提供高效、稳定的Web服务。而AJP Connector(Apache JServ Protocol Connector)作为连接Tomcat和Apache HTTP Server的重要桥梁,扮演着至关重要的角色
730 2
|
Java 网络安全 Apache
SshClient应用指南:使用org.apache.sshd库在服务器中执行命令。
总结起来,Apache SSHD库是一个强大的工具,甚至可以用于创建你自己的SSH Server。当你需要在服务器中执行命令时,这无疑是非常有用的。希望这个指南能对你有所帮助,并祝你在使用Apache SSHD库中有一个愉快的旅程!
941 29
|
Java 应用服务中间件 测试技术
Maven学习笔记(一):Maven基础(基于命令行的学习和应用)
Maven 是一款 Java 项目构建工具,主要用于管理 jar 包及其依赖关系。 本文主要了解Maven基础知识及基础应用,旨在为之后的进一步学习奠定基础。 内容上几近全为学习《尚硅谷2022版Maven教程》整理所得。 仅供参考。
928 82
Maven学习笔记(一):Maven基础(基于命令行的学习和应用)
|
Java Maven
Maven编译报错:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile 解决方案
在执行Maven项目中的`install`命令时,遇到编译插件版本不匹配的错误。具体报错为:`maven-compiler-plugin:3.13.0`要求Maven版本至少为3.6.3。解决方案是将Maven版本升级到3.6.3或降低插件版本。本文详细介绍了如何下载、解压并配置Maven 3.6.3,包括环境变量设置和IDEA中的Maven配置,确保项目顺利编译。
17346 5
Maven编译报错:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.13.0:compile 解决方案
|
存储 分布式计算 druid
大数据-149 Apache Druid 基本介绍 技术特点 应用场景
大数据-149 Apache Druid 基本介绍 技术特点 应用场景
484 1
大数据-149 Apache Druid 基本介绍 技术特点 应用场景
|
消息中间件 Java Kafka
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
Spring Boot 与 Apache Kafka 集成详解:构建高效消息驱动应用
805 1
|
Java Maven Spring
SpringBoot 系列之 Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resource
这篇文章描述了在使用Maven构建Spring Boot项目时遇到的`maven-resources-plugin`插件版本问题导致的编译失败,并提供了通过修改插件版本至3.1.0来解决这个问题的方法。
SpringBoot 系列之 Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resource
|
分布式计算 大数据 数据处理
Apache Spark的应用与优势:解锁大数据处理的无限潜能
【8月更文挑战第23天】Apache Spark以其卓越的性能、易用性、通用性、弹性与可扩展性以及丰富的生态系统,在大数据处理领域展现出了强大的竞争力和广泛的应用前景。随着大数据技术的不断发展和普及,Spark必将成为企业实现数字化转型和业务创新的重要工具。未来,我们有理由相信,Spark将继续引领大数据处理技术的发展潮流,为企业创造更大的价值。
|
Java 持续交付 项目管理
Maven是一款基于Apache许可的项目管理和构建自动化工具,在Java开发中极为流行。
Maven是一款基于Apache许可的项目管理和构建自动化工具,在Java开发中极为流行。它采用项目对象模型(POM)来描述项目,简化构建流程。Maven提供依赖管理、标准构建生命周期、插件扩展等功能,支持多模块项目及版本控制。在Java Web开发中,Maven能够自动生成项目结构、管理依赖、自动化构建流程并运行多种插件任务,如代码质量检查和单元测试。遵循Maven的最佳实践,结合持续集成工具,可以显著提升开发效率和项目质量。
335 1

推荐镜像

更多