逐步搭建 Spring5+SpringMVC5+Mybatis3+Bootstrap3 框架Demo

目錄

一、準備工作

二、框架搭建

1.集成Spring與Spring MVC

1)新建Maven項目

2)配置文件

3)運行框架

2.加載Bootstrap

1)引入Bootstrap

2)應用Bootstrap

3.集成Mybatis

1)配置文件

2)運行框架

4.改進框架

1)引入Lombok

2)引入Log4j

5.完善Demo

三、總結


一、準備工作

本Demo使用Eclipse作爲開發IDE,運行容器是Tomcat,數據庫是MySQL,後端使用Maven管理jar包,前端展現使用Bootstrap。因此,所需工具和準備有:

  • Eclipse

Demo使用的Eclipse版本爲Oxygen.1a Release (4.7.1a),下載列表地址爲:

https://www.eclipse.org/downloads/packages/release/oxygen/1a

  • Tomcat

Demo使用的Tomcat版本爲8.5.30,下載列表地址爲:

https://archive.apache.org/dist/tomcat/tomcat-8/v8.5.30/bin/

  • MySQL

Demo使用的MySQL版本爲5.7.3-m13,下載列表地址爲:

http://www.mirrorservice.org/sites/ftp.mysql.com/Downloads/MySQLInstaller/

  • Maven

Demo使用的Maven版本爲3.5.2,下載列表地址爲:

http://apache.dattatec.com/maven/maven-3/

  • Bootstrap

Demo使用的Bootstrap版本爲3.3.7,下載列表地址爲:

https://getbootstrap.com/docs/versions/

  • jQuery

Demo使用的jQuery版本爲3.4.0,下載列表地址爲:

http://jquery.com/download/ 

二、框架搭建

由於安裝IDE和配置Maven、Tomcat不是主要介紹的內容,此處略過。下面直接進行框架的搭建。

1.集成Spring與Spring MVC

1)新建Maven項目

在Eclipse的File菜單項中選擇new,在隨後的子菜單中選擇Maven Project:

隨後出現新建窗口:

只勾選使用默認工作空間地址就行,其他可以不用選,然後點擊Next:

由於Demo是web工程,所以選擇webapp這一項就好,然後點擊Next:

填寫Group Id、Artifact Id然後點擊Finish即可完成建立Maven項目了。

建立好的項目結構:

這裏發現引入的JRE版本較低,需要替換掉,本Demo採用的版本是jre8。替換方法是:選中項目名,使用快捷鍵alt+enter,進入項目的properties設置對話框:

選中Java Build Path,Remove掉JRE庫,並點擊Add Library…按鈕,添加jre8庫:

點擊Apply按鈕保存配置,然後選擇左邊菜單項中的Java Compiler,把編譯器level選爲1.8:

點擊Apply按鈕保存配置,然後選擇左邊菜單項中的Project Facets,把Java這一項選爲1.8

點擊Apply按鈕保存配置,然後選擇左邊菜單項中的Server,把Server選上Tomcat:

點擊Apply按鈕保存配置,然後選擇左邊菜單項中的Targeted Runtimes,選中Tomcat:

點擊Apply and Close按鈕保存配置並關閉對話框。

現在項目結構如下:

2)配置文件

現在來配置pom.xml文件,Demo使用的Spring版本是5.1.6.RELEASE:

<properties>
  	<spring.version>5.1.6.RELEASE</spring.version> 
	<jstl.version>1.2</jstl.version>
</properties>

<dependencies>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-core</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>${spring.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>${spring.version}</version>
	</dependency> 
		
	<dependency>
		<groupId>javax.servlet</groupId>
		<artifactId>jstl</artifactId>
		<version>${jstl.version}</version>
	</dependency>
</dependencies>

然後是配置web.xml文件,關於Spring的配置是指明Spring配置文件所在路徑和添加監聽器:

<context-param>
	<param-name>contextConfigLocation</param-name>
	<param-value>classpath:config/applicationContext-spring.xml</param-value>
</context-param>
<listener>
	<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

關於Spring MVC的配置是添加servlet,並在其中初始化參數裏指明Spring MVC配置文件所在路徑:

<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:config/applicationContext-springmvc.xml</param-value>
	</init-param>
	<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
	<servlet-name>springMVC</servlet-name>
	<url-pattern>/</url-pattern>
</servlet-mapping>

在resources文件夾中新建config文件夾,並建立配置文件。

首先配置applicationContext-spring.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: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
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context.xsd">
	
	<!-- 掃描註解類(service) -->
	<context:component-scan base-package="com.ynter.service" />
	
</beans>

採用Spring的自動註解,配置其去掃描service類並自動裝配bean。

接下來配置applicationContext-springmvc.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:mvc="http://www.springframework.org/schema/mvc" 
	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
	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">

	<!-- 開啓MVC註解 -->
	<mvc:annotation-driven />
	
	<!-- 掃描註解類(controller) -->
	<context:component-scan base-package="com.ynter.controller" />

	<!-- 配置 Spring MVC 的視圖模板 -->
	<bean id="viewResolver"
		class="org.springframework.web.servlet.view.InternalResourceViewResolver">
		<!-- 支持JSTL -->
		<property name="viewClass"
			value="org.springframework.web.servlet.view.JstlView" />
		<!-- 模板的路徑 -->
		<property name="prefix" value="/WEB-INF/view/" />
		<!-- 模板文件後綴 -->
		<property name="suffix" value=".jsp" />
	</bean>

	<!-- 靜態資源訪問 -->
	<mvc:resources location="/WEB-INF/res/js/" mapping="/js/**" />
	<mvc:resources location="/WEB-INF/res/css/" mapping="/css/**" />
	<mvc:resources location="/WEB-INF/res/images/" mapping="/images/**" />
</beans>

此時的項目結構爲:

到此Spring和SpringMVC初步集成完畢。

3)運行框架

首先運行項目試試能不能訪問(已經預先準備了簡單內容的index.jsp):

創建controller文件TestController.java並進行編寫:

@Controller
@RequestMapping("/test")
public class TestController {

	@PostMapping("/showMessage")
	public ModelAndView showMessage(HttpServletRequest request) {
		
		ModelAndView mv = new ModelAndView("test/showMessage");
		mv.addObject("message", "Hello ssm demo!");
		
		return mv;
	}
}

在index.jsp中加入表單:

<form action="test/showMessage" method="post">
	<button type="submit">點擊跳轉</button>
</form>

新增showMessage.jsp:

<%@ page language="java" contentType="text/html; charset=utf8"
	pageEncoding="utf8"%>
<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf8">
		<title>SSM Demo Index</title>
	</head>
<body style="text-align:center;">
	<h2 style="text-align:center;">Welcome to ssm demo!</h2>
	<p>The message is : ${message}</p>
</body>
</html>

保存項目後重部署到Tomcat,並進行訪問:

此時項目結構爲:

2.加載Bootstrap

1)引入Bootstrap

Demo使用的Bootstrap需要用到jQuery,所以引入Bootstrap的同時也把jQuery一起引入。在WEB-INF文件夾下新建util文件夾,用來存放下載並解壓出來的插件。

改造applicationContext-springmvc.xml,加入對Bootstrap所在路徑的靜態映射配置:

<mvc:resources location="/WEB-INF/util/bootstrap/" mapping="/bootstrap/**" />
<mvc:resources location="/WEB-INF/util/jQuery/" mapping="/jQuery/**" />

Bootstrap的引入就完成了。

2)應用Bootstrap

首先在index.jsp中引入Bootstrap所需文件:

<script type="text/javascript"
	src="${pageContext.request.contextPath}/jQuery/jquery.min.js"></script>
<script type="text/javascript"
	src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"></script>
		
<link rel="stylesheet"
	href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.min.css" />

然後改造下頁面內容:

<body>
	<div class="container">
		<h2>Welcome to ssm demo! - index</h2>
	</div>
	
	<div class="container">
		<form action="test/showMessage" method="post" class="form-index">
			<div class="form-group">
				<button type="submit" class="btn btn-lg btn-primary btn-block">點擊跳轉</button>
			</div>
		</form>
	</div>
</body>

對於showMessage.jsp頁面做同樣的引入並進行改造。

重部署項目並重啓Tomcat,訪問項目:

3.集成Mybatis

1)配置文件

Demo使用的Mybatis版本是3.5.1,在pom.xml文件中配置:

<properties>
    …
    <mybatis.version>3.5.1</mybatis.version>
    <mybatis.spring.version>2.0.1</mybatis.spring.version>
</properties>

<dependencies>
     …
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis</artifactId>
        <version>${mybatis.version}</version>
    </dependency>
    <dependency>
        <groupId>org.mybatis</groupId>
        <artifactId>mybatis-spring</artifactId>
        <version>${mybatis.spring.version}</version>
    </dependency>
</dependencies>

由於需要連接MySQL數據庫,所需驅動也要配置進來:

<properties>
    …
    <mysql.version>5.1.38</mysql.version>
</properties>

<dependencies>
     …
    <dependency>
        <groupId>org.springframework</groupId>
        <artifactId>spring-jdbc</artifactId>
        <version>${spring.version}</version>
    </dependency>
     …
    <dependency>
        <groupId>mysql</groupId>
        <artifactId>mysql-connector-java</artifactId>
        <version>${mysql.version}</version>
    </dependency>
</dependencies>

使用Spring管理數據庫鏈接要用到數據連接池,這裏使用的是c3p0,因此一併配置進來:

<properties>
    …
    <c3p0.version>0.9.5.4</c3p0.version>
</properties>

<dependencies>
     …
    <dependency>
        <groupId>com.mchange</groupId>
        <artifactId>c3p0</artifactId>
        <version>${c3p0.version}</version>
    </dependency>
</dependencies>

接下來就是對Mybatis的整體配置,首先建立數據庫連接文件datasource.properties:

dataSource.driverClass=com.mysql.jdbc.Driver
dataSource.jdbcUrl=jdbc:mysql://127.0.0.1:3306/test?useSSL=false
dataSource.user=root
dataSource.password=root
dataSource.maxPoolSize=20
dataSource.maxIdleTime = 1000
dataSource.minPoolSize=5
dataSource.initialPoolSize=5

然後對applicationContext-spring.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:mybatis="http://mybatis.org/schema/mybatis-spring" 
	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.xsd
	http://www.springframework.org/schema/context 
	http://www.springframework.org/schema/context/spring-context.xsd
	http://mybatis.org/schema/mybatis-spring 
	http://mybatis.org/schema/mybatis-spring.xsd
	http://www.springframework.org/schema/tx
	http://www.springframework.org/schema/tx/spring-tx.xsd">
	
	<!-- 掃描註解類(service) -->
	<context:component-scan base-package="com.ynter.service" />
	
	<!-- 掃描 mapper 接口並自動引入 -->
	<mybatis:scan base-package="com.ynter.mapper" />
	
	<!-- 加載數據源參數 -->
	<context:property-override location="classpath:config/datasource.properties" />

	<!-- 配置c3p0數據源 -->
	<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource" />

	<!-- 配置sqlSessionFactory -->
	<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"
		p:dataSource-ref="dataSource" />

	<!-- JDBC事務管理器 -->
	<bean id="transactionManager"
		class="org.springframework.jdbc.datasource.DataSourceTransactionManager"
		p:dataSource-ref="dataSource" />

	<!-- 啓用註解方式事務管理 -->
	<tx:annotation-driven transaction-manager="transactionManager" />
</beans>

至此Mybatis的集成完畢。

2)運行框架

首先在數據庫建立表:

CREATE TABLE `t_book_info` (
  `id`varchar(32) NOT NULL,
  `name` varchar(32) DEFAULT NULL,
  `author` varchar(32) DEFAULT NULL,
  `isbn` varchar(17) DEFAULT NULL,
	`price` float DEFAULT NULL,
	`in_time` date DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=INNODB DEFAULT CHARSET=utf8;

在Demo中建立對應的pojo類BookInfoPojo.java,並進行編寫(由於引入了lombok,可以省略get/set方法,具體在下一節介紹):

package com.ynter.pojo;

import java.util.Date;

import lombok.Data;

@Data
public class BookInfoPojo {

	private String id;
	private String name;
	private String author;
	private String isbn;
	private Float price;
	private Date inTime;
		
}

建立mapper接口BookInfoMapper.java,並進行編寫:

package com.ynter.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Select;

import com.ynter.pojo.BookInfoPojo;

public interface BookInfoMapper {

	@Select(" SELECT * FROM t_book_info")
	public List<BookInfoPojo> findAll();
}

建立service接口BookInfoService.java,並進行編寫:

package com.ynter.service;

import java.util.List;

import com.ynter.pojo.BookInfoPojo;

public interface BookInfoService {

	public List<BookInfoPojo> getBookInfos();
}

建立service實現類BookInfoServiceImpl.java,並進行編寫:

package com.ynter.service.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.ynter.mapper.BookInfoMapper;
import com.ynter.pojo.BookInfoPojo;
import com.ynter.service.BookInfoService;

@Service
@Transactional(propagation = Propagation.REQUIRED, isolation = Isolation.DEFAULT)
public class BookInfoServiceImpl implements BookInfoService {

	@Autowired
	private BookInfoMapper bookInfoMapper;

	@Override
	@Transactional(readOnly = true)
	public List<BookInfoPojo> getBookInfos() {
		return bookInfoMapper.findAll();
	}

}

建立controller類BookInfoController.java,並進行編寫:

package com.ynter.controller;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.ynter.service.BookInfoService;

@Controller
@RequestMapping("/bookInfo")
public class BookInfoController {

	@Autowired
	private BookInfoService bookInfoService;

	@RequestMapping("/showBookInfos")
	public ModelAndView showBookInfos(HttpServletRequest request) {

		ModelAndView mv = new ModelAndView("bookInfo/showBookInfos");
		mv.addObject("bookInfos", bookInfoService.getBookInfos());

		return mv;
	}
}

建立頁面showBookInfos.jsp,並編寫內容:

<%@ page language="java" contentType="text/html; charset=utf8"
	pageEncoding="utf8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html>
<html lang="zh-CN">
	<head>
		<meta http-equiv="Content-Type" content="text/html; charset=utf8">
		<script type="text/javascript"
			src="${pageContext.request.contextPath}/jQuery/jquery.min.js"></script>
		<script type="text/javascript"
			src="${pageContext.request.contextPath}/bootstrap/js/bootstrap.min.js"></script>
		
		<link rel="stylesheet"
			href="${pageContext.request.contextPath}/bootstrap/css/bootstrap.min.css" />
		<link rel="stylesheet"
			href="${pageContext.request.contextPath}/css/common.css" />
		<link rel="stylesheet"
			href="${pageContext.request.contextPath}/css/bookInfo/bookInfo.css" />
			
		<title>showBookInfos</title>
	</head>
	<body>
		<div class="container">
			<h1>showBookInfos</h1>
		</div>
		
		<div class="div-table">
			<table class="table table-striped">
				<thead>
			        <tr>
			          <th>序號</th>
			          <th>書名</th>
			          <th>作者</th>
			          <th>ISBN</th>
			          <th>價格</th>
			        </tr>
	      		</thead>
	      		<tbody>
					<c:forEach items="${bookInfos}" var="bookInfo" varStatus="status">
						<tr>
							<td>${status.index + 1}</td>
							<td>${bookInfo.name}</td>
							<td>${bookInfo.author}</td>
							<td>${bookInfo.isbn}</td>
							<td>${bookInfo.price}</td>
						</tr>
					</c:forEach>
				</tbody>
			</table>
		</div>
		
		<div class="container div-return">
			<a class="btn btn-lg btn-primary btn-block" href="${pageContext.request.contextPath}">返回</a>
		</div>
	</body>
</html>

改造頁面index.jsp,添加跳轉按鈕:

…
<div class="container">
		<form action="bookInfo/showBookInfos" method="post" class="form-index">
			<div class="form-group">
				<button type="submit" class="btn btn-lg btn-primary btn-block">查看圖書信息</button>
			</div>
		</form>
	</div>
…

重部署Demo,重啓Tomcat,看看效果:

至此,整個框架就集成完畢。現在項目結構如下:

4.改進框架

1)引入Lombok

Demo中可以引入lombok來讓pojo類省去get/set編寫,具體引入步驟如下:

在pom.xml中配置:

…
<properties>
		<lombok.version>1.18.6</lombok.version>
	</properties>
…
<dependencies>
…
		<dependency>
			<groupId>org.projectlombok</groupId>
			<artifactId>lombok</artifactId>
			<version>${lombok.version}</version>
		</dependency>
</dependencies>
…

保存後maven將會自動下載lombok的jar包,需要去到下載目錄中找到該jar包,雙擊啓動安裝程序:

點擊Specify location…按鈕選擇eclipse所在目錄,然後點擊Install/Update按鈕進行安裝。安裝完畢後會在eclipse目錄下看到Lombok程序lombok.jar:

然後就可以在Demo中使用Lombok插件了(上節的pojo類中)。

2)引入Log4j

爲了方便調試,可以在Demo中引入Log4j,這裏引入的是Log4j2,具體步驟爲:

在pom.xml配置:

…
<properties>
		<log4j2.version>2.11.2</log4j2.version>
	</properties>
…
<dependencies>
…
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-core</artifactId>
			<version>${log4j2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-api</artifactId>
			<version>${log4j2.version}</version>
		</dependency>
		<dependency>
			<groupId>org.apache.logging.log4j</groupId>
			<artifactId>log4j-web</artifactId>
			<version>${log4j2.version}</version>
		</dependency>
</dependencies>
…

接下來,在web.xml中配置:

…
	<!-- log4j2 配置 start -->
	<context-param>
		<param-name>log4jConfiguration</param-name>
		<param-value>classpath:config/applicationContext-log4j2.xml</param-value>
	</context-param>
	<!-- log4j2 配置 end -->
…

在相應位置建立applicationContext-log4j2.xml文件,並編寫內容:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="Warn" monitorInterval="30">
	<Appenders>
		<Console name="Console" target="SYSTEM_OUT">
			<PatternLayout pattern="[%d{yyyy-MM-dd HH:mm:ss.SSS} %5p] [%C] [%M : %L]%n====>%m%n%n" />
        </Console>
    </Appenders>

	<Loggers>
		<Logger name="org.springframework" level="info" additivity="false">
            <AppenderRef ref="Console" />
        </Logger>
        
        <Logger name="org.mybatis" level="info" additivity="false">
        	<AppenderRef ref="Console" />
        </Logger>
        
        <Logger name="com.ynter" level="debug" additivity="false">
        	<AppenderRef ref="Console" />
        </Logger>
        
        <Root level="info">
        	<AppenderRef ref="Console" />
        </Root>
	</Loggers>
</Configuration>

之後只需在需要使用Log4j的類中引入以下語句即可使用:

…
private static final Logger log = LogManager.getLogger();
…

5.完善Demo

這一節對Demo中關於BookInfo的增刪改等功能進行完善。

首先對BookInfoMapper.java進行修改:

…
	@SelectKey(statement = " SELECT REPLACE(UUID(),'-','')", keyProperty = "id", resultType = String.class, before = true)
	@Insert(" INSERT INTO t_book_info(id, name, author, isbn, price, in_time) VALUES(#{id}, #{name}, #{author}, #{isbn}, #{price}, now())")
	public int insert(BookInfoPojo bookInfo);

	@Delete(" DELETE FROM t_book_info WHERE id = #{id}")
	public int delete(String id);

	@Select(" SELECT * FROM t_book_info")
	public List<BookInfoPojo> findAll();

	@Update(" UPDATE t_book_info SET name = #{name}, author = #{author}, isbn = #{isbn}, price = #{price} WHERE id = #{id}")
	public int update(BookInfoPojo bookInfo);
…

接下來對BookInfoService.java進行修改:

…
	public int setBookInfo(BookInfoPojo bookInfo);
	
	public int removeBookInfo(String id);

	public List<BookInfoPojo> getBookInfos();
	
	public int changeBookInfo(BookInfoPojo bookInfo);
…

對BookInfoServiceImpl.java進行修改:

…
	@Override
	@Transactional()
	public int setBookInfo(BookInfoPojo bookInfo) {
		return bookInfoMapper.insert(bookInfo);
	}

	@Override
	@Transactional()
	public int removeBookInfo(String id) {
		return bookInfoMapper.delete(id);
	}
	
	@Override
	@Transactional(readOnly = true)
	public List<BookInfoPojo> getBookInfos() {
		return bookInfoMapper.findAll();
	}
	
	@Override
	@Transactional()
	public int changeBookInfo(BookInfoPojo bookInfo) {
		return bookInfoMapper.update(bookInfo);
	}
…

對BookInfoController.java進行修改:

…
	@RequestMapping("/createBookInfo")
	public ModelAndView createBookInfo(HttpServletRequest request) {

		BookInfoPojo bookInfo = new BookInfoPojo();

		String name = request.getParameter("name");
		String author = request.getParameter("author");
		String isbn = request.getParameter("isbn");
		Float price = Float.valueOf(request.getParameter("price"));

		bookInfo.setName(name);
		bookInfo.setAuthor(author);
		bookInfo.setIsbn(isbn);
		bookInfo.setPrice(price);

		int result = bookInfoService.setBookInfo(bookInfo);

		log.info("The insert result is : " + (result > 0 ? true : false));

		return showBookInfos(request);
	}

	@RequestMapping("/destroyBookInfo")
	public ModelAndView destroyBookInfo(HttpServletRequest request) {

		String id = request.getParameter("id");

		int result = bookInfoService.removeBookInfo(id);

		log.info("The delete result is : " + (result > 0 ? true : false));

		return showBookInfos(request);
	}

	@RequestMapping("/showBookInfos")
	public ModelAndView showBookInfos(HttpServletRequest request) {

		ModelAndView mv = new ModelAndView("bookInfo/showBookInfos");
		mv.addObject("bookInfos", bookInfoService.getBookInfos());

		return mv;
	}

	@RequestMapping("/modifyBookInfo")
	public ModelAndView modifyBookInfo(HttpServletRequest request) {

		BookInfoPojo bookInfo = new BookInfoPojo();

		String id = request.getParameter("id");
		String name = request.getParameter("name");
		String author = request.getParameter("author");
		String isbn = request.getParameter("isbn");
		Float price = Float.valueOf(request.getParameter("price"));

		bookInfo.setId(id);
		bookInfo.setName(name);
		bookInfo.setAuthor(author);
		bookInfo.setIsbn(isbn);
		bookInfo.setPrice(price);

		int result = bookInfoService.changeBookInfo(bookInfo);

		log.info("The update result is : " + (result > 0 ? true : false));

		return showBookInfos(request);
	}
…

最後是對頁面進行修改,代碼略。

重部署Demo,重啓Tomcat,效果如下:

三、總結

Demo在集成時其實也遇到很多問題,最終通過查資料等方式解決了,下面簡單概況下一些可能會碰到的問題。

  • Maven在初始建立時有可能需要調節下參數,例如Java Build Path的內容、Java Compiler的內容等,在上面也提到過。
  • Web.xml在配置時,要注意使用的版本,本Demo用的是3.0,可以在配置文件的開頭查看到。例如:
<web-app version="3.0" xmlns="http://java.sun.com/xml/ns/javaee"
	xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
…
</web-app>

*另:項目代碼可以在這裏下載:https://download.csdn.net/download/ynter/11147066

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章