在學習spring4+springmvc+mybatis的ssm框架,idea整合簡單實現增刪改查功能,在這裏記錄一下。
原文在這裏:https://my.oschina.net/finchxu/blog/3007984
工做環境:html
項目上傳到了Github方便查看:https://github.com/finch-xu/springbook 有用的話歡迎加星。前端
頁面演示:java
首先新建項目mysql
如圖所示新建maven的webappgit
建數據庫和數據表github
CREATE DATABASE books; CREATE TABLE `bookadmin` ( `bid` int(11) NOT NULL AUTO_INCREMENT, `bn` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `author` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, `press` varchar(255) CHARACTER SET utf8 COLLATE utf8_general_ci NOT NULL, PRIMARY KEY (`bid`) USING BTREE ) ENGINE = InnoDB AUTO_INCREMENT = 14 CHARACTER SET = utf8 COLLATE = utf8_general_ci ROW_FORMAT = Dynamic;
這裏是項目目錄結構web
springbook ├── src │ └── main │ ├── java │ │ └── cn │ │ └── book │ │ ├── controller │ │ │ └── BooksController.java │ │ ├── mapper │ │ │ ├── BooksMapper.java │ │ │ └── BooksMapper.xml │ │ ├── pojo │ │ │ └── Bookadmin.java │ │ └── service │ │ ├── BooksServiceImpl.java │ │ └── BooksService.java │ ├── resources │ │ ├── applicationContext-dao.xml │ │ ├── applicationContext-service.xml │ │ ├── applicationContext-trans.xml │ │ ├── jdbc.properties │ │ ├── log4j.properties │ │ ├── spring-mvc.xml │ │ └── sqlMapConfig.xml │ └── webapp │ ├── index.jsp │ └── WEB-INF │ ├── jsp │ │ ├── listBooks.jsp │ │ ├── savepage.jsp │ │ └── updatepage.jsp │ └── web.xml
pom.xml 找不到的包能夠去https://mvnrepository.com/ 這裏找,很方便的。spring
<?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>cn.book</groupId> <artifactId>spring</artifactId> <version>1.0-SNAPSHOT</version> <packaging>war</packaging> <name>spring Maven Webapp</name> <!-- FIXME change it to the project's website --> <url>http://www.example.com</url> <properties> <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <!--<maven.compiler.source>1.8</maven.compiler.source>--> <!--<maven.compiler.target>1.8</maven.compiler.target>--> <spring.version>4.3.19.RELEASE</spring.version> <validator.version>5.2.4.Final</validator.version> <slf4j.version>1.7.7</slf4j.version> <commons-lang3.version>3.3.2</commons-lang3.version> <commons-io.version>2.4</commons-io.version> <commons-codec.version>1.9</commons-codec.version> <commons-fileupload.version>1.3.1</commons-fileupload.version> <commons-beanutils.version>1.9.1</commons-beanutils.version> </properties> <dependencies> <!-- WEB begin --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.2.8</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.2</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.29</version> </dependency> <dependency> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> </dependency> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> <type>jar</type> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>jstl</artifactId> <version>1.2</version> <type>jar</type> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> <!--<scope>provided</scope>--> </dependency> <dependency> <groupId>javax.servlet.jsp</groupId> <artifactId>jsp-api</artifactId> <version>2.1</version> <!--<scope>provided</scope>--> </dependency> <!-- WEB end --> <!-- SPRING begin --> <dependency> <groupId>commons-dbcp</groupId> <artifactId>commons-dbcp</artifactId> <version>1.4</version> </dependency> <dependency> <groupId>com.esotericsoftware.reflectasm</groupId> <artifactId>reflectasm</artifactId> <version>1.09</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.2.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>${spring.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context-support</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>${spring.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>${spring.version}</version> </dependency> <!-- spring orm --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-orm</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>javax.inject</groupId> <artifactId>javax.inject</artifactId> <version>1</version> </dependency> <!-- bean validate --> <!--<dependency>--> <!--<groupId>org.hibernate</groupId>--> <!--<artifactId>hibernate-validator</artifactId>--> <!--<version>${validator.version}</version>--> <!--</dependency>--> <!-- SPRING end --> <!-- AOP begin --> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.7.4</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>3.1</version> </dependency> <!-- AOP end --> <!-- TEST begin --> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.12</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>${spring.version}</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-oxm</artifactId> <version>${spring.version}</version> </dependency> <!-- TEST end --> <!-- LOGGING begin --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>${slf4j.version}</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>${slf4j.version}</version> </dependency> <!-- common-logging 實際調用slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jcl-over-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <!-- java.util.logging 實際調用slf4j --> <dependency> <groupId>org.slf4j</groupId> <artifactId>jul-to-slf4j</artifactId> <version>${slf4j.version}</version> </dependency> <!-- LOGGING end --> <dependency> <groupId>commons-lang</groupId> <artifactId>commons-lang</artifactId> <version>2.6</version> </dependency> <dependency> <groupId>commons-io</groupId> <artifactId>commons-io</artifactId> <version>${commons-io.version}</version> </dependency> <dependency> <groupId>commons-codec</groupId> <artifactId>commons-codec</artifactId> <version>${commons-codec.version}</version> </dependency> <dependency> <groupId>commons-fileupload</groupId> <artifactId>commons-fileupload</artifactId> <version>${commons-fileupload.version}</version> </dependency> <dependency> <groupId>commons-beanutils</groupId> <artifactId>commons-beanutils</artifactId> <version>${commons-beanutils.version}</version> <exclusions> <exclusion> <groupId>commons-logging</groupId> <artifactId>commons-logging</artifactId> </exclusion> </exclusions> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <version>1.16.18</version> <scope>provided</scope> </dependency> </dependencies> <build> <defaultGoal>install</defaultGoal> <pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-compiler-plugin</artifactId> <version>2.3.2</version> <configuration> <source>1.8</source> <target>1.8</target> <maxmem>256M</maxmem> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-idea-plugin</artifactId> <version>2.2</version> <configuration> <downloadSources>true</downloadSources> <downloadJavadocs>true</downloadJavadocs> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-resources-plugin</artifactId> <version>2.4.3</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-clean-plugin</artifactId> <version>2.4.1</version> <configuration> <filesets> <fileset> <directory>activemq-data</directory> </fileset> </filesets> </configuration> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-install-plugin</artifactId> <version>2.3.1</version> </plugin> <plugin> <artifactId>maven-remote-resources-plugin</artifactId> <version>1.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-jar-plugin</artifactId> <version>2.2</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-dependency-plugin</artifactId> <version>2.1</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <version>2.5</version> </plugin> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-checkstyle-plugin</artifactId> <version>2.6</version> </plugin> <plugin> <groupId>org.codehaus.mojo</groupId> <artifactId>exec-maven-plugin</artifactId> <version>1.1.1</version> </plugin> </plugins> </pluginManagement> <plugins> <plugin> <groupId>org.apache.maven.plugins</groupId> <artifactId>maven-surefire-plugin</artifactId> <configuration> <childDelegation>false</childDelegation> <useFile>true</useFile> <failIfNoTests>false</failIfNoTests> <includes> <include>**/*Test.java</include> </includes> </configuration> </plugin> </plugins> <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources> </build> </project>
必定要注意這段內容,在maven打包war時掃描這些xml文件 <resources> <resource> <directory>src/main/java</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> <resource> <directory>src/main/resources</directory> <includes> <include>**/*.properties</include> <include>**/*.xml</include> </includes> <filtering>false</filtering> </resource> </resources>
resourcessql
applicationContext-dao.xml 用的dbcp鏈接池。數據庫
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 數據庫鏈接池 --> <bean id="propertyConfigurer" class="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer"> <property name="location" value="classpath:jdbc.properties"/> </bean> <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close"> <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="maxActive" value="${jdbc.maxActive}" /> <!-- 最大空閒數 --> <property name="maxIdle" value="${jdbc.maxIdle}" /> </bean> <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"> <property name="dataSource" ref="dataSource" /> <!-- 加載mybatis核心配置文件 --> <property name="configLocation" value="classpath:sqlMapConfig.xml" /> <!-- 別名包掃描 --> <property name="typeAliasesPackage" value="cn.book.pojo" /> </bean> <!-- 動態代理,第二種方式:包掃描(推薦): --> <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"> <!-- basePackage多個包用","分隔 --> <property name="basePackage" value="cn.book.mapper" /> </bean> </beans>
applicationContext-service.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- @Service包掃描器 --> <context:component-scan base-package="cn.book.service"/> </beans>
applicationContext-trans.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:p="http://www.springframework.org/schema/p" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.0.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.0.xsd http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd"> <!-- 事務管理器 --> <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="save*" propagation="REQUIRED" /> <tx:method name="insert*" propagation="REQUIRED" /> <tx:method name="delete*" propagation="REQUIRED" /> <tx:method name="update*" propagation="REQUIRED" /> <tx:method name="find*" propagation="SUPPORTS" read-only="true" /> <tx:method name="get*" propagation="SUPPORTS" read-only="true" /> <tx:method name="query*" propagation="SUPPORTS" read-only="true" /> </tx:attributes> </tx:advice> <!--<!– 切面 –>--> <!--<aop:config>--> <!--<aop:advisor advice-ref="txAdvice"--> <!--pointcut="execution(* cn.book.service.*.*(..))" />--> <!--</aop:config>--> </beans>
jdbc.properties 這裏要注意應定要加上「jdbc.」的前綴。我用的是mysql5.7因此driver直接這麼寫就行,若是是mysql6及以上的就不同了,具體百度吧。
若是遇到什麼時區問題,記得在url後邊再加上時區設置就好了。
jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://127.0.0.1:3306/books?useUnicode=true&characterEncoding=utf-8 jdbc.username=root jdbc.password=12345678 jdbc.maxActive=10 jdbc.maxIdle=5
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:p="http://www.springframework.org/schema/p" 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-4.0.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd"> <!-- 配置@controller掃描包 --> <!--<context:component-scan base-package="cn.book.controller" />--> <context:annotation-config/> <context:component-scan base-package="cn.book.controller"> <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/> </context:component-scan> <!-- 配置註解驅動,至關於同時使用最新處理器映射跟處理器適配器,對json數據響應提供支持 --> <mvc:annotation-driven /> <mvc:default-servlet-handler/> <!-- 配置視圖解析器 --> <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/jsp/"/> <property name="suffix" value=".jsp"/> </bean> </beans>
sqlMapConfig.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>
web.xml 這裏的最後一部分(有註釋的那裏)寫的是/而不是/*,由於用了後者就把jsp也當靜態文件了,訪問頁面直接顯示源代碼而不是解析jsp。
<?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>Archetype Created Web Application</display-name> <welcome-file-list> <welcome-file>index.jsp</welcome-file> </welcome-file-list> <!-- 配置spring --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext*.xml</param-value> </context-param> <!-- 使用監聽器加載Spring配置文件 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- 解決post亂碼問題 --> <filter> <filter-name>encoding</filter-name> <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class> <!-- 設置編碼參是UTF8 --> <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> <!-- 前端控制器 --> <servlet> <servlet-name>springmvc-web</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring-mvc.xml</param-value> </init-param> </servlet> <servlet-mapping> <servlet-name>springmvc-web</servlet-name> <url-pattern>/</url-pattern><!--這裏寫的是/而不是/*,由於用了後者就把jsp也當靜態文件了--> </servlet-mapping> </web-app>
而後就是代碼:
Mapper部分:
BooksMapper.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="cn.book.mapper.BooksMapper"> <sql id="BASE_TABLE"> bookadmin </sql> <sql id="BASE_COLUMN"> bid,bn,author,press </sql> <!--<resultMap id="BaseResultMap" type="cn.book.pojo.Bookadmin">--> <!--<id column="bid" property="bid" jdbcType="INTEGER" />--> <!--<result column="bn" property="bn" jdbcType="VARCHAR" />--> <!--<result column="author" property="author" jdbcType="VARCHAR" />--> <!--<result column="press" property="press" jdbcType="VARCHAR" />--> <!--</resultMap>--> <insert id="insert" parameterType="Bookadmin"> INSERT INTO <include refid="BASE_TABLE"/> <trim prefix="(" suffix=")" suffixOverrides=","> bn,author, <if test="press != null"> press, </if> </trim> <trim prefix="VALUES(" suffix=")" suffixOverrides=","> #{bn,jdbcType=VARCHAR},#{author,jdbcType=VARCHAR}, <if test="press != null"> #{press,jdbcType=VARCHAR}, </if> </trim> </insert> <select id="getBookByBid" resultType="Bookadmin"> select bid,bn,author,press from bookadmin where bid = #{bid} </select> <select id="list" resultType="Bookadmin"> select * from bookadmin </select> <update id="update" parameterType="Bookadmin"> update <include refid="BASE_TABLE"/> set bn = #{bn},author = #{author},press = #{press} where bid = #{bid} </update> <delete id="delete" parameterType="Bookadmin"> delete from <include refid="BASE_TABLE"/> where bid = #{bid} </delete> <!--resultType="Bookadmin"--> </mapper>
BooksMapper.java
package cn.book.mapper; import cn.book.pojo.Bookadmin; import java.util.List; public interface BooksMapper{ List<Bookadmin> list(); int insert(Bookadmin record); int update(Bookadmin b); int delete(Bookadmin bid); Bookadmin getBookByBid(Integer bid); }
POJO實體
Bookadmin.java
package cn.book.pojo; public class Bookadmin { Integer bid; String bn; String author; String press; public Integer getBid() { return bid; } public void setBid(Integer bid) { this.bid = bid; } public String getBn() { return bn; } public void setBn(String bn) { this.bn = bn; } public String getAuthor() { return author; } public void setAuthor(String author) { this.author = author; } public String getPress() { return press; } public void setPress(String press) { this.press = press; } }
service部分
BooksService.java
package cn.book.service; import cn.book.pojo.Bookadmin; import org.springframework.stereotype.Service; import java.util.List; @Service public interface BooksService { List<Bookadmin> list(); int insertBook(Bookadmin bookadmin); int update(Bookadmin b); int deleteBookByBid(Bookadmin bid); Bookadmin getBookByBid(int bid); }
BooksServiceImpl.java
package cn.book.service; import cn.book.mapper.BooksMapper; import cn.book.pojo.Bookadmin; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.util.List; @Service public class BooksServiceImpl implements BooksService { @Autowired private BooksMapper booksMapper; // 列出數據 @Override public List<Bookadmin> list(){ List<Bookadmin> list = this.booksMapper.list(); return list; } // 插入數據 @Override public int insertBook(Bookadmin bookadmin){ return booksMapper.insert(bookadmin); } // 更新數據 @Override public int update(Bookadmin b){ return booksMapper.update(b); } // 刪除數據 @Override public int deleteBookByBid(Bookadmin bid){ return booksMapper.delete(bid); } @Override public Bookadmin getBookByBid(int bid){ return booksMapper.getBookByBid(bid); } }
Controller部分
BooksController.java
package cn.book.controller; import cn.book.pojo.Bookadmin; import cn.book.service.BooksService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.ui.Model; import org.springframework.web.bind.annotation.PathVariable; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.RequestMethod; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.servlet.ModelAndView; import java.util.List; @Controller @RequestMapping("/a") public class BooksController { @Autowired BooksService booksService; //列出數據表格 // 設置listBooks頁面(list第一種寫法) @RequestMapping("/listBooks") public ModelAndView listBooks(){ ModelAndView mav = new ModelAndView(); List<Bookadmin> bb = booksService.list(); mav.addObject("bb",bb); mav.setViewName("listBooks"); return mav; } // list的第二種寫法 // @RequestMapping("/listBooks") // public String listBooks(Model model){ // List<Bookadmin> bb = booksService.list(); // model.addAttribute("bb",bb); // return "listBooks"; // } // 添加數據(兩部分) // 第一步:跳轉到這裏並添加圖書信息,點擊添加按鈕就執行下邊第二段代碼 @RequestMapping("/addBooks0") public String addBooks0(){ return "savepage"; } // 第二步:把下邊的頁面數據返回給後端,再跳轉到listBooks頁面 @RequestMapping(value = "/addBooks",method = RequestMethod.POST) public String addBooks(Bookadmin bookadmin){ booksService.insertBook(bookadmin); return "redirect:listBooks"; } // 修改數據(兩部分) // 第一步:更新圖書,先經過bid找到圖書,並列在/updatepage/{bid}頁面上, @RequestMapping("/updatepage/{bid}") public String updatepage(@PathVariable("bid") int bid,Model model){ model.addAttribute("bookadmin",booksService.getBookByBid(bid)); return "updatepage"; } // 第二步:而後修改便可,在這裏點更新提交數據給後端 @RequestMapping(value = "/update",method = RequestMethod.POST) public String update(Bookadmin b){ booksService.update(b); return "redirect:listBooks"; } // 刪除圖書數據 @RequestMapping("/deleteBooksByBid") public String deleteBooksByBid(Bookadmin bid){ booksService.deleteBookByBid(bid); return "redirect:listBooks"; } }
JSP頁面
listBooks.jsp 列出全部的圖書信息(而且包含添加、修改和刪除的功能按鈕)
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %> <%--^^^^^添加對jstl列表的支持^^^^^--%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>listBooks</title> </head> <body> <form> <table align="center" bgcolor="aqua" border="1" cellpadding="0"> <tr> <th width="140">圖書BID</th> <th width="140">書名</th> <th width="140">做者</th> <th width="140">出版社</th> <th width="140">修改</th> <th width="140">刪除</th> </tr> <c:forEach items="${bb}" var="b"> <%--varStatus="ct"--%> <tr> <td>${b.bid}</td> <td>${b.bn}</td> <td>${b.author}</td> <td>${b.press}</td> <td><a href="${pageContext.request.contextPath}/a/updatepage/${b.bid}">修改</a></td> <td><a href="${pageContext.request.contextPath}/a/deleteBooksByBid?bid=${b.bid}" onclick='return confirm("確認要刪除嗎?")'>刪除</a></td> </tr> </c:forEach> <%--<td><a href="${pageContext.request.contextPath}/a/addBooks0">添加圖書(跳轉頁面)</a></td>--%> </table> </form> <form id="saveForm" action="${pageContext.request.contextPath}/a/addBooks" method="post"> <table align="center" bgcolor="aqua" border="1" cellpadding="0"> <tr> <th width="140">書名</th> <th width="140">做者</th> <th width="140">出版社</th> </tr> <tr> <td width="140"><input type="text" value="${bookadmin.bn}" name="bn"/></td> <td width="140"><input type="text" value="${bookadmin.author}" name="author"/></td> <td width="140"><input type="text" value="${bookadmin.press}" name="press" /></td> <td width="140"><input type="submit" value="添加" /></td> </tr> </table> </form> </body> </html>
savepage.jsp 添加圖書並返回到上邊的列表頁面
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <% String path = request.getContextPath(); String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/"; %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>添加圖書</title> </head> <body> <br/> <form id="saveForm" action="${pageContext.request.contextPath}/a/addBooks" method="post"> <table align="center" bgcolor="aqua" border="1" cellpadding="0"> <tr> <td>書名:</td> <td><input type="text" value="${bookadmin.bn}" name="bn"/></td> </tr> <tr> <td>做者:</td> <td><input type="text" value="${bookadmin.author}" name="author"/></td> </tr> <tr> <td>出版社:</td> <td><input type="text" value="${bookadmin.press}" name="press" /></td> </tr> <input type="submit" value="添加" /> </table> </form> </body> </html>
updatepage.jsp 更新和修改圖書信息
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %> <% String path = request.getContextPath(); String basePath = request.getScheme() + "://" + request.getServerName() + ":" + request.getServerPort() + path + "/"; %> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>更新&修改 圖書信息</title> </head> <body> <h2>編輯圖書信息!</h2> <form id="updateForm" action="${pageContext.request.contextPath}/a/update" method="post"> <input type="hidden" value="${bookadmin.bid}" name="bid"/> <table align="center" bgcolor="aqua" border="1" cellpadding="0"> <tr> <td>書名:</td> <td><input type="text" value="${bookadmin.bn}" name="bn"/></td> </tr> <tr> <td>做者:</td> <td><input type="text" value="${bookadmin.author}" name="author"/></td> </tr> <tr> <td>出版社:</td> <td><input type="text" value="${bookadmin.press}" name="press"/></td> </tr> <input type="submit" value="更新" /> </table> </form> </body> </html>
而後能夠在idea裏開一個tomcat來啓動項目,實現簡單的增刪改查功能。
訪問http://localhost:8080/springbook_war_exploded/a/listBooks就獲得頁面:
項目上傳到了Github方便查看:https://github.com/finch-xu/springbook 有用的話歡迎加星。
轉載需註明本文地址:https://my.oschina.net/finchxu/blog/3007984
感謝:
controller的詳細講解:https://www.cnblogs.com/pophope/p/5619504.html
https://blog.csdn.net/Peng_Hong_fu/article/details/53536862
https://www.javatpoint.com/spring-mvc-crud-example
https://www.journaldev.com/3531/spring-mvc-hibernate-mysql-integration-crud-example-tutorial