算命网站该怎样做/优化大师班级
超级通道:MyBatis代码实例系列-绪论
本章主要记录Mybatis初步整合Spring + Spring MVC框架(只是初步),实现Web请求实例。涉及到的技术有:
- 通过SqlSessionFactoryBean的的DataSource结合Spring的DataSource,替代MyBatis配置文件的DataSource
- 通过SqlSessionFactoryBean的mapperLocations,替代MyBatis配置文件的mappers配置
- 通过SqlSessionFactoryBean的typeAliasesPackage,替代MyBatis配置文件的typeAliases配置
- 通过Spring的DataSourceTransactionManager,替代MyBatis配置文件的JdbcTransactionManager配置
- 通过MapperScannerConfigurer的sqlSessionFactoryBeanName,替代MyBatis建立会话工厂的new SqlSessionFactoryBuilder().build(reader)方式。
- 通过MapperScannerConfigurer的basePackage,替代MyBatis实例化Dao层对象的sqlSession.getMapper(IDAO.class)方式
- tx:annotation-driven:Spring事务控制开启注解,通过@Transactional注解Service层方法,实现事务控制。
- JsonResult:以泛型定义返回值的数据结构,实现复用。
- ShowList:打印对象列表的工具类。
0. 实例说明
本章是以MyBatis代码实例系列-03:MyBatis单张表简单实现增删改查 + log4j + 手动事务控制为基础,进行MyBatis与Spring以及Spring MVC的初步整合,以达到实现Web请求的目的。通过对比前后两种实现方式,能够更好地理解单用MyBatis框架与使用SSM框架组合的区别,更深入的理解各类框架。
业务场景与SQL参考MyBatis代码实例系列-03:MyBatis单张表简单实现增删改查 + log4j + 手动事务控制。
1.单独使用MyBatis的配置方式
配置方法详见MyBatis代码实例系列-03:MyBatis单张表简单实现增删改查 + log4j + 手动事务控制。此处只给出关键部分。
1.1.目录结构
src
\---main\---java| \---pers| \---hanchao| \---himybatis| \---curd| \---Topic.java| \---ITopicDAO.java| \---TopicApp.java\---webapp\---mybatis-mappers\---Topic.xml\---log4j.properties\---mybatis-config.xml
1.2.MyBatis配置文件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">
<!--MyBatis的总配置文件-->
<configuration><!--类型依赖:配置Java类对应的别名,与Question.xml中的resultType相互对应--><typeAliases><!--通过XML+IDAO的配置方式,实现单表的增删改查--><typeAlias type="pers.hanchao.himybatis.curd.Topic" alias="Topic"/></typeAliases><!--mybatis的数据库连接--><environments default="dev"><environment id="dev"><!--事务管理--><transactionManager type="JDBC"></transactionManager><!--数据源信息--><dataSource type="POOLED"><property name="driver" value="com.mysql.jdbc.Driver"/><property name="url" value="jdbc:mysql://localhost:3306/exam?useSSL=false"/><property name="username" value="****"/><property name="password" value="****"/></dataSource></environment></environments><!--映射xml的路径配置--><mappers><mapper resource="mybatis-mappers/Topic.xml"/></mappers>
</configuration>
1.3.业务类TopicApp.java
package pers.hanchao.himybatis.curd;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 org.apache.log4j.Logger;import java.io.IOException;
import java.io.Reader;
import java.util.ArrayList;
import java.util.List;/*** <p>通过XML+IDAO配置MyBatis,实现单表的增删改查</p>* @author hanchao 2018/1/27 0:35**/
public class TopicApp {/** SqlSessionFactory用于创建SqlS */private static SqlSessionFactory sqlSessionFactory;/** Reader用于读取配置文件 */private static Reader reader;private static final Logger LOGGER = Logger.getLogger(TopicApp.class);static{try{//读取MyBatis总配置文件reader = Resources.getResourceAsReader("mybatis-config.xml");//根据配置文件创建SqlSessionFactorysqlSessionFactory = new SqlSessionFactoryBuilder().build(reader);} catch (IOException e) {e.printStackTrace();LOGGER.error("加载MyBatis配置文件出错!");}}/*** <p>简单的增删改查</p>* @author hanchao 2018/1/27 0:37**/public static void main(String[] args) {//创建数据库会话SqlSession sqlSession = sqlSessionFactory.openSession();try{//调用IDAOITopicDAO topicDAO = sqlSession.getMapper(ITopicDAO.class);//查询所有的话题showTopicList(topicDAO.queryTopicList());//新增一个话题Topic topic = new Topic(1,"題目1",100,"答案1");topicDAO.insertTopic(topic);LOGGER.info("新增一个话题:" + topic.toString());//查询所有的话题showTopicList(topicDAO.queryTopicList());//修改一個话题topic = new Topic(1,"题目1",88,"答案1111");topicDAO.updateTopic(topic);LOGGER.info("修改一个话题:" + topic.toString());//查询所有的话题showTopicList(topicDAO.queryTopicList());//删除一个话题topicDAO.deleteTopic(1);LOGGER.info("删除一个话题:id = 1");//查询所有的话题showTopicList(topicDAO.queryTopicList());//新增5个话题for (int i = 0; i < 5; i++) {int index = 5 + i;topic = new Topic(index,"题目" + index,60 + index,"答案" + index);topicDAO.insertTopic(topic);LOGGER.info("新增一个话题:" + topic.toString());}//查询所有的话题showTopicList(topicDAO.queryTopicList());//查询一个题目Topic topic1 = topicDAO.queryTopicById(9);LOGGER.info("查询一个话题,id = 9,result:" + topic1.toString());//事务提交sqlSession.commit();}catch (Exception e){//事务回滚sqlSession.rollback();}finally {//关闭连接sqlSession.close();}}/*** <p>打印所有话题</p>* @author hanchao 2018/1/27 0:21**/private static void showTopicList(List<Topic> topicList) {LOGGER.info("===================================显示当前所有话题===================================");//如果List无值,则打印无信息if (null == topicList || topicList.size() == 0){LOGGER.info("暂无话题.");}else {for (Topic topic : topicList){LOGGER.info(topic.toString());}}LOGGER.info("====================================================================================\n");}
}
通过上面的实例代码,可以总结:在单独使用MyBatis时,如需完成一次数据库操作,出了一些必要工作,如编写实体类、XML映射文件和IDAO类等,至少还需要进行三大步骤操作:
配置mybatis-config.xml,配置项至少需要有:
- typeAliases:类型依赖别名配置
- dataSource:数据库连接信息配置
- mapper:XML映射文件配置
在业务代码中获取DAO层实现类对象,一般流程如下:
- 通过Reader读取配置文件mybatis-config.xml
- 通过配置文件信息,创建SqlSessionFactory,即SQL会话工厂
- 通过SQL会话工厂开启数据库连接会话,即SqlSession
- 通过数据库连接会话获取映射的DAO层实现类对象
通过DAO层实现类对象进行数据库查询与事务控制,一般流程如下:
- 执行数据库操作方法
- 如果执行成功,就进行事务提交(commit)
- 如果执行失败,就进行事务回滚(rollback)
- 无论失败还是成功,最后都需要关闭事务(close)
可以发现,如果单独使用MyBatis实现业务功能,有以下不方便之处:
- 每当有新的实体类产生时,都需要进行typeAliases和mapper的配置。
- 在每个业务操作类中,都需要进行mybatis-config.xml的读取、SqlSessionFactory的创建、SqlSession的开启等操作。
- 每次涉及事务操作,都需要手动进行commit、rollback和close。
很多代码都是重复的,都可以抽取出来进行处理。当然可以自己动手实现,不过根据“不要重复造轮子”的原则,这里更推荐通过SSM进行整合,减少重复代码处理。
通过初步整合SSM之后,如需完成一次数据库操作,只需要在业务类中调用数据库操作方法即可,上面的其他步骤都交由Spring进行管理。
下面介绍对SSM的初步整合。
2.SSM初步整合的配置方式
2.1.目录结构
src
\---main\---java| \---pers| \---hanchao| \---himybatis| \---curd| | \---Topic.java| | |---ITopicDAO.java| |---curd| \---TopicController.java| |---TopicService.java\---resources| \---mybatis-mappers| | \---Topic.xml| |---log4j.properties| |---jdbc.properties| |---applicationContext.xml| |---spring-mybatis-jdbc.xml\---webapp\---ssm| \---topic.jsp|---WEB-INF| \---web.xml| |---spring-mvc-servlet.xml|---index.jsp
通过对比之前的目录结构:
- 实体类Topic.java、DAO层接口ITopicDAO.java和XML映射文件Topic.xml都没无变化
- 业务操作类由原来的TopicApp.java替换成了TopicController.java和TopicService.java
- 移除了MyBatis的配置文件:mybatis-config.xml,由下面两个配置文件进行替代:
- 数据库连接信息属性文件:jdbc.properties
- Spring与MyBatis的配置文件:spring-mybatis-jdbc.xml
- 新增了Spring的总配置文件:applicationContext.xml
- 新增了Spring MVC的总配置文件:spring-mvc-servlet.xml
- 新增了Web项目的启动文件:web.xml
- 新增了Web项目的首页:index.jsp
- 新增了业务页面:topic.jsp
2.2.MyBatis的整合
MyBatis的原来的方式:
mybatis-config.xml + TopicApp.java
SSM中MyBatis的使用方式:
spring-mybatis-jdbc.xml + jdbc.properties + TopicController.java + TopicService.java
下面这些文件进行说明:
2.2.1.spring-mybatis-jdbc.xml
spring-mybatis-jdbc.xml的作用可以总结如下:
1. 通过SqlSessionFactoryBean的的DataSource结合Spring的DataSource,替代MyBatis配置文件的DataSource
2. 通过SqlSessionFactoryBean的mapperLocations,替代MyBatis配置文件的mappers配置
3. 通过SqlSessionFactoryBean的typeAliasesPackage,替代MyBatis配置文件的typeAliases配置
4. 通过Spring的DataSourceTransactionManager,替代MyBatis配置文件的JdbcTransactionManager配置
5. 通过MapperScannerConfigurer的sqlSessionFactoryBeanName,替代MyBatis建立会话工厂的new SqlSessionFactoryBuilder().build(reader)方式。
6. 通过MapperScannerConfigurer的basePackage,替代MyBatis实例化Dao层对象的sqlSession.getMapper(IDAO.class)方式
具体看配置
<?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"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/tx http://www.springframework.org/schema/tx/spring-tx.xsd"><!--数据源配置--><!--通过property-placeholder获取属性文件配置的值--><context:property-placeholder file-encoding="utf-8" location="classpath:jdbc.properties"/><!--配置DataSource--><bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource"><property name="driverClassName" value="${jdbc.driverClassName}"/><property name="url" value="${jdbc.url}"/><property name="username" value="${jdbc.username}"/><property name="password" value="${jdbc.password}"/></bean><!--配置SqlSessionFactory--><bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean"><!--用Spring的dataSource替代原mybatis-config.xml的dataSource--><property name="dataSource" ref="dataSource"/><!--配置MyBatis总配置文件,如果通过其他配置取代了所有的MyBatis配置,则可以不要此项配置--><!--<property name="configLocation" value="classpath:mybatis-config.xml"/>--><!--配置MyBatis映射文件,取代原mybatis-config.xml的mappers配置--><property name="mapperLocations" value="classpath:mybatis-mappers/*.xml"/><!--配置类型别名,取代原mybatis-config.xml的typeAliases,最好将实体放在同一类型的包下--><property name="typeAliasesPackage" value="pers.hanchao.himybatis.curd"/></bean><!--配置IDAO接口所在扫描路径,主要MyBatis映射文件里要配置正确的IDAO路径--><bean class="org.mybatis.spring.mapper.MapperScannerConfigurer"><!--配置扫描IDAO的路径,替代原MyBatis的ITopicDAO topicDAO = sqlSession.getMapper(ITopicDAO.class)的实例化形式--><property name="basePackage" value="pers.hanchao.himybatis.curd"/><!--配置sqlSessionFactory,替代private static SqlSessionFactory sqlSessionFactory的注入形式--><property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" /></bean><!--事务管理--><bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"><property name="dataSource" ref="dataSource"/></bean><!--基于注解的声明式事务--><tx:annotation-driven transaction-manager="transactionManager"/>
</beans>
2.2.2.jdbc.properties
其中jdbc.properties内容如下:
jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/exam?useSSL=false
jdbc.username=****
jdbc.password=*******
对于上述的第5条和第6条,通过TopicController.java和TopicService.java可以更加直观的感受:
2.2.3.业务控制类:TopicController.java
第5条和第6条说明如下:
5. 通过MapperScannerConfigurer的sqlSessionFactoryBeanName,替代MyBatis建立会话工厂的new SqlSessionFactoryBuilder().build(reader)方式。
6. 通过MapperScannerConfigurer的basePackage,替代MyBatis实例化Dao层对象的sqlSession.getMapper(IDAO.class)方式
在TopicController.java中,不再需要进行以下操作:
- 通过Reader读取配置文件mybatis-config.xml
- 通过配置文件信息,创建SqlSessionFactory,即SQL会话工厂
- 通过SQL会话工厂开启数据库连接会话,即SqlSession
- 通过数据库连接会话获取映射的DAO层实现类对象
TopicController.java
package pers.hanchao.himybatis.ssm;import org.apache.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import pers.hanchao.himybatis.curd.entity.Topic;
import pers.hanchao.himybatis.utils.JsonResult;
import pers.hanchao.himybatis.utils.ShowList;import java.util.List;/*** <p>Spring + Spring MVC + MyBatis初步整合实例(RESTFul风格)</p>* @author hanchao 2018/1/28 19:19**/
@RestController
@RequestMapping("/ssm")
public class TopicController {@Autowiredprivate TopicService topicService;private static final Logger LOGGER = Logger.getLogger(TopicController.class);/*** <p>查询一个话题</p>* @author hanchao 2018/1/28 16:58**/@GetMapping("/topic/{id}")public JsonResult<Topic> queryTopicById(@PathVariable Integer id){Topic topic = this.topicService.queryTopicById(id);JsonResult<Topic> jsonResult = new JsonResult<Topic>();//非空判断if (null != topic){jsonResult.addList(topic);LOGGER.info(topic.toString());}else {jsonResult.setMessage("无查询结果");LOGGER.info("无查询结果");}return jsonResult;}/*** <p>查询所有的话题</p>* @author hanchao 2018/1/28 18:02**/@GetMapping("/topic/")public JsonResult<Topic> queryTopicList(){List<Topic> topicList = this.topicService.queryTopicList();JsonResult<Topic> jsonResult = new JsonResult<Topic>();//非空判断if (null != topicList && topicList.size() > 0){jsonResult.setList(topicList);ShowList.showList(topicList);}else {jsonResult.setMessage("无查询结果");LOGGER.info("无查询结果");}return jsonResult;}/*** <p>新增一个话题</p>* @author hanchao 2018/1/28 17:35**/@PostMapping("/topic/")public JsonResult<Topic> insertTopic(@RequestBody Topic topic){Topic topic1 = this.topicService.queryTopicById(topic.getId());//如果已经存在此话题,则不能再新增if (null != topic1){return new JsonResult<Topic>(-1,"话题已经存在!");}else{this.topicService.insertTopic(topic);return new JsonResult<Topic>();}}/*** <p>修改一个话题</p>* @author hanchao 2018/1/28 17:50**/@PutMapping("/topic/")public JsonResult<Topic> putTopic(@RequestBody Topic topic){Topic topic1 = this.topicService.queryTopicById(topic.getId());if (null != topic1){this.topicService.updateTopic(topic);return new JsonResult<Topic>();}else{//如果不存在此话题,则不能进行替换return new JsonResult<Topic>(-1,"话题不存在!");}}/*** <p>删除一个话题</p>* @author hanchao 2018/1/28 17:59**/@DeleteMapping("/topic/{id}")public JsonResult<Topic> deleteTopic(@PathVariable Integer id){Topic topic1 = this.topicService.queryTopicById(id);if (null != topic1){this.topicService.deleteTopic(id);return new JsonResult<Topic>();}else{//如果不存在此话题,则不能进行删除return new JsonResult<Topic>(-1,"话题不存在!");}}
}
2.2.4.业务处理类:TopicService.java
在TopicService.java中,不再需要进行以下操作:
- 如果执行成功,就进行事务提交(commit)
- 如果执行失败,就进行事务回滚(rollback)
- 无论失败还是成功,最后都需要关闭事务(close)
直接调用DAO层提供的数据库操作方法即可。
TopicService.java
package pers.hanchao.himybatis.ssm;import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import pers.hanchao.himybatis.curd.dao.ITopicDAO;
import pers.hanchao.himybatis.curd.entity.Topic;import java.util.List;/*** <p>Service层</p>* @author hanchao 2018/1/28 19:20**/
@Service
public class TopicService {@Autowiredprivate ITopicDAO topicDAO;public Topic queryTopicById(Integer id) {return this.topicDAO.queryTopicById(id);}@Transactionalpublic void insertTopic(Topic topic) {this.topicDAO.insertTopic(topic);}@Transactionalpublic void updateTopic(Topic topic) {this.topicDAO.updateTopic(topic);}@Transactionalpublic void deleteTopic(Integer id) {this.topicDAO.deleteTopic(id);}@Transactionalpublic List<Topic> queryTopicList(){return this.topicDAO.queryTopicList();}
}
2.3.Spring和Spring MVC的其他配置
本章Spring和Spring MVC不是重点,不多说,直接给代码。
pom.xml:jar包依赖
<springframework.version>5.0.0.RELEASE</springframework.version><servlet-api.version>3.1.0</servlet-api.version><jsp-api.version>2.0</jsp-api.version><jstl.version>1.2</jstl.version><commons-logging.version>1.2</commons-logging.version><commons-lang3.version>3.3.2</commons-lang3.version><commons-io.version>2.4</commons-io.version><tomcat-plugin.version>2.2</tomcat-plugin.version><jackson.version>2.9.0</jackson.version><log4j.version>1.2.17</log4j.version><junit.version>4.12</junit.version><mysql.version>5.1.40</mysql.version><mybatis.version>3.4.5</mybatis.version><mybatis-spring.version>1.3.1</mybatis-spring.version>
web.xml:Web项目启动加载过滤器、Spring MVC前端控制器、Spring上下文环境和欢迎页面。
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"xmlns="http://java.sun.com/xml/ns/javaee"xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"version="3.0"><display-name>Hi MyBatis</display-name><!--编码转换器,解决POST请求中文乱码问题--><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><servlet-name>spring-mvc</servlet-name><servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class><load-on-startup>1</load-on-startup></servlet><servlet-mapping><servlet-name>spring-mvc</servlet-name><url-pattern>/</url-pattern></servlet-mapping><!--Spring上下文配置--><context-param><param-name>contextConfigLocation</param-name><param-value>classpath:applicationContext.xml</param-value></context-param><!--上下文环境加载监听器--><listener><listener-class>org.springframework.web.context.ContextLoaderListener</listener-class></listener><welcome-file-list><welcome-file>index.jsp</welcome-file></welcome-file-list>
</web-app>
spring-mvc-servlet.xml:SpringMVC的配置文件,包括开启注解、自动装配、视图解析器以及静态资源配置等。
<?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/beanshttp://www.springframework.org/schema/beans/spring-beans.xsdhttp://www.springframework.org/schema/contexthttp://www.springframework.org/schema/context/spring-context.xsdhttp://www.springframework.org/schema/mvchttp://www.springframework.org/schema/mvc/spring-mvc.xsd"><!--开启component注解自动扫描--><context:component-scan base-package="pers.hanchao.himybatis.ssm"/><!-- Spring MVC默认的注解映射的支持 :提供Controller请求转发,json自动转换等功能--><mvc:annotation-driven /><!--开启注解:提供spring容器的一些注解--><context:annotation-config/><!--静态资源处理方式一:使用mvc:default-servlet-handler,default-servlet-name="所使用的Web服务器默认使用的Servlet名称",一般情况下为"default" --><!--<mvc:default-servlet-handler default-servlet-name="default"/>--><!--静态资源处理方式二:通过mvc:resources指定静态资源--><!--所有URI为"/static/**"的资源都从"/static/"里查找,这些静态资源缓存1年(即 : 31536000秒)--><mvc:resources mapping="/static/**" location="/static/" cache-period="31536000"/><!--默认视图解析器:jsp--><bean class="org.springframework.web.servlet.view.InternalResourceViewResolver"><property name="prefix" value="/"/><property name="suffix" value=".jsp"/><property name="order" value="0"/><property name="contentType" value="charset=UTF-8"></property></bean>
</beans>
applicationContext.xml:Spring的总配置文件,通过import加载其他配置文件,如spring-mybatis-jdbc.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"><!--数据源信息:PropertyPlaceHolder、DataSource、SqlSessionFactory--><import resource="classpath:spring-mybatis-jdbc.xml"/>
</beans>
topic.jsp:业务展示页面
<%--Created by IntelliJ IDEA.User: hanchaoDate: 2018/1/28Time: 17:07To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head><title>话题首页</title><style type="text/css">div{margin: 5px 5px; }.div-left {float: left;margin: 5px 5px;}.div-text-center {text-align:center; border:1px solid #96c2f1; background:#eff7ff;}textarea{border:1px solid #9bdf70;background:#f0fbeb}.in-text{width: 30px;}</style>
</head>
<body>
<div class="div-left"><textarea id="message" cols="50" rows="50"></textarea>
</div>
<div class="div-left"><div class="div-text-center"><input type="button" value="查询所有(GET)" onclick="topics('GET')"/></div><div class="div-text-center"><label>话题id:</label><input class="in-text" type="text" id="id" value="1"/><input type="button" value="查询一个(GET)" onclick="topic('GET')"/><input type="button" value="删除一个(DELETE)" onclick="topic('DELETE')"></div><div class="div-text-center"><table style="text-align: right;width: 325px;"><tr><td><label>id</label></td><td><input id="new_id" type="text" value="1"/> </td></tr><tr><td><label>题目</label></td><td><input id="new_title" type="text" value="新话题"/> </td></tr><tr><td><label>分数</label></td><td><input id="new_score" type="text" value="100"/> </td></tr><tr><td><label>答案</label></td><td><input id="new_answer" type="text" value="新答案"/> </td></tr><tr><td><input type="button" value="新增(POST)" onclick="topic1('POST')"> </td><td><input type="button" value="修改(PUT)" onclick="topic1('PUT')"> </td></tr></table></div>
</div>
</body>
<script type="text/javascript" src="../static/jquery-3.2.1.min.js"></script>
<script type="text/javascript">/*** 获取一个话题:[GET]/ssm/topic/{id}*//*** 删除一个话题:[DELETE]/ssm/topic/{id}*/function topic(type) {$.ajax({type:type,url:"/ssm/topic/" + $("#id").val(),contentType:"application/json;charset=utf-8",success:function (data) {console.log(data);var html = "url[" + type + "]:/ssm/topic/" + $("#id").val() + "\n\nresult:\n" + JSON.stringify(data, null, 4);$("#message").html(html);}});}/*** 获取全部话题:[GET]/ssm/topic/*//*** 删除全部话题:[DELETE]/ssm/topic/*/function topics(type) {$.ajax({type:type,url:"/ssm/topic/",contentType:"application/json;charset=utf-8",success:function (data) {console.log(data);var html = "url[" + type + "]:/ssm/topic/\n\nresult:\n" + JSON.stringify(data, null, 4);$("#message").html(html);}});}/*** 新增一个话题:[POST]/ssm/topic/*//*** 替换一个话题:[PUT]/ssm/topic/*//*** 修改一个话题:[PATCH]/ssm/topic/*/function topic1(type) {$.ajax({type:type,url:"/ssm/topic/",data:JSON.stringify({id:$("#new_id").val(),title:$("#new_title").val(),score:$("#new_score").val(),answer:$("#new_answer").val()}),contentType:"application/json;charset:utf-8",success:function (data) {console.log(data);var html = "url[" + type + "]:/ssm/topic/\n\nresult:\n" + JSON.stringify(data,null,4);$("#message").html(html);}});}
</script>
</html>