首页 > 其他分享 >SSM框架整合(十五)

SSM框架整合(十五)

时间:2022-11-10 15:35:38浏览次数:37  
标签:www http 框架 int springframework SSM 十五 org schema


你未看此花时,则此花与汝心同归于寂, 你来看此花时,此花颜色一时明白起来,便知此花不在你的心外。

上一章简单介绍了SpringMVC的拦截器(十四),如果没有看过,​​请观看上一章​​。

一. SSM框架的整合

SSM 框架, 指的是 Spring+SpringMVC+MyBatis 框架。

其中, Spring的知识可以 参考老蝴蝶以前的文章,​​Spring的"两个蝴蝶飞,你好"的简单开发(一)​​ MyBatis也可以参考老蝴蝶以前的文章: MyBatis的简单了解(一)

SSM的整合,是在以前的基础之上,进行整合的,不对以前的知识进行讲解。

SSM的整合,也是跟以前SSH的整合一样,两两整合。 但SpringMVC是Spring框架的一部分,所以SpringMVC与Spring框架不需要整合。
所以,直接 Spring与MyBatis进行整合即可。

整合SSM 实现 REST 风格的CRUD操作。

二. SSM框架整合的详细步骤

二.一 新建一个动态的Web项目,名称为SSM, 选择2.5版本的

二.二 在src下创建包,在SSM项目下创建 config 的源文件夹

src 下创建的包分别为 : com.yjl.pojo, com.yjl.mapper, com.yjl.service, com.yjl.service.impl, com.yjl.action, com.yjl.utils , 来放置代码

创建源文件夹为 config, 来放置 配置文件

SSM框架整合(十五)_java

二.三 创建mybatis 数据库,里面创建 user表。 以user表为例进行整合

User的 字段有 ,id,name,sex,age,description, id为Integer,自动增长,主键。

SSM框架整合(十五)_spring_02

数据有:

SSM框架整合(十五)_spring_03

二.四 导入SSM 需要的整合Jar包

1 . MyBatis 所需要的Jar包

SSM框架整合(十五)_spring_04

共15个。

2 . Spring+SpringMVC所需要的 jar包

SSM框架整合(十五)_SSM框架整合_05


共 25个

3 . JSTL模板类 库,有两个

SSM框架整合(十五)_SSM框架整合_06

4 . 数据库连接池 C3P0所需要的 jar包 或者是dbcp 所需要的jar包。 用dbcp吧,区别于SSH. 有两个

SSM框架整合(十五)_xml_07

5 . mysql 数据库的驱动 1个。

SSM框架整合(十五)_java_08

6 . MyBatis与 Spring整合所需要的jar包 由MyBatis提供, 注意版本,选择1.3版本的。 1个。

SSM框架整合(十五)_xml_09

将这些jar 包放置在 WEB-INF 下面的lib文件夹下。

共有 16+25+2+2+1+1= 46个。

导入之后, 发现 commons-logging-1.2.jar 包 重复,(Spring与MyBatis都有),去除一个。

log4j.jar 有两个版本, log4j-1.2.17.jar(MyBatis的), log4j-1.2.16.jar(Spring的),去除低版本的,保留 1.2.17

故最后只剩下 44个 jar包。

SSM框架整合(十五)_xml_10

二.五 源文件夹 config下创建 db.properties 文件,来存储数据库的连接配置

db.properties:

##关于数据库的属性
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?characterEncoding=utf8
jdbc.username=root
jdbc.password=abc123
## 关于数据库连接池的属性
jdbc.maxActive=30
jdbc.maxIdle=5

在数据库前面加上前缀, jdbc,避免直接 url,username 与spring中的属性重复。

二.六 源文件夹config 下创建log4j.properties, 来存储日志信息

log4j.properties

### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n

### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=debug, stdout

二.七 源文件夹 config下创建 mybatis文件夹,下面再创建 SqlMapConfig.xml 文件,存储MyBatis的配置

二.八 config下创建spring的文件夹,下面再创建 spring的配置文件

如 applicationContext-dao.xml(Spring与dao的整合) , applicationContext-service.xml(Spring与Service的整合), springmvc.xml (SpringMVC的配置文件)

创建之后, config 源文件夹下的目录如下所示:

SSM框架整合(十五)_xml_11

上面是配置基本的文件,还没有到真正开始呢。 现在,才正式进入配置。

二.九 利用MyBatis的逆向工程来生成 user 表的逆向代码

MyBatis的逆向工程,可以观看老蝴蝶写的文章: ​​MyBatis逆向工程的使用(十二)​​

逆向工程执行之后 ,会生成 User.java, UserExample.java, UserMapper.java, UserMapper.xml 文件。

将 User.java,UserExample.java 复制到 com.yjl.pojo 包下, 将UserMapper.java, UserMapper.xml 复制到 com.yjl.mapper 包下。

在MyBatis中添加分页查询的功能, 关于MyBatis的分页,可以观看老蝴蝶以前写的文章: ​​MyBatis的pageHelper分页插件的使用(十五)​​

需要在UserExample, UserMapper.java, UserMapper.xml 中添加分页的功能代码。

故需要对其进行稍微的改变。

改变后的文件如下:

User.java

package com.yjl.pojo;

import java.io.Serializable;

public class User implements Serializable{
private static final long serialVersionUID = 6736354022794444729L;

private Integer id;

private String name;

private Integer age;

private String sex;

private String description;

public Integer getId() {
return id;
}

public void setId(Integer id) {
this.id = id;
}

public String getName() {
return name;
}

public void setName(String name) {
this.name = name == null ? null : name.trim();
}

public Integer getAge() {
return age;
}

public void setAge(Integer age) {
this.age = age;
}

public String getSex() {
return sex;
}

public void setSex(String sex) {
this.sex = sex == null ? null : sex.trim();
}

public String getDescription() {
return description;
}

public void setDescription(String description) {
this.description = description == null ? null : description.trim();
}

@Override
public String toString() {
return "User [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + ", description=" + description
+ "]";
}
}

UserExample.java

package com.yjl.pojo;

import java.util.ArrayList;
import java.util.List;

public class UserExample {
protected String orderByClause;

protected boolean distinct;

//添加两个字段,用于分页。
private int start; //开始的位置

private int offset; //每页显示的最大数目

public int getStart() {
return start;
}

public void setStart(int start) {
this.start = start;
}

public int getOffset() {
return offset;
}

public void setOffset(int offset) {
this.offset = offset;
}

// .... 省略逆向工程生成的代码, 主要是太多了,老蝴蝶就不复制了。

}

UserMapper.java

package com.yjl.mapper;

import java.util.List;

import org.apache.ibatis.annotations.Param;

import com.yjl.pojo.User;
import com.yjl.pojo.UserExample;

public interface UserMapper {
int countByExample(UserExample example);

int deleteByExample(UserExample example);

int deleteByPrimaryKey(Integer id);

int insert(User record);

int insertSelective(User record);

List<User> selectByExample(UserExample example);

User selectByPrimaryKey(Integer id);

int updateByExampleSelective(@Param("record") User record, @Param("example") UserExample example);

int updateByExample(@Param("record") User record, @Param("example") UserExample example);

int updateByPrimaryKeySelective(User record);

int updateByPrimaryKey(User record);

//根据sql语句进行相应的查询
List<User> selectBySQL(@Param(value="limit")int limit,
@Param(value="offset") int offset);
}

UserMapper.xml

代码也太多了,就不复制了,在逆向工程生成的代码之上, 把 selectBySQL写出来即可。

<!-- 分页查询 -->
<select id="selectBySQL" resultMap="BaseResultMap" parameterType="com.yjl.pojo.UserExample" >
select
<include refid="Base_Column_List" />
from user
limit #{limit},#{offset}
</select>

样式为:

SSM框架整合(十五)_SSM框架整合_12

二.十 SqlMapConfig.xml 的Mybatis文件的配置

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>
<settings>
<!-- 设置配置文件 -->
<!-- 开启二级缓存 -->
<setting name="cacheEnabled" value="true"/>
<!-- 控制懒加载的 -->
<setting name="lazyLoadingEnabled" value="true"/>
<setting name="aggressiveLazyLoading" value="false"/>
<setting name="multipleResultSetsEnabled" value="true"/>
<setting name="useColumnLabel" value="true"/>
<setting name="useGeneratedKeys" value="false"/>
<setting name="autoMappingBehavior" value="PARTIAL"/>
<setting name="autoMappingUnknownColumnBehavior" value="WARNING"/>
<setting name="defaultExecutorType" value="SIMPLE"/>
<setting name="defaultStatementTimeout" value="25"/>
<setting name="defaultFetchSize" value="100"/>
<setting name="safeRowBoundsEnabled" value="false"/>
<setting name="localCacheScope" value="SESSION"/>
<setting name="jdbcTypeForNull" value="OTHER"/>
<setting name="lazyLoadTriggerMethods" value="equals,clone,hashCode,toString"/>
<!-- 设置日志为 log4j -->
<setting name="logImpl" value="LOG4J"/>
</settings>
<!-- 配置别名 -->
<typeAliases>
<!-- 定义包的形式 ,可以多个-->
<package name="com.yjl.pojo"/>
</typeAliases>

<!-- 放置在别名之后,环境之前 -->
<plugins>
<!-- 分页插件,引入拦截器 -->
<plugin interceptor="com.github.pagehelper.PageInterceptor">
<!-- 指定数据库为mysql,虽然会自动监测。 -->
<property name="helperDialect" value="mysql"/>
</plugin>
</plugins>

</configuration>

相比于以前的MyBatis的配置, 去除掉数据库配置和映射文件的配置, 由applicationContext-dao.xml 来完成。

只保留 setting,typeAliases, plugins 三个配置。

二.十一 applicationContext-dao.xml 的配置

applicationContext-dao.xml

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 配置数据源 ,dbcp -->
<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>
<!-- sqlSessionFactory -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
</bean>
<!-- mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 -->
<property name="basePackage" value="com.yjl.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>

完成的工作是, 配置数据源,生成sqlSessionFactory, 配置扫描器。

二.十二 创建 UserService 接口和 UserServiceImpl 实现类

UserService 接口:

package com.yjl.service;

import java.util.List;

import com.yjl.pojo.User;
import com.yjl.pojo.UserExample;

/**
@author:yuejl
@date: 2019年9月9日 下午7:40:35
@Description 类的相关描述
*/
public interface UserService {
int countByExample(UserExample example);

int deleteByExample(UserExample example);

int deleteByPrimaryKey(Integer id);

int insert(User record);

int insertSelective(User record);

List<User> selectByExample(UserExample example);

User selectByPrimaryKey(Integer id);

int updateByExampleSelective( User record,UserExample example);

int updateByExample(User record, UserExample example);

int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
//根据sql语句进行相应的查询
List<User> selectBySQL(int limit, int offset);
}

UserServiceImpl 实现类:

package com.yjl.service;

import java.util.List;

import com.yjl.pojo.User;
import com.yjl.pojo.UserExample;

/**
@author:yuejl
@date: 2019年9月9日 下午7:40:35
@Description 类的相关描述
*/
public interface UserService {
int countByExample(UserExample example);

int deleteByExample(UserExample example);

int deleteByPrimaryKey(Integer id);

int insert(User record);

int insertSelective(User record);

List<User> selectByExample(UserExample example);

User selectByPrimaryKey(Integer id);

int updateByExampleSelective( User record,UserExample example);

int updateByExample(User record, UserExample example);

int updateByPrimaryKeySelective(User record);
int updateByPrimaryKey(User record);
//根据sql语句进行相应的查询
List<User> selectBySQL(int limit, int offset);
}

样式如下:

SSM框架整合(十五)_xml_13

二.十三 applicationContext-service.xml 的配置

<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

<-- 事管理器
对mybatis操作数据库事务控制,需要spri层ng使用jdbc的事务控制类
-->
<!--添加扫描,需要扫描action层和service层-->
<context:component-scan base-package="com.yjl"></context:component-scan>


<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源
dataSource在applicationContext-dao.xml中配置了
-->
<property name="dataSource" ref="dataSource"/>
</bean>

<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<!--列举常见的方法形式-->
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="edit*" propagation="REQUIRED" />
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="add*" propagation="REQUIRED" />
<tx:method name="new*" propagation="REQUIRED" />
<tx:method name="set*" propagation="REQUIRED" />
<tx:method name="remove*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="change*" propagation="REQUIRED" />
<tx:method name="get*" propagation="REQUIRED" read-only="true" />
<tx:method name="find*" propagation="REQUIRED" read-only="true" />
<tx:method name="count*" propagation="REQUIRED" read-only="true" />
<tx:method name="load*" propagation="REQUIRED" read-only="true" />
<tx:method name="*" propagation="REQUIRED" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- aop -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.yjl.service.impl.*.*(..))"/>
</aop:config>
</beans>

主要是配置事务, 利用AOP的思想。

二.十四 后端UserAction

实现CRUD的操作, 注入 UserService 接口

UserAction.java

package com.yjl.action;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

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.ResponseBody;

import com.yjl.pojo.User;
import com.yjl.service.UserService;

/**
@atuhor:yuejl
@Description: 类描述
*/
@Controller
@RequestMapping(value="/user")
public class UserAction {
@Autowired
private UserService userService;
//转到登录的页面
@RequestMapping(value="toLogin")
public String toLogin(Model model){
model.addAttribute("user",new User());
return "user/login";
}
//一定不要忘记添加 produces 属性。 添加时,方法为POST
@RequestMapping(value="add",method=RequestMethod.POST,produces={"application/json"})
public @ResponseBody Map<String,Object> add(User user){
userService.insert(user);
Map<String,Object> resultMap=new HashMap<String,Object>();
resultMap.put("request_status",true);
return resultMap;
}
//修改时,方法为PUT
@RequestMapping(value="edit/{id}",method=RequestMethod.PUT,produces={"application/json"})
public @ResponseBody Map<String,Object> edit(User user){
userService.updateByPrimaryKeySelective(user);
Map<String,Object> resultMap=new HashMap<String,Object>();
resultMap.put("request_status",true);
return resultMap;
}
//删除时,方法用DELETE
@RequestMapping(value="deleteById/{id}",method=RequestMethod.DELETE,produces={"application/json"})
public @ResponseBody Map<String,Object> deleteById(@PathVariable(value="id") int id){
userService.deleteByPrimaryKey(id);
Map<String,Object> resultMap=new HashMap<String,Object>();
resultMap.put("request_status",true);
return resultMap;
}
//查询时,用GET
@RequestMapping(value="findById/{id}",method=RequestMethod.GET,produces={"application/json"})
public @ResponseBody Map<String,Object> findById(@PathVariable(value="id") int id){
User user=userService.selectByPrimaryKey(id);
Map<String,Object> resultMap=new HashMap<String,Object>();
resultMap.put("request_status",true);
resultMap.put("user",user);
return resultMap;
}
//查询时,用GET
@RequestMapping(value="findAll",method=RequestMethod.GET,produces={"application/json"})
public @ResponseBody Map<String,Object> findAll(){
List<User> userList=userService.selectBySQL(1, 10);
Map<String,Object> resultMap=new HashMap<String,Object>();
resultMap.put("request_status",true);
resultMap.put("userList",userList);
return resultMap;
}
}

二.十五 springmvc.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:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
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/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd ">
<!-- 配置的是注解的,重写视图解析器, springmvc里面只扫描action层,不能扫描其他层 -->
<context:component-scan base-package="com.yjl.action"></context:component-scan>

<!--配置静态资源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
<mvc:resources location="/image/" mapping="/image/**"></mvc:resources>

<!-- 设置fastjson的配置方案 -->
<mvc:annotation-driven>
<!-- 设置不使用默认的消息转换器 -->
<mvc:message-converters register-defaults="false">
<!-- 配置Spring的转换器 -->
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.xml.XmlAwareFormHttpMessageConverter"/>
<bean class="org.springframework.http.converter.ByteArrayHttpMessageConverter"/>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<!-- 配置fastjson中实现HttpMessageConverter接口的转换器 -->
<bean id="fastJsonHttpMessageConverter"
class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
<!-- 加入支持的媒体类型:返回contentType -->
<property name="supportedMediaTypes">
<list>
<!-- 这里顺序不能反,一定先写text/html,不然ie下会出现下载提示 -->
<value>text/html;charset=UTF-8</value>
<value>application/json;charset=UTF-8</value>
</list>
</property>
<!-- 可添加其他的属性来扩展功能,如日期 -->
<property name="features">
<list>
<!-- 默认的意思就是不配置这个属性,配置了就不是默认了 -->
<!-- 是否输出值为null的字段 ,默认是false-->
<value>WriteMapNullValue</value>

<value>WriteNullNumberAsZero</value>
<value>WriteNullListAsEmpty</value>
<value>WriteNullStringAsEmpty</value>
<value>WriteNullBooleanAsFalse</value>
<value>WriteDateUseDateFormat</value>
</list>
</property>
</bean>
</mvc:message-converters>
</mvc:annotation-driven>

<!-- 视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
</beans>

配置json,和视图解析器。 如果有转换器和国际化的话,按照老蝴蝶以前讲的知识进行配置。

二.十六 web.xml 配置文件

<?xml version="1.0" encoding="UTF-8"?>
<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_2_5.xsd" id="WebApp_ID" version="2.5">
<display-name>SSM</display-name>

<!-- 启动spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>

<!-- 乱码过滤器 -->
<filter>
<filter-name>EncodingFilter</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>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!-- 隐藏域方法 -->
<filter>
<filter-name>hiddenHttpMethodFilter</filter-name>
<filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>hiddenHttpMethodFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>

<!--前端控制 器 -->
<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:spring/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>

<!-- 欢迎页 -->
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
</web-app>

二.十七 前端 login.jsp 页面

采用 Ajax 进行传输数据。

<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<script type="text/javascript" src="/SSM/js/jquery-2.1.1.min.js"></script>
<%@ taglib prefix="form" uri="http://www.springframework.org/tags/form" %>
<title>展示</title>
</head>
<body>
<h2>两个蝴蝶飞,SSM框架整合使用</h2>
<form:form commandName="user" type="post">
<button type="button" id="add" onclick="addJson()">添加</button><br/>
<button type="button" id="edit" onclick="editJson()">修改</button><br/>
<button type="button" id="delete" onclick="delJson()">删除</button><br/>
<button type="button" id="findById" onclick="findByIdJson()">查询id></button><br/>
<button type="button" id="findAll" onclick="findAllJson()">查询全部</button><br/>
<div id="showId"> 展示的信息</div>
</form:form>

<script>
function addJson(){
jsonAjax("add","add","id=10&name=精灵妹&password=1234&sex=女&age=24&description=一个快乐的精灵&_method=POST");
}
function editJson(){
jsonAjax("edit","edit/10","id=10&name=精灵妹&description=一个快乐的精灵哈哈&_method=PUT");
}
function delJson(){
jsonAjax("delete","deleteById/10","_method=DELETE");
}
function findByIdJson(){
jsonAjax("findById","findById/10","_method=GET");
}
function findAllJson(){
jsonAjax("findAll","findAll","_method=GET");
}
function jsonAjax(sign,url,data){
var message="";
switch(sign){
case "add":{
message="添加成功";
break;
}
case "edit":{
message="修改成功";
break;
}
case "delete":{
message="删除成功";
break;
}
case "findById":{
message="查询单个成功";
break;
}
case "findAll":{
message="查询全部成功";
break;
}
}

$.ajax({
type:"post",
url:url, //注意请求路径
data:data,
success:function(resultData){
if(resultData.request_status){
//清空
$("#showId").empty();
//追加
$("#showId").append(message+"<br/>");

if(sign=="findById"){
var data=resultData.user;
var str="<table><tr><th>编号</th><th>姓名</th><th>描述</th></tr>";
str+="<tr>";
str+="<td>"+data.id+"</td>";
str+="<td>"+data.name+"</td>";
str+="<td>"+data.description+"</td>";
str+="</tr>";
str+="</table>";
$("#showId").append(str);
}
if(sign=="findAll"){
var data=resultData.userList;
var str="<table><tr><th>编号</th><th>姓名</th><th>描述</th></tr>";
$.each(data,function(idx,item){
str+="<tr>";
str+="<td>"+item.id+"</td>";
str+="<td>"+item.name+"</td>";
str+="<td>"+item.description+"</td>";
str+="</tr>";
})
str+="</table>";
$("#showId").append(str);
}
}
}
})
}
</script>
</body>
</html>

二.十八 重启服务器,进行验证整合是否成功

点击查询全部

SSM框架整合(十五)_java_14

点击添加,再点击查询全部

SSM框架整合(十五)_java_15

SSM框架整合(十五)_java_16

而数据库中显示 :

SSM框架整合(十五)_spring_17

点击修改,再点击查询全部

SSM框架整合(十五)_spring_18

SSM框架整合(十五)_xml_19

数据库展示

SSM框架整合(十五)_SSM框架整合_20


点击查询id,显示:

SSM框架整合(十五)_SSM框架整合_21

说明整合成功。

二.十九 其他的配置

对 Service层的处理, 老蝴蝶是在 UserServiceImpl 实现类中添加了 @Service的注解, 然后只配置了一个 applicationContext-service.xml 的配置文件。 然后在 springmvc.xml 包扫描的时候,扫描了一下 com.yjl.service 包。

有的人, 会创建 applicationContext-service.xml 和applicationContext-tx.xml 配置文件, -service.xml 文件里面 放置各种 bean, 来实例化 UserServiceImpl 的实现类,

<!--写多个bean-->
<bean id="userService" class="com.yjl.service.impl.UserServiceImpl"></bean>

-tx.xml 里面放置事务处理,即老蝴蝶这里的 applicationContext-service.xml 的内容。(这里可扫描包,也可以不扫描包)
太多,就不复制了。 即 二.十三 里面的内容。

这样,就不需要在 UserServiceImpl 上添加@Service注解了, springmvc.xml 扫描的时候,也不需要扫描 com.yjl.service包了。

两者方式都可以。

注意,在写事务的时候,一定不要捕获异常,不然事务是不会回滚的。

可以这样:

@Override
public int insert(User record) {
int result= userMapper.insert(record);
int a=10/0;
return result;
}

但一定不能这样:

@Override
public int insert(User record) {
int result= userMapper.insert(record);
try{
int a=10/0;
}catch(Exception e){
e.printStackTrace();
}
return result;
}

谢谢!!!


标签:www,http,框架,int,springframework,SSM,十五,org,schema
From: https://blog.51cto.com/u_13420484/5841775

相关文章

  • SpringBoot自定义日志Starter(二十五)
    即使有一天,我放弃了自己的身体,也请你,不要放弃我,我亲爱的灵魂.上一章简单介绍了SpringBoot自定义Starter(二十四),如果没有看过,​​请观看上一章​​一.AOP实现日志功能......
  • 多数据源配置JdbcTemplate(十五)
    二八佳人体似酥,腰间仗剑斩愚夫。虽然不见人头落,暗里教君骨髓枯。上一章简单介绍了SpringBoot整合MyBatisPlus(十四),如果没有看过,​​请观看上一章​​工作中,在业务的发展......
  • Python爬虫的scrapy框架的简单应用
    load_mzitu\mzitu\​​item.py​​#-*-coding:utf-8-*-#Defineherethemodelsforyourscrapeditems##Seedocumentationin:#http://doc.scrapy.org/en/latest/......
  • Struts2实现类型转换器(十五)
    勿以恶小而为之,勿以善小而不为--------------------------刘备劝诸君,多行善事积福报,莫作恶上一章简单介绍了Struts2实现JSON和Ajax操作(十四),如果没有看过,​​请观看上一......
  • scrapy框架
    什么是框架?就是一个集成了很多功能并且具有很强通用性的一个项目模板如何学习框架?专门学习框架封装的各种功能的详细用法什么是scrapy?爬虫中封装好的一个明星框......
  • 中文书籍对《人月神话》的引用(20211105更新161-165本):大师品软件、JavaScript开发框架
    ​​中文书籍对《人月神话》的引用(第001到160本)>>​​《人月神话》于1975年出版,1995年出二十周年版。自出版以来,该书被大量的书籍和文章引用,直到现在热潮不退。UMLChina摘录......
  • 太全面了!RF接口自动化框架项目实战
    每天进步一点点,关注我们哦,每天分享测试技术文章本文章出自【码同学软件测试】码同学公众号:自动化软件测试,领取资料可加:magetest码同学抖音号:小码哥聊软件测试以码同学V......
  • 从实现一个React到深度理解React框架核心原理
    前言这篇文章循序渐进地介绍实现以下几个概念,遵循本篇文章基本就能搞懂为啥需要fiber,为啥需要commit和phases、reconciliation阶段等原理。本篇文章又不完全和原文一致,这......
  • 支持JDK19虚拟线程的web框架,之四:看源码,了解quarkus如何支持虚拟线程
    欢迎访问我的GitHub这里分类和汇总了欣宸的全部原创(含配套源码):https://github.com/zq2599/blog_demos《支持JDK19虚拟线程的web框架》系列文章链接支持JDK19虚拟线......
  • 【前端】学习前端vue框架,了解了什么是v-model
    什么是v-model呢?v-model指令可以在表单input、textarea及select元素上创建双向数据绑定。它会根据控件类型自动选取正确的方法来更新元素。尽管有些神奇,但v-model本......