springmvc_mybatis框架整合

本文详细介绍了如何配置Maven Web项目,包括pom.xml的依赖管理、资源文件加载、构建插件设置,以及Spring MVC框架的整合,实现了一个简单的图书管理系统。

配置maven web项目:

 

第一步:

配置文件:

pom.xml:

<?xml version="1.0" encoding="UTF-8"?>

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
    <modelVersion>4.0.0</modelVersion>

    <groupId>com.zit</groupId>
    <artifactId>springmvc04</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>
    <name>springmvc04</name>

    <dependencies>
        <!-- https://mvnrepository.com/artifact/junit/junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
            <scope>test</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.mybatis/mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/mysql/mysql-connector-java -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>8.0.12</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/org.projectlombok/lombok -->
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.2</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.0.9.RELEASE</version>
        </dependency>


        <!-- https://mvnrepository.com/artifact/javax.servlet/javax.servlet-api -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
            <scope>provided</scope>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp/jsp-api -->
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.2.1-b03</version>
            <scope>provided</scope>
        </dependency>

        <!-- https://mvnrepository.com/artifact/javax.servlet/jstl -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/org.codehaus.jackson/jackson-mapper-asl -->
        <dependency>
            <groupId>org.codehaus.jackson</groupId>
            <artifactId>jackson-mapper-asl</artifactId>
            <version>1.9.13</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.9.6</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-fileupload/commons-fileupload -->
        <dependency>
            <groupId>commons-fileupload</groupId>
            <artifactId>commons-fileupload</artifactId>
            <version>1.3.3</version>
        </dependency>

        <!-- https://mvnrepository.com/artifact/commons-io/commons-io -->
        <dependency>
            <groupId>commons-io</groupId>
            <artifactId>commons-io</artifactId>
            <version>2.6</version>
        </dependency>


    </dependencies>

    <build>
        <finalName>${project.artifactId}</finalName>
        <testSourceDirectory>src/test/java</testSourceDirectory>
        <sourceDirectory>src/main/java</sourceDirectory>
        <!-- 解决无法加载资源配置文件 -->
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
                <includes>
                    <include>**/*.xml</include>
                    <include>**/*.properties</include>
                </includes>
            </resource>
        </resources>

        <plugins>
            <!-- 配置maven编译插件 -->
            <plugin>
                <groupId>org.apache.maven.plugins</groupId>
                <artifactId>maven-compiler-plugin</artifactId>
                <version>3.8.0</version>
                <configuration>
                    <source>1.8</source>
                    <target>1.8</target>
                    <encoding>UTF-8</encoding>
                </configuration>
            </plugin>

            <!-- 配置jetty servlet服务器 -->
            <plugin>
                <groupId>org.eclipse.jetty</groupId>
                <artifactId>jetty-maven-plugin</artifactId>
                <version>9.4.12.v20180830</version>
                <configuration>
                    <stopKey>exit</stopKey>
                    <stopPort>8989</stopPort>
                    <scanIntervalSeconds>10</scanIntervalSeconds>
                    <reload>manual</reload>
                    <webAppConfig>
                        <contextPath>/</contextPath>
                    </webAppConfig>
                    <httpConnector>
                        <port>80</port>
                    </httpConnector>
                </configuration>
                <executions>
                    <execution>
                        <id>jetty-run</id>
                        <phase>test</phase>
                        <goals>
                            <goal>run</goal>
                        </goals>
                    </execution>
                </executions>
            </plugin>
        </plugins>


    </build>


</project>

src/main/resources/包下:

resources/db.properties:

db.driver=com.mysql.cj.jdbc.Driver
db.url=jdbc:mysql://localhost:3306/dt_game?serverTimezone=PRC&useSSL=false&uerUnicode=true&characterEncoding=utf-8
db.username=root
db.password=

resources/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>
    <!--引入数据库服务配置文件信息-->
    <!-- 加载db.properties -->
    <properties resource="db.properties"/>

    <typeAliases>
        <!--将实体包下的类自动为别名 com.fz.entity.User 别名就是user-->
        <package name="com.zit.entity"/>
    </typeAliases>

    <environments default="development">
        <environment id="development">
            <transactionManager type="JDBC"/>
            <dataSource type="POOLED">
                <property name="driver" value="${db.driver}"/>
                <property name="url" value="${db.url}"/>
                <property name="username" value="${db.username}"/>
                <property name="password" value="${db.password}"/>
            </dataSource>
        </environment>
    </environments>
    <mappers>
        <!-- 加载映射配置文件 -->
        <!--   <mapper resource="com/zit/mapper/BookMapper.xml"/>-->
        <!--使用接口-->
        <!--<mapper class="com.zit.mapper.BookMapper"/>-->
        <!--使用包-->
        <package name="com.zit.mapper"/>
    </mappers>
</configuration>

resources/smvc.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
			http://www.springframework.org/schema/context/spring-context.xsd
			http://www.springframework.org/schema/mvc
			http://www.springframework.org/schema/mvc/spring-mvc.xsd">

    <!-- 配置自动扫描的包 -->
    <context:component-scan base-package="com.zit.controller"/>

    <!-- 在没有配置mvc:resources的时候没有问题,一旦配置了mvc:resources,注解方式的url就没有加载 -->
    <mvc:annotation-driven>
        <!-- 消息转换器 -->
        <mvc:message-converters register-defaults="true">
            <bean class="org.springframework.http.converter.StringHttpMessageConverter">
                <property name="supportedMediaTypes" value="text/html;charset=UTF-8"/>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!-- 文件上传支持 -->
    <bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <!-- 104857600 代表100MB -->
        <property name="maxUploadSize" value="104857600"/>
        <property name="maxInMemorySize" value="40960"/>
        <property name="defaultEncoding" value="UTF-8"></property>
    </bean>

    <!--    <mvc:interceptors>
            <mvc:interceptor>
                <mvc:mapping path="/admin/**"/>
                <mvc:exclude-mapping path="/admin/login"/>
                <bean class="com.zit.interceptor.TestInterceptor"/>
            </mvc:interceptor>
    
        </mvc:interceptors>-->


    <!--<mvc:resources mapping="/images/**" location="/images/" />-->


    <!-- 配置视图解析器 如何把handler 方法返回值解析为实际的物理视图 -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/template/"></property>
        <property name="suffix" value=".jsp"></property>
    </bean>
</beans>

src/main/webapp/WEB-INF/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">
    <display-name>springmvc04</display-name>

    <!--springmvc 5.1.0 servlet配置-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath*:smvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>


    <!-- spring filter 编码过滤器 -->
    <filter>
        <filter-name>characterEncodingFilter</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>
        <init-param>
            <param-name>forceEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>characterEncodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!--  &lt;!&ndash;访问静态资源&ndash;&gt;
      <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.html</url-pattern>
        <url-pattern>*.css</url-pattern>
        <url-pattern>*.js</url-pattern>
        <url-pattern>*.jpg</url-pattern>
        <url-pattern>*.gif</url-pattern>
        <url-pattern>*.png</url-pattern>
        <url-pattern>*.rar</url-pattern>
      </servlet-mapping>-->

    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
        <url-pattern>*.ico</url-pattern>
    </servlet-mapping>


    <!--配置web项目的web.xml文件的首页-->
    <welcome-file-list>
        <welcome-file>/</welcome-file>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

</web-app>


 

 

第二步:各种包下的文件:

src/main/java

java/com.zit/controller/BookController.java

package com.zit.controller;

import com.zit.dao.BookService;
import com.zit.dao.BookServiceImpl;
import com.zit.entity.Book;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

@Controller
public class BookController {
    protected BookService bdao = new BookServiceImpl();

    @RequestMapping
    public String index(Model model) {
        //model.addAttribute("user","李思思");
        model.addAttribute("books", bdao.query());
        return "index";
    }

    @GetMapping("/del/{id}")
    public String delete(@PathVariable("id") int id) {
        bdao.deleteById(id);
        return "redirect:/";
    }

    @GetMapping("/add")
    public void add() {

    }


    @PostMapping("/addsave")/* @ResponseBody*/
    public String addsave(Book book) {
        bdao.add(book);
        return "redirect:/";

        // return book.toString();
    }

    @GetMapping("/update/{id}")
    public String update(@PathVariable("id") int id, Model model) {
        model.addAttribute("book", bdao.queryById(id));
        return "update";
    }


    @PostMapping("/updatesave")
    public String updatesave(Book book) {
        bdao.update(book);
        return "redirect:/";
    }

}

java/com.zit.dao/BookService()interface

package com.zit.dao;

import com.zit.entity.Book;

import java.util.List;

public interface BookService {
    public List<Book> query();

    public int deleteById(int id);

    public int add(Book book);

    public Book queryById(int id);

    public int update(Book book);
}

java/com.zit.dao/BookServiceImpl.java

package com.zit.dao;

import com.zit.entity.Book;
import com.zit.mapper.BookMapper;
import org.apache.ibatis.session.SqlSession;

import java.util.List;

public class BookServiceImpl implements BookService {
    protected SqlSession session;
    protected BookMapper bmdao;


    public BookServiceImpl() {
        this.session = new MybatisUtil().getSession();
        this.bmdao = session.getMapper(BookMapper.class);
    }

    @Override
    public List<Book> query() {
        return bmdao.query();
    }


    @Override
    public int deleteById(int id) {
        int i = bmdao.deleteById(id);
        session.commit();
        return i;
    }

    @Override
    public int add(Book book) {
        int i = bmdao.add(book);
        session.commit();
        return i;
    }

    @Override
    public Book queryById(int id) {

        return bmdao.queryById(id);
    }

    @Override
    public int update(Book book) {
        int i = bmdao.update(book);
        session.commit();
        return i;
    }


}

java/com.zit.dao/MybatisUtil.java

package com.zit.dao;

import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;

import java.io.IOException;
import java.io.InputStream;

public class MybatisUtil {
    private SqlSessionFactory sf;
    private SqlSession ss;

    public MybatisUtil() {
        InputStream is = null;
        try {
            is = Resources.getResourceAsStream("mybatis-config.xml");
        } catch (IOException e) {
            e.printStackTrace();
        }
        this.sf = new SqlSessionFactoryBuilder().build(is);
        this.ss = this.sf.openSession();
    }

    public SqlSession getSession() {
        return this.ss;
    }
}

  

 

java/com.zit.entity包

java/com.zit.entity/Book.java

package com.zit.entity;

import lombok.Data;
import org.springframework.format.annotation.DateTimeFormat;

import java.math.BigDecimal;
import java.util.Date;

@Data
public class Book {
    private int id;
    private String name;
    private BigDecimal price;
    @DateTimeFormat(pattern = "yyyy-MM-dd")
    private Date btime;
}

java/com.zit.mapper/BookMapper.interface

package com.zit.mapper;

import com.zit.entity.Book;
import org.apache.ibatis.annotations.Delete;
import org.apache.ibatis.annotations.Insert;
import org.apache.ibatis.annotations.Select;
import org.apache.ibatis.annotations.Update;

import java.util.List;

public interface BookMapper {
    @Select("select * from book")
    public List<Book> query();

    @Delete("delete from book where id=#{id}")
    public int deleteById(int id);

    @Insert("insert into book values(null,#{name},#{price},#{btime})")
    public int add(Book book);


    @Select("select * from book where id=#{id}")
    public Book queryById(int id);


    @Update("update book set name=#{name},price=#{price},btime=#{btime} where id=#{id}")
    public int update(Book book);

}

java/com.zit.mapper/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.zit.mapper.BookMapper">


</mapper>

 

src/main/resources包

db.properties    mybatis-config.xml    smvc.xml文件上面已经写过了。。。

 

src/main/webapp

src/main/webapp/css/index.css

.tt {
    width: 80%;
    border-collapse: collapse;
    margin: 20px auto;
}

.tt caption {
    font-weight: bold;
    letter-spacing: 5px;
    font: 25px/55px "微软雅黑";
}

.tt tr td, .tt tr th {
    border: 1px solid #d9d9d9;
    padding: 8px;
    text-align: center;
    font: 14px/28px "微软雅黑";
}

.tt tr:hover {
    background-color: #f4ffcb;
}

webapp/WEB-INF/template/add.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图书管理系统1.0</title>
    <link rel="stylesheet" href="/css/index.css">
</head>
<body>
<h3>新书籍信息</h3>
<form action="/addsave" method="post">
    <table class="tt">
        <tr>
            <td>书籍名称</td>
            <td><input type="text" name="name"></td>
        </tr>
        <tr>
            <td>书籍价格</td>
            <td><input type="text" name="price"></td>
        </tr>
        <tr>
            <td>出版日期</td>
            <td><input type="text" name="btime"></td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="提交"></td>
        </tr>
    </table>
</form>

<a href="/">首页</a>

</body>
</html>

webapp/WEB-INF/template/index.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图书管理系统1.0</title>
    <link rel="stylesheet" href="/css/index.css">
</head>
<body>
<table class="tt">
    <tr>
        <th>编号</th>
        <th>书籍名称</th>
        <th>价格</th>
        <th>出版日期</th>
        <th>基本操作</th>
    </tr>
    <c:forEach items="${books}" var="book">
        <tr>
            <td>${book.id}</td>
            <td>${book.name}</td>
            <td>${book.price}</td>
            <td><fmt:formatDate value="${book.btime}" pattern="yyyy-MM-dd"/></td>
            <td><a href="/del/${book.id}.html">删除</a> &nbsp;&nbsp;
                <a href="/update/${book.id}.html">编辑</a></td>
        </tr>
    </c:forEach>
    <tr>
        <td colspan="20"><a href="/add">添加新书籍</a></td>
    </tr>
</table>

</body>
</html>

webapp/WEB-INF/template/update.jsp

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>图书管理系统1.0</title>
    <link rel="stylesheet" href="/css/index.css">
</head>
<body>
<h3>编辑图书:${book.name}</h3>
<form action="/updatesave" method="post">
    <input type="hidden" name="id" value="${book.id}">
    <table class="tt">
        <tr>
            <td>书籍名称</td>
            <td><input type="text" name="name" value="${book.name}"></td>
        </tr>
        <tr>
            <td>书籍价格</td>
            <td><input type="text" name="price" value="${book.price}"></td>
        </tr>
        <tr>
            <td>出版日期</td>
            <td><input type="text" name="btime" value="<fmt:formatDate value='${book.btime}' pattern='yyyy-MM-dd' />">
            </td>
        </tr>
        <tr>
            <td colspan="2"><input type="submit" value="更改"></td>
        </tr>
    </table>
</form>

<a href="/">首页</a>

</body>
</html>

webapp/WEB-INF/web.xml文件上面已经写过了。。

 

weapp/favicon.ico(网上找一个放上去)  ====占标文件

 

结束......

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值