一、Spring
1.简介
Spring框架是一个分层架构,包含一系列的功能要素,并被分为大约20个模块。
这些模块被总结为以下几个部分:
-
Core Container
Core Container(核心容器)包含有Core、Beans、Context和Expression Language模块
Core和Beans模块是框架的基础部分,提供IoC(转控制)和依赖注入特性。这里的基础概念是BeanFactory,它提供对Factory模式的经典实现来消除对程序性单例模式的需要,并真正地允许你从程序逻辑中分离出依赖关系和配置- Core模块主要包含Spring框架基本的核心工具类
- Beans模块是所有应用都要用到的,它包含访问配置文件、创建和管理bean以及进行Inversion of Control/Dependency Injection(Ioc/DI)操作相关的所有类
- Context模块构建于Core和Beans模块基础之上,提供了一种类似于JNDI注册器的框架式的对象访问方法。Context模块继承了Beans的特性,为Spring核心提供了大量扩展,添加了对国际化(如资源绑定)、事件传播、资源加载和对Context的透明创建的支持。ApplicationContext接口是Context模块的关键
- Expression Language模块提供了一个强大的表达式语言用于在运行时查询和操纵对象,该语言支持设置/获取属性的值,属性的分配,方法的调用,访问数组上下文、容器和索引器、逻辑和算术运算符、命名变量以及从Spring的IoC容器中根据名称检索对象
-
Data Access/Integration
- JDBC模块提供了一个JDBC抽象层,它可以消除冗长的JDBC编码和解析数据库厂商特有的错误代码,这个模块包含了Spring对JDBC数据访问进行封装的所有类
- ORM模块为流行的对象-关系映射API,如JPA、JDO、Hibernate、iBatis等,提供了一个交互层,利用ORM封装包,可以混合使用所有Spring提供的特性进行O/R映射,如前边提到的简单声明性事务管理
-
Web
Web上下文模块建立在应用程序上下文模块之上,为基于Web的应用程序提供了上下文,所以Spring框架支持与Jakarta Struts的集成。Web模块还简化了处理多部分请求以及将请求参数绑定到域对象的工作。Web层包含了Web、Web-Servlet、Web-Struts和Web、Porlet模块
- Web模块:提供了基础的面向Web的集成特性,例如,多文件上传、使用Servlet listeners初始化IoC容器以及一个面向Web的应用上下文,它还包含了Spring远程支持中Web的相关部分
- Web-Servlet模块web.servlet.jar:该模块包含Spring的model-view-controller(MVC)实现,Spring的MVC框架使得模型范围内的代码和web forms之间能够清楚地分离开来,并与Spring框架的其他特性基础在一起
- Web-Struts模块:该模块提供了对Struts的支持,使得类在Spring应用中能够与一个典型的Struts Web层集成在一起
- Web-Porlet模块:提供了用于Portlet环境和Web-Servlet模块的MVC的实现
-
AOP
AOP模块提供了一个符合AOP联盟标准的面向切面编程的实现,它让你可以定义例如方法拦截器和切点,从而将逻辑代码分开,降低它们之间的耦合性,利用source-level的元数据功能,还可以将各种行为信息合并到你的代码中
Spring AOP模块为基于Spring的应用程序中的对象提供了事务管理服务,通过使用Spring AOP,不用依赖EJB组件,就可以将声明性事务管理集成到应用程序中
-
Test
Test模块支持使用Junit和TestNG对Spring组件进行测试
二、Spring MVC
1. springMvc:是一个表现层框架,
作用:就是从请求中接收传入的参数,将处理后的结果数据返回给页面展示。
2. 核心配置文件(如springMVC.xml)需要配置的东西:
- 配置@Controller注解扫描
<context:component-scan base-package="com.spring.controller"></context:component-scan>
- 注解驱动
作用:替我们自动配置最新版的注解的处理器映射器和处理器适配器。
如果没有显示的配置处理器映射器和处理器适配那么springMvc会去默认的dispatcherServlet.properties中查找, 对应的处理器映射器和处理器适配器去使用,这样每个请求都要扫描一次他的默认配置文件,效率非常低,会降低访问速度,所以要显示的配置处理器映射器和处理器适配器。
<mvc:annotation-driven></mvc:annotation-driven>
- 配置视图解析器
作用:在controller中指定页面路径的时候就不用写页面的完整路径名称了,可以直接写页面去掉扩展名的名称。
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 真正的页面路径 = 前缀 + 去掉后缀名的页面名称 + 后缀 -->
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
3. web.xml的基础配置
<!-- spirngMvc前端控制器 -->
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 如果没有指定springMvc核心配置文件那么默认会去找/WEB-INF/+<servlet-name>中的内容 + -servlet.xml配置文件 -->
<!-- 指定springMvc核心配置文件位置 -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springMVC.xml</param-value>
</init-param>
<!-- tomcat启动的时候就加载这个servlet -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
4.搭建SSM架构
1)导入包,相关的包可在这下载:ssm(spring+springmvc+mybatis)整合需要的jar包
然后使用逆向工程生成pojo和映射文件以及接口
2)配置 空的mybatis核心配置文件SqlMapConfig.xml(貌似也可以不用,把它删了也没有出现什么问题)
3)配置ApplicationContext-dao.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">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据库连接池 -->
<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="10" />
<property name="maxIdle" value="5" />
</bean>
<!-- mapper配置 -->
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<!-- <property name="configLocation" value="classpath:SqlMapConfig.xml" /> -->
</bean>
<!-- 配置Mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.ssm.dao"/>
</bean>
</beans>
4)配置 @Service注解扫描: 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="com.ssm.service"></context:component-scan>
</beans>
5)配置 事务: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:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.ssm.service.*.*(..))" />
</aop:config>
</beans>
6)配置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:p="http://www.springframework.org/schema/p"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:dubbo="http://code.alibabatech.com/schema/dubbo" 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://code.alibabatech.com/schema/dubbo http://code.alibabatech.com/schema/dubbo/dubbo.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.0.xsd">
<!-- @Controller注解扫描 -->
<context:component-scan base-package="com.ssm.controller"></context:component-scan>
<!-- 注解驱动:
替我们显示的配置了最新版的注解的处理器映射器和处理器适配器 -->
<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
<!-- 配置视图解析器
作用:在controller中指定页面路径的时候就不用写页面的完整路径名称了,可以直接写页面去掉扩展名的名称
-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<!-- 真正的页面路径 = 前缀 + 去掉后缀名的页面名称 + 后缀 -->
<!-- 前缀 -->
<property name="prefix" value="/WEB-INF/jsp/"></property>
<!-- 后缀 -->
<property name="suffix" value=".jsp"></property>
</bean>
<!-- 配置自定义转换器
注意: 一定要将自定义的转换器配置到注解驱动上
-->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<!-- 指定自定义转换器的全路径名称 -->
<bean class="com.ssm.controller.converter.CustomGlobalStrToDateConverter"/>
</set>
</property>
</bean>
</beans>
7)配置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_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MySSM</display-name>
<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>
<!-- 加载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>
<!-- springmvc前端控制器 -->
<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:SpringMvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springMvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<!-- 配置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>
</filter>
<filter-mapping>
<filter-name>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
8)控制层(controller) :
package com.ssm.controller;
import java.util.Date;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.websocket.Session;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpRequest;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import com.ssm.pojo.Items;
import com.ssm.service.ItemsService;
import com.ssm.vo.QueryVo;
@Controller
public class ItemsController {
@Autowired
private ItemsService itemsService;
@RequestMapping("/list")
public ModelAndView ItemsList() throws Exception{
List<Items> list = itemsService.list();
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("itemList", list);
modelAndView.setViewName("itemList");
return modelAndView;
}
/**
* springMvc中默认支持的参数类型:也就是说在controller方法中可以加入这些也可以不加, 加不加看自己需不需要,都行.
*HttpServletRequest
*HttpServletResponse
*HttpSession
*Model
*/
@RequestMapping("/itemEdit")
public String ItemsEdit(HttpServletRequest request, HttpServletResponse response,HttpSession session, Model model) throws Exception{
String idStr = request.getParameter("id");
Items items = itemsService.findItemsById(Integer.parseInt(idStr));
//Model模型:模型中放入了返回给页面的数据
//model底层其实就是用的request域来传递数据,但是对request域进行了扩展.
model.addAttribute("item", items);
//如果springMvc方法返回一个简单的string字符串,那么springMvc就会认为这个字符串就是页面的名称
return "editItem";
}
//springMvc可以直接接收基本数据类型,包括string.spirngMvc可以帮你自动进行类型转换.
//controller方法接收的参数的变量名称必须要等于页面上input框的name属性值
//public String update(Integer id, String name, Float price, String detail) throws Exception{
//spirngMvc可以直接接收pojo类型:要求页面上input框的name属性名称必须等于pojo的属性名称
@RequestMapping("/updateitem")
public String update(Items items) throws Exception{
/*items.setCreatetime(new Date());*/
itemsService.updateItems(items);
return "success";
}
//如果Controller中接收的是Vo,那么页面上input框的name属性值要等于vo的属性.属性.属性.....
@RequestMapping("search")
public String search(QueryVo queryVo) throws Exception{
System.out.println(queryVo);
return "";
}
}
其中:在控制层我定义了一个自定义转换类的包(即converter) ,创建了一个CustomGlobalStrToDateConverter类用于将字符串转换成时间,即:
package com.ssm.controller.converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
/**
* S - source:源
* T - target:目标
*
*/
public class CustomGlobalStrToDateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
try {
Date date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(source);
return date;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
9)业务层(service) ,创建了一个service接口和实现类,即:
package com.ssm.service;
import java.util.List;
import com.ssm.pojo.Items;
public interface ItemsService {
public List<Items> list() throws Exception;
public Items findItemsById(Integer id) throws Exception;
public void updateItems(Items items) throws Exception;
}
package com.ssm.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.ssm.dao.ItemsMapper;
import com.ssm.pojo.Items;
import com.ssm.pojo.ItemsExample;
@Service
public class ItemsServiceImpl implements ItemsService {
@Autowired
private ItemsMapper itemsMapper;
@Override
public List<Items> list() throws Exception {
//如果不需要任何查询条件,直接将example对象new出来即可
ItemsExample example = new ItemsExample();
List<Items> list = itemsMapper.selectByExampleWithBLOBs(example);
return list;
}
@Override
public Items findItemsById(Integer id) throws Exception {
Items items = itemsMapper.selectByPrimaryKey(id);
return items;
}
@Override
public void updateItems(Items items) throws Exception {
itemsMapper.updateByPrimaryKeyWithBLOBs(items);
}
}
5. 总结1:
ssm整合:
1)Dao层
- pojo和映射文件以及接口使用逆向工程生成
- SqlMapConfig.xml mybatis核心配置文件
- ApplicationContext-dao.xml 整合后spring在dao层的配置:(1)数据源(2)会话工厂(3)扫描Mapper
2)service层
- 事务:ApplicationContext-trans.xml
- @Service注解扫描: ApplicationContext-service.xml
3)controller层
配置SpringMvc.xml,包含:
- 注解扫描:扫描@Controller注解
- 注解驱动:替我们显示的配置了最新版的处理器映射器和处理器适配器
- 视图解析器:显示的配置是为了在controller中不用每个方法都写页面的全路径
4)web.xml
- springMvc前端控制器配置
- spring监听
参数绑定(从请求中接收参数)重点
1)默认类型:
在controller方法中可以有也可以没有,看自己需求随意添加。即:httpservletRqeust,httpServletResponse,httpSession,Model(ModelMap其实就是Mode的一个子类,一般用的不多)
2)基本类型:string,double,float,integer,long.boolean
3)pojo类型:页面上input框的name属性值必须要等于pojo的属性名称
4)vo类型:页面上input框的name属性值必须要等于vo中的属性.属性.属性....
5)自定义转换器converter:
作用:由于springMvc无法将string自动转换成date,所以需要自己手动编写类型转换器。包含以下步骤:
- 需要编写一个类实现Converter接口
- 在springMvc.xml中配置自定义转换器
- 在springMvc.xml中将自定义转换器配置到注解驱动上
6. controller重定向和请求转发
1)重定向:浏览器中url发生改变,request域中的数据不可以带到重定向后的方法中
- model.addAttribute("id", items.getId());
- 在springMvc中凡是以redirect:字符串开头的都为重定向。 即 return "redirect:itemEdit/"+items.getId();
2)请求转发:浏览器中url不发生改变,request域中的数据可以带到转发后的方法中
- model.addAttribute("id", items.getId());
- spirngMvc中请求转发:返回的字符串以forward:开头的都是请求转发, 后面forward:itemEdit.action表示相对路径,相对路径就是相对于当前目录,当前为类上面指定的items目录.在当前目录下可以使用相对路径随意跳转到某个方法中
- 后面forward:/itemEdit.action路径中以斜杠开头的为绝对路径,绝对路径从项目名后面开始算return "forward:/items/itemEdit.action";
7. @RequestMapping:通过RequestMapping注解可以定义不同的处理器映射规则。
1)URL路径映射
@RequestMapping(value="/item")或@RequestMapping("/item)
value的值是数组,可以将多个url映射到同一个方法
2)窄化请求映射
- 在class上添加@RequestMapping(url)指定通用请求前缀, 限制此类下的所有方法请求url必须以请求前缀开头,通过此方法对url进行分类管理。如下:
@RequestMapping放在类名上边,设置请求前缀
@Controller
@RequestMapping("/item")
- 方法名上边设置请求映射url:
@RequestMapping放在方法名上边,如下:
@RequestMapping("/queryItem ")
在class和方法名上加入@RequestMapping后,此时,访问地址变为:/item/queryItem
3)请求方法限定
- 限定GET方法
@RequestMapping(method = RequestMethod.GET)
如果通过Post访问则报错:
HTTP Status 405 - Request method 'POST' not supported
例如:
@RequestMapping(value="/editItem",method=RequestMethod.GET)
- 限定POST方法
@RequestMapping(method = RequestMethod.POST)
如果通过Post访问则报错:
HTTP Status 405 - Request method 'GET' not supported
- GET和POST都可以
@RequestMapping(method={RequestMethod.GET,RequestMethod.POST})