zoukankan      html  css  js  c++  java
  • SSM整合

    概述

    IDEA2020.3 + Tomcat9 + Maven3.6.3 + MySql5.7

    数据库准备

    DROP DATABASE IF EXISTS `ssmbuild`;
    CREATE DATABASE `ssmbuild`;
    USE `ssmbuild`;
    
    DROP TABLE IF EXISTS `book`;
    CREATE TABLE `book` (
    	`book_id` INT ( 10 ) NOT NULL AUTO_INCREMENT COMMENT '书id',
    	`book_name` VARCHAR ( 100 ) NOT NULL COMMENT '书名',
    	`book_count` INT ( 11 ) NOT NULL COMMENT '数量',
    	`book_detail` VARCHAR ( 200 ) NOT NULL COMMENT '描述',
    	PRIMARY KEY `book_id` ( `book_id` ) 
    ) ENGINE = INNODB DEFAULT CHARSET = utf8;
    
    INSERT INTO `book` ( `book_id`, `book_name`, `book_count`, `book_detail` )
    VALUES
    	( 1, 'Java', 1, '从入门到放弃' ),
    	( 2, 'MySQL', 10, '从删库到跑路' ),
    	( 3, 'Linux', 5, '从进门到进牢' );
    

    Pom依赖

    新建Mavenweb项目

    <properties>
        <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
        <maven.compiler.source>1.8</maven.compiler.source>
        <maven.compiler.target>1.8</maven.compiler.target>
    </properties>
    
    <dependencies>
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
            <scope>test</scope>
        </dependency>
    
        <!--数据库-->
        <dependency> <!--数据库驱动,兼容5.7-->
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.22</version>
        </dependency>
        <dependency> <!--数据库连接池-->
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.2.4</version>
        </dependency>
    
        <!--Servlet JSP-->
        <dependency><!--servlet3.0以上才有注解-->
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <dependency><!--jstl包含servlet2.5 jsp2.1-->
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl-api</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency><!--taglib包-->
            <groupId>org.apache.taglibs</groupId>
            <artifactId>taglibs-standard-impl</artifactId>
            <version>1.2.5</version>
        </dependency>
    
        <!--MyBatis-->
        <dependency><!--mybatis-->
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.5.6</version>
        </dependency>
        <dependency><!--mybatis-spring整合-->
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>2.0.6</version>
        </dependency>
    
        <!--Spring-->
        <dependency><!--Spring核心-->
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.3.3</version>
        </dependency>
        <dependency><!--事务-->
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.3.3</version>
        </dependency>
        <dependency><!--AOP-->
            <groupId>org.aspectj</groupId>
            <artifactId>aspectjweaver</artifactId>
            <version>1.9.6</version>
        </dependency>
    
        <!--工具-->
        <dependency><!--Java对象转字符串-->
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.75</version>
        </dependency>
        <dependency><!--中文乱码解决-->
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.12.1</version>
        </dependency>
    </dependencies>
    
    <build>
        <!-- 防止资源导出错误 -->
        <resources>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.properties</include>
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>
    

    基本结构配置

    • com.demo.entity
    • com.demo.mapper
    • com.demo.service
    • com.demo.controller
    • mybatis-config.xml
    <?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>
     
    </configuration>
    
    • applicationContext.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"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd">
    
    </beans>
    

    MyBatis层

    使用Druid数据源

    db.properties

    driver=com.mysql.cj.jdbc.Driver
    url=jdbc:mysql://localhost:3306/ssmbuild?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
    username=root
    password=root
    
    # Druid配置
    # 连接池最大数量
    druid.maxActive=20
    # 初始化连接大小
    druid.initialSize=1
    # 获取连接最大等待时间
    druid.maxWait=60000
    # 连接池最小空闲
    druid.minIdle=3
    # 自动清除无用连接
    druid.removeAbandoned=true
    # 清除无用连接的等待时间
    druid.removeAbandonedTimeout=180000
    # 连接属性
    druid.connectionProperties=clientEncoding=UTF-8
    # 检测连接有效性的时间间隔
    druid.timeBetweenEvictionRunsMillis=60000
    # 一个连接在池中最小生存的时间
    druid.minEvictableIdleTimeMillis=300000
    # 连接有效性,检测sql
    druid.validationQuery=SELECT 'x'
    # 定时检测空闲连接有效性
    druid.testWhileIdle=true
    # 检测获取的连接的有效性
    druid.testOnBorrow=false
    # 检测要归还的连接的有效性
    druid.testOnReturn=false
    # 别名方式,扩展插件,监控统计用的filter:stat,日志用的filter:log4j,防御sql注入的filter:wall
    druid.filters=stat
    # #是否缓存preparedStatement,即PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
    druid.poolPreparedStatements=false
    druid.maxPoolPreparedStatementPerConnectionSize=50
    

    mybatis-config.xml

    <?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="logImpl" value="STDOUT_LOGGING"/>
            <!--开启下划线转驼峰-->
            <setting name="mapUnderscoreToCamelCase" value="true"/>
            <!--开启二级缓存-->
            <setting name="cacheEnabled" value="true"/>
        </settings>
    
        <!--配置别名-->
        <typeAliases>
            <package name="com.demo.entity"/>
        </typeAliases>
    
        <!--Mapper注册-->
        <mappers>
            <package name="com.demo.mapper"/>
        </mappers>
    
    </configuration>
    

    Book.java

    @Data
    @NoArgsConstructor
    @AllArgsConstructor
    @Builder
    public class Book {
        private Integer bookId;
        private String bookName;
        private Integer bookCount;
        private String bookDetail;
    }
    

    BookMapper.java

    public interface BookMapper {
        /**
         * 查询一本书
         */
        Book getBookById(int id);
    
        /**
         * 条件查询书
         */
        List<Book> getBookByCondition(Map<String, Object> map);
    
        /**
         * 查询所有书
         */
        List<Book> getAllBook();
    
        /**
         * 增加一本书
         */
        int addBook(Book book);
    
        /**
         * 更新一本书
         */
        int updateBookByCondition(Book book);
    
        /**
         * 删除一本书
         */
        int deleteBookById(int id);
    }
    

    BookMapper.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.demo.mapper.BookMapper">
    
        <select id="getBookById" parameterType="int" resultType="book">
            select * from ssmbuild.book where book_id = #{id}
        </select>
    
        <select id="getBookByCondition" resultType="book">
            select * from ssmbuild.book
            <where>
                <include refid="if-book-query"/>
            </where>
        </select>
    
        <select id="getAllBook" resultType="book">
            select * from ssmbuild.book
        </select>
    
        <insert id="addBook" parameterType="book">
            insert into ssmbuild.book(book_id, book_name, book_count, book_detail)
            VALUES (#{bookId}, #{bookName}, #{bookCount}, #{bookDetail})
        </insert>
    
        <update id="updateBookByCondition" parameterType="book">
            update ssmbuild.book
            <set>
                <include refid="if-book-set"/>
            </set>
            where book_id = #{bookId}
        </update>
    
        <delete id="deleteBookById" parameterType="int">
            delete from ssmbuild.book where book_id = #{id}
        </delete>
    
        <sql id="if-book-query">
            <!--建议包含所有字段-->
            <if test="bookId != null">
                and book_id = #{bookId}
            </if>
            <if test="bookName != null">
                and book_name like concat('%', #{bookName}, '%')
            </if>
            <if test="bookCount != null">
                and book_count = #{bookCount}
            </if>
            <if test="bookDetail != null">
                and book_detail = #{bookDetail}
            </if>
        </sql>
    
        <sql id="if-book-set">
            <!--建议包含除主键外所有字段-->
            <if test="bookName != null">
                book_name = #{bookName},
            </if>
            <if test="bookCount != null">
                book_count = #{bookCount},
            </if>
            <if test="bookDetail != null">
                book_detail = #{bookDetail},
            </if>
        </sql>
    
    </mapper>
    

    BookService.java

    public interface BookService {
        /**
         * 查询一本书
         */
        Book getBookById(int id);
    
        /**
         * 条件查询书
         */
        List<Book> getBookByCondition(Map<String, Object> map);
    
        /**
         * 查询所有书
         */
        List<Book> getAllBook();
    
        /**
         * 增加一本书
         */
        int addBook(Book book);
    
        /**
         * 更新一本书
         */
        int updateBookByCondition(Book book);
    
        /**
         * 删除一本书
         */
        int deleteBookById(int id);
    }
    

    BookServiceIml.java

    @Service
    public class BookServiceImpl implements BookService {
    
        @Resource
        private BookMapper bookMapper;
    
        public void setBookMapper(BookMapper bookMapper) {
            this.bookMapper = bookMapper;
        }
    
        /**
         * 查询一本书
         */
        @Override
        public Book getBookById(int id) {
            return bookMapper.getBookById(id);
        }
    
        /**
         * 条件查询书
         */
        @Override
        public List<Book> getBookByCondition(Map<String, Object> map) {
            return bookMapper.getBookByCondition(map);
        }
    
        /**
         * 查询所有书
         */
        @Override
        public List<Book> getAllBook() {
            return bookMapper.getAllBook();
        }
    
        /**
         * 增加一本书
         */
        @Override
        public int addBook(Book book) {
            return bookMapper.addBook(book);
        }
    
        /**
         * 更新一本书
         */
        @Override
        public int updateBookByCondition(Book book) {
            return bookMapper.updateBookByCondition(book);
        }
    
        /**
         * 删除一本书
         */
        @Override
        public int deleteBookById(int id) {
            return bookMapper.deleteBookById(id);
        }
    }
    

    Spring层

    spring-mapper.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:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd">
    
        <!--引入数据库配置文件-->
        <context:property-placeholder location="classpath:db.properties"/>
    
        <!--Druid数据源配置-->
        <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
              init-method="init" destroy-method="clone">
            <property name="driverClassName" value="${driver}"/>
            <property name="url" value="${url}"/>
            <property name="username" value="${username}"/>
            <property name="password" value="${password}"/>
    
            <property name="maxActive" value="${druid.maxActive}"/>
            <property name="initialSize" value="${druid.initialSize}"/>
            <property name="maxWait" value="${druid.maxWait}"/>
            <property name="minIdle" value="${druid.minIdle}"/>
    
            <property name="removeAbandoned" value="${druid.removeAbandoned}"/>
            <property name="removeAbandonedTimeout" value="${druid.removeAbandonedTimeout}"/>
            <property name="connectionProperties" value="${druid.connectionProperties}"/>
            <property name="timeBetweenEvictionRunsMillis" value="${druid.timeBetweenEvictionRunsMillis}"/>
            <property name="minEvictableIdleTimeMillis" value="${druid.minEvictableIdleTimeMillis}"/>
            <property name="validationQuery" value="${druid.validationQuery}"/>
            <property name="testWhileIdle" value="${druid.testWhileIdle}"/>
            <property name="testOnBorrow" value="${druid.testOnBorrow}"/>
            <property name="testOnReturn" value="${druid.testOnReturn}"/>
            <property name="filters" value="${druid.filters}"/>
            <property name="poolPreparedStatements" value="${druid.poolPreparedStatements}"/>
            <property name="maxPoolPreparedStatementPerConnectionSize"
                      value="${druid.maxPoolPreparedStatementPerConnectionSize}"/>
        </bean>
    
        <!--SqlSessionFactory-->
        <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <!--绑定mybatis配置文件-->
            <property name="configLocation" value="classpath:mybatis-config.xml"/>
        </bean>
    
        <!-- 配置扫描Dao接口包,动态实现Mapper接口注入到spring容器中 -->
        <!--解释 : https://www.cnblogs.com/jpfss/p/7799806.html-->
        <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
            <!-- 注入sqlSessionFactory -->
            <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
            <!-- 给出需要扫描Mapper接口包 -->
            <property name="basePackage" value="com.demo.mapper"/>
        </bean>
    
    </beans>
    

    spring-service.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:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
           xmlns:aop="http://www.springframework.org/schema/aop"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop https://www.springframework.org/schema/aop/spring-aop.xsd">
    
        <!--扫描service下的所有包,使其支持注解-->
        <context:component-scan base-package="com.demo.service"/>
    
        <!--配置事务管理器-->
        <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
            <property name="dataSource" ref="dataSource"/>
        </bean>
    
        <!--配置事务环绕-->
        <tx:advice id="txAdvice" transaction-manager="transactionManager">
            <tx:attributes>
                <!--配置哪些方法使用什么样的事务,配置事务的传播特性-->
                <tx:method name="add" propagation="REQUIRED"/>
                <tx:method name="delete" propagation="REQUIRED"/>
                <tx:method name="update" propagation="REQUIRED"/>
                <tx:method name="search*" propagation="REQUIRED"/>
                <tx:method name="get" read-only="true"/>
            </tx:attributes>
        </tx:advice>
    
        <!--配置aop织入事务-->
        <aop:config>
            <aop:pointcut id="txPointcut" expression="execution(* com.demo.service.impl.*.*(..))"/>
            <aop:advisor advice-ref="txAdvice" pointcut-ref="txPointcut"/>
        </aop:config>
    
    </beans>
    

    applicationContext.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:context="http://www.springframework.org/schema/context"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd">
    
        <import resource="classpath:spring/spring-mapper.xml"/>
        <import resource="classpath:spring/spring-service.xml"/>
        <import resource="classpath:spring/spring-mvc.xml"/>
    
        <!--开启注解支持-->
        <context:annotation-config/>
    
    </beans>
    

    SpringMVC层

    spring-mvc.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:context="http://www.springframework.org/schema/context"
           xmlns:mvc="http://www.springframework.org/schema/mvc"
           xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           https://www.springframework.org/schema/mvc/spring-mvc.xsd">
    
        <!-- 自动扫描包,让指定包下的注解生效,由IOC容器统一管理 -->
        <context:component-scan base-package="com.demo.controller"/>
        <!-- 让Spring MVC不处理静态资源 -->
        <mvc:default-servlet-handler/>
        <!-- 支持mvc注解驱动 -->
        <mvc:annotation-driven/>
    
        <!--视图解析器-->
        <bean id="internalResourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
            <property name="prefix" value="/WEB-INF/jsp/"/> <!--前缀-->
            <property name="suffix" value=".jsp"/> <!--后缀-->
        </bean>
    
        <!--json字符串乱码问题解决,需要jackson包-->
        <mvc:annotation-driven>
            <mvc:message-converters register-defaults="true">
                <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                    <constructor-arg value="UTF-8"/>
                </bean>
                <bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
                    <property name="objectMapper">
                        <bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
                            <property name="failOnEmptyBeans" value="false"/>
                        </bean>
                    </property>
                </bean>
            </mvc:message-converters>
        </mvc:annotation-driven>
    
    </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"
             metadata-complete="false">
    
        <!--注册DispatcherServlet-->
        <servlet>
            <servlet-name>springmvc</servlet-name>
            <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
            <init-param>
                <param-name>contextConfigLocation</param-name>
                <!--关联一个springmvc的配置文件-->
                <param-value>classpath:applicationContext.xml</param-value>
            </init-param>
            <!--启动级别-1 数字越小,启动越早-->
            <load-on-startup>1</load-on-startup>
        </servlet>
        <servlet-mapping>
            <servlet-name>springmvc</servlet-name>
            <url-pattern>/</url-pattern>
        </servlet-mapping>
    
        <!--乱码处理-->
        <filter>
            <filter-name>encoding</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>encoding</filter-name>
            <url-pattern>/*</url-pattern>
        </filter-mapping>
    
    </web-app>
    

    实例测试

    BookServiceTest

    public class BookServiceTest {
        private BookService bookService;
    
        @Before
        public void before() {
            ApplicationContext context = new ClassPathXmlApplicationContext("applicationContext.xml");
            bookService = context.getBean("bookServiceImpl", BookService.class);
        }
    
        @Test
        public void testGetAllBook() {
            List<Book> allBook = bookService.getAllBook();
            for (Book book : allBook) {
                System.out.println(book);
            }
        }
    
        @Test
        public void testGetBookById() {
            Book book = bookService.getBookById(1);
            System.out.println(book);
        }
    
        @Test
        public void testGetBookByCondition() {
            Map<String, Object> map = new HashMap<>();
            map.put("bookName", "Java");
            map.put("bookCount", 1);
    
            List<Book> bookList = bookService.getBookByCondition(map);
            for (Book book : bookList) {
                System.out.println(book);
            }
        }
    
        @Test
        public void testAddBook() {
            Book book = new Book(10, "钢铁是怎样练成的", 10, "老毛子写的");
            bookService.addBook(book);
        }
    
        @Test
        public void testUpdateBook() {
            Book book = new Book(10, "钢铁是怎样练成的1", 1111, null);
    
            bookService.updateBookByCondition(book);
        }
    
        @Test
        public void testDeleteBookById() {
            bookService.deleteBookById(10);
        }
    }
    

    Controller

    @Controller
    @RequestMapping("/book")
    public class BookController {
    
        @Resource
        private BookService bookService;
    
        @RequestMapping("/toAllBookPage")
        public String allBook(Model model) {
            List<Book> allBook = bookService.getAllBook();
            model.addAttribute("allBook", allBook);
            return "allBook";
        }
    
        @RequestMapping("/toAddBookPage")
        public String toAddBookPage() {
            return "addBook";
        }
    
        @RequestMapping("/addBook")
        public String addBook(Book book) {
            bookService.addBook(book);
            // 重定向防止f5刷新重新提交
            return "redirect:/book/toAllBookPage";
        }
    
        @RequestMapping("/toUpdateBookPage/{bookId}")
        public String toUpdateBookPage(Model model, @PathVariable int bookId) {
            Book book = bookService.getBookById(bookId);
            model.addAttribute("book", book);
            return "updateBook";
        }
    
        @RequestMapping("/updateBook")
        public String updateBook(Book book) {
    
            bookService.updateBookByCondition(book);
            // 重定向防止f5刷新重新提交
            return "redirect:/book/toAllBookPage";
        }
    
        @RequestMapping("/deleteBook/{bookId}")
        public String deleteBook(@PathVariable int bookId) {
            bookService.deleteBookById(bookId);
            // 重定向防止f5刷新重新提交
            return "redirect:/book/toAllBookPage";
        }
    
        @RequestMapping("/getBookByCondition")
        public String getBookByCondition(Model model, @RequestParam(value = "bookId", required = false) Integer bookId, @RequestParam(value = "bookName", required = false) String bookName) {
            System.out.println(bookId);
            System.out.println(bookName);
            Map<String, Object> map = new HashMap<>();
            if (bookId != null) {
                map.put("bookId", bookId);
            }
            if (!bookName.trim().equals("")) {
                map.put("bookName", bookName.trim());
            }
            List<Book> bookList = bookService.getBookByCondition(map);
            model.addAttribute("allBook", bookList);
            if (bookList.size() == 0) {
                model.addAttribute("error", "没有相关信息!");
            }
    
            return "allBook";
        }
    
    }
    

    index.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>首页</title>
    </head>
    <body>
    <h3>
        <a href="${pageContext.request.contextPath}/book/toAllBookPage">书籍展示</a>
    </h3>
    </body>
    </html>
    

    allbook.jsp

    <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>书籍展示</title>
    </head>
    <body>
    <h1>书籍展示</h1>
    <h3>
        <a href="${pageContext.request.contextPath}/book/toAddBookPage">添加书籍</a>
    </h3>
    <form action="${pageContext.request.contextPath}/book/getBookByCondition">
        <p>
            书籍编号:<input type="number" name="bookId">
            书籍名称:<input type="text" name="bookName">
            <input type="submit" value="查询">
            <span style="color: red">${error}</span>
        </p>
    </form>
    <table border="1" cellpadding="10" cellspacing="0">
        <thead>
            <tr>
                <td>书籍编号</td>
                <td>书籍名称</td>
                <td>书籍数量</td>
                <td>书籍详情</td>
                <td>操作</td>
            </tr>
        </thead>
        <tbody>
            <c:forEach items="${allBook}" var="item">
                <tr>
                    <td>${item.bookId}</td>
                    <td>${item.bookName}</td>
                    <td>${item.bookCount}</td>
                    <td>${item.bookDetail}</td>
                    <td>
                        <a href="${pageContext.request.contextPath}/book/toUpdateBookPage/${item.bookId}">修改</a> |
                        <a href="${pageContext.request.contextPath}/book/deleteBook/${item.bookId}">删除</a>
                    </td>
                </tr>
            </c:forEach>
        </tbody>
    </table>
    <a href="${pageContext.request.contextPath}/index.jsp">返回首页</a>
    </body>
    </html>
    

    addBook.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>添加书籍</title>
    </head>
    <body>
    <h1>添加书籍</h1>
    <form action="${pageContext.request.contextPath}/book/addBook">
        <!--name要和实体类属性一样-->
        <p>书籍名称:<input type="text" name="bookName" required></p>
        <p>书籍数量:<input type="number" name="bookCount" required></p>
        <p>书籍详情:<input type="text" name="bookDetail" required></p>
        <p><input type="submit" value="添加"></p>
    </form>
    <a href="${pageContext.request.contextPath}/index.jsp">返回首页</a>
    </body>
    </html>
    

    updateBook.jsp

    <%@ page contentType="text/html;charset=UTF-8" language="java" %>
    <html>
    <head>
        <title>修改书籍</title>
    </head>
    <body>
    <h1>修改书籍</h1>
    <form action="${pageContext.request.contextPath}/book/updateBook">
        <!--name要和实体类属性一样-->
        <input type="hidden" name="bookId" value="${book.bookId}">
        <p>书籍名称:<input type="text" name="bookName" value="${book.bookName}" required></p>
        <p>书籍数量:<input type="number" name="bookCount" value="${book.bookCount}" required></p>
        <p>书籍详情:<input type="text" name="bookDetail" value="${book.bookDetail}" required></p>
        <p><input type="submit" value="修改"></p>
    </form>
    <a href="${pageContext.request.contextPath}/index.jsp">返回首页</a>
    </body>
    </html>
    
  • 相关阅读:
    swift2.0学习之拓展
    CSDN处理问题神速,顶你,为你点32个赞!
    quick-cocos2d-x教程7:程序框架内framework文件夹分析
    Android自己定义Toast
    leetcode: Add Digits
    Effective Java:对于全部对象都通用的方法
    动态规划法-01背包问题
    loosejar原理简要分析
    eclipse中Client/Server程序生成exe
    Spring 新手教程(三) 注入和自己主动装配
  • 原文地址:https://www.cnblogs.com/shenleg/p/14289889.html
Copyright © 2011-2022 走看看