SpringMVC进阶(一)

来源:互联网 发布:mac下html5开发工具 编辑:程序博客网 时间:2024/06/03 14:57
Spring MVC回顾:

springmvc入门程序
目的:对前端控制器、处理器映射器、处理器适配器、视图解析器学习
非注解的处理器映射器、处理器适配器
注解的处理器映射器、处理器适配器(掌握)



SpringMVC框架:
第一步:发起请求到前端控制器(DispatcherServlet)
第二步:前端控制器请求HandlerMapping查找 Handler
可以根据xml配置、注解进行查找
第三步:处理器映射器HandlerMapping向前端控制器返回Handler
第四步:前端控制器调用处理器适配器去执行Handler
第五步:处理器适配器去执行Handler
第六步:Handler执行完成给适配器返回ModelAndView
第七步:处理器适配器向前端控制器返回ModelAndView
ModelAndView是springmvc框架的一个底层对象,包括 Model和view
第八步:前端控制器请求视图解析器去进行视图解析
根据逻辑视图名解析成真正的视图(jsp)
第九步:视图解析器向前端控制器返回View
第十步:前端控制器进行视图渲染
视图渲染将模型数据(在ModelAndView对象中)填充到request域
第十一步:前端控制器向用户响应结果 



入门程序
1.需求
以案例作为驱动。
springmvc和mybaits使用一个案例(商品订单管理)。
功能需求:商品列表查询


2.环境准备
数据库环境:mysql5.1
SpringMVC进阶(一)


java环境:
jdk1.7.0_72
eclipse indigo
springmvc版本:spring3.2
需要spring3.2所有jar(一定包括spring-webmvc-3.2.0.RELEASE.jar)

SpringMVC进阶(一)



3.配置前端控制器
在web.xml中配置前端控制器。
SpringMVC进阶(一)



4.配置处理器适配器
在classpath下的springmvc.xml中配置处理器适配器
SpringMVC进阶(一)


通过查看原代码:

SpringMVC进阶(一)



此适配器能执行实现 Controller接口的Handler。


SpringMVC进阶(一)



5.开发Handler
需要实现controller接口,才能由org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter适配器执行。

public class ItemsController1 implements Controller {

@Override
public ModelAndView handleRequest(HttpServletRequestrequest,
HttpServletResponse response) throws Exception {
//调用service查找 数据库,查询商品列表,这里使用静态数据模拟
List《Items》 itemsList = new ArrayList《Items》();
//向list中填充静态数据
Items items_1 = new Items();
items_1.setName("联想笔记本");
items_1.setPrice(6000f);
items_1.setDetail("ThinkPad T430 联想笔记本电脑!");
Items items_2 = new Items();
items_2.setName("苹果手机");
items_2.setPrice(5000f);
items_2.setDetail("iphone6苹果手机!");
itemsList.add(items_1);
itemsList.add(items_2);

//返回ModelAndView
ModelAndView modelAndView =  newModelAndView();
//相当 于request的setAttribut,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList);
//指定视图
modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");

return modelAndView;
}

}


6.web-inf/jsp/items/itemsList.jsp




7.配置Handler
将编写Handler在spring容器加载。


SpringMVC进阶(一)




8.配置处理器映射器
在classpath下的springmvc.xml中配置处理器映射器
SpringMVC进阶(一)



9.配置视图解析器

需要配置解析jsp的视图解析器。


SpringMVC进阶(一)



10.部署调试

访问地址:http://localhost:8080/springmvcfirst1208/queryItems.action

处理器映射器根据url找不到Handler,报下边的错误。说明url错误。
处理器映射器根据url找到了Handler,转发的jsp页面找到,报下边的错误,说明jsp页面地址错误了。




非注解的处理器映射器和适配器
1.非注解的处理器映射器

处理器映射器:
org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping


另一个映射器:
org.springframework.web.servlet.handler.SimpleUrlHandlerMapping

《!--简单url映射  --》
《beanclass="org.springframework.web.servlet.handler.SimpleUrlHandlerMapping"》
《property name="mappings"》
《props》
《!-- 对itemsController1进行url映射,url是/queryItems1.action--》
《prop key="/queryItems1.action"》itemsController1《/prop》
《prop key="/queryItems2.action"》itemsController1《/prop》
《prop key="/queryItems3.action"》itemsController2《/prop》
《/props》
《/property》
《/bean》

多个映射器可以并存,前端控制器判断url能让哪些映射器映射,就让正确的映射器处理。




2.非注解的处理器适配器

org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter
要求编写的Handler实现 Controller接口。

org.springframework.web.servlet.mvc.HttpRequestHandlerAdapter
要求编写的Handler实现 HttpRequestHandler接口。

SpringMVC进阶(一)

@Override
public void handleRequest(HttpServletRequest request,
HttpServletResponse response) throws ServletException,IOException {
//调用service查找 数据库,查询商品列表,这里使用静态数据模拟
List《Items》 itemsList = new ArrayList《Items》();
//向list中填充静态数据
Items items_1 = new Items();
items_1.setName("联想笔记本");
items_1.setPrice(6000f);
items_1.setDetail("ThinkPad T430 联想笔记本电脑!");
Items items_2 = new Items();
items_2.setName("苹果手机");
items_2.setPrice(5000f);
items_2.setDetail("iphone6苹果手机!");
itemsList.add(items_1);
itemsList.add(items_2);
//设置模型数据
request.setAttribute("itemsList", itemsList);
//设置转发的视图
request.getRequestDispatcher("/WEB-INF/jsp/items/itemsList.jsp").forward(request,response);

//使用此方法可以通过修改response,设置响应的数据格式,比如响应json数据

}





5.注解的处理器映射器和适配器

在spring3.1之前使用org.springframework.web.servlet.mvc.annotation.DefaultAnnotationHandlerMapping注解映射器。

在spring3.1之后使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping注解映射器。

在spring3.1之前使用org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter注解适配器。

在spring3.1之后使用org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter注解适配器。



1.配置注解映射器和适配器。
《!--注解映射器 --》
《beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/》
《!--注解适配器 --》
《beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/》
《!-- 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置
mvc:annotation-driven默认加载很多的参数绑定方法,
比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
实际开发时使用mvc:annotation-driven
--》
《!-- 《mvc:annotation-driven》《/mvc:annotation-driven》 --》



2.开发注解Handler

使用注解的映射器和注解的适配器。(注解的映射器和注解的适配器必须配对使用)

//使用Controller标识 它是一个控制器
@Controller
public class ItemsController3 {
//商品查询列表
//@RequestMapping实现 对queryItems方法和url进行映射,一个方法对应一个url
//一般建议将url和方法写成一样
@RequestMapping("/queryItems")
public ModelAndView queryItems()throws Exception{
//调用service查找 数据库,查询商品列表,这里使用静态数据模拟
List《Items》 itemsList = new ArrayList《Items》();
//向list中填充静态数据
Items items_1 = new Items();
items_1.setName("联想笔记本");
items_1.setPrice(6000f);
items_1.setDetail("ThinkPad T430 联想笔记本电脑!");
Items items_2 = new Items();
items_2.setName("苹果手机");
items_2.setPrice(5000f);
items_2.setDetail("iphone6苹果手机!");
itemsList.add(items_1);
itemsList.add(items_2);
//返回ModelAndView
ModelAndView modelAndView =  newModelAndView();
//相当 于request的setAttribut,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList);
//指定视图
//下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为
//modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
//上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
modelAndView.setViewName("items/itemsList");
return modelAndView;
}



3.在spring容器中加载Handler

《!-- 对于注解的Handler可以单个配置
实际开发中建议使用组件扫描
--》
《!-- 《bean class="cn.itcast.ssm.controller.ItemsController3"/》 --》
《!-- 可以扫描controller、service、...
这里让扫描controller,指定controller的包
--》
《context:component-scanbase-package="cn.itcast.ssm.controller"》《/context:component-scan》




小结:

通过入门程序理解springmvc前端控制器、处理器映射器、处理器适配器、视图解析器用法。

前端控制器配置:
第一种:*.action,访问以.action结尾 由DispatcherServlet进行解析

第二种:/,所以访问的地址都由DispatcherServlet进行解析,对于静态文件的解析需要配置不让DispatcherServlet进行解析
  使用此种方式可以实现 RESTful风格的url

处理器映射器:
非注解处理器映射器(了解)
注解的处理器映射器(掌握)
对标记@Controller类中标识有@RequestMapping的方法进行映射。在@RequestMapping里边定义映射的url。使用注解的映射器不用在xml中配置url和Handler的映射关系。

处理器适配器:
非注解处理器适配器(了解)
注解的处理器适配器(掌握)
注解处理器适配器和注解的处理器映射器是配对使用。理解为不能使用非注解映射器进行映射。

《mvc:annotation-driven》《/mvc:annotation-driven》可以代替下边的配置:

《!--注解映射器 --》
《beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/》
《!--注解适配器 --》
《beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/》

实际开发使用:mvc:annotation-driven


视图解析器配置前缀和后缀:

SpringMVC进阶(一)


程序中不用指定前缀和后缀:
SpringMVC进阶(一)







springmvc+mybaits的系统架构:
 
表现层springmvc-》业务层service接口 -》持久层mybaits-》mysql
spring将各层进行整合
通过spring管理持久层的mapper(相当于dao接口)
通过spring管理业务层service,service中可以调用mapper接口。
spring进行事务控制。

通过spring管理表现层Handler,Handler中可以调用service接口。

mapper、service、Handler都是javabean。



第一步:整合dao层
mybatis和spring整合,通过spring管理mapper接口。
使用mapper的扫描器自动扫描mapper接口在spring中进行注册。

第二步:整合service层
通过spring管理 service接口。
使用配置方式将service接口配置在spring配置文件中。
实现事务控制。

第三步:整合springmvc
由于springmvc是spring的模块,不需要整合。




jar包:springmvc和mybatis整合




1.sqlMapConfig.xml

mybatis自己的配置文件。
《?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》
《!-- 全局setting配置,根据需要添加 --》
《!-- 配置别名 --》
《typeAliases》
《!-- 批量扫描别名 --》
《package name="cn.itcast.ssm.po"/》
《/typeAliases》

《!-- 配置mapper
由于使用spring和mybatis的整合包进行mapper扫描,这里不需要配置了。
必须遵循:mapper.xml和mapper.java文件同名且在一个目录 
--》

《!-- 《mappers》
《/mappers》 --》
《/configuration》




2.applicationContext-dao.xml
配置:
数据源
SqlSessionFactory
mapper扫描器


《!-- 加载db.properties文件中的内容,db.properties文件中key命名要有一定的特殊规则--》
《context:property-placeholderlocation="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="30" /》
《property name="maxIdle" value="5" /》
《/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扫描器 --》
《beanclass="org.mybatis.spring.mapper.MapperScannerConfigurer"》
《!-- 扫描包路径,如果需要扫描多个包,中间使用半角逗号隔开 --》
《property name="basePackage"value="cn.itcast.ssm.mapper"》《/property》
《property name="sqlSessionFactoryBeanName"value="sqlSessionFactory" /》
《/bean》




3.手动定义商品查询mapper

针对综合查询mapper,一般情况会有关联查询,建议自定义mapper


3.1 ItemsMapperCustom.xml

sql语句:
SELECT * FROM items  WHERE items.name LIKE'%笔记本%'

public class Items {
    private Integerid;

    private Stringname;

    private Floatprice;

    private Stringpic;

    private Datecreatetime;

    private Stringdetail;
}
public class ItemsCustom extends Items {
//添加商品信息的扩展属性
}



items的扩展对象:
public class ItemsQueryVo {
//商品信息
private Items items;
//为了系统 可扩展性,对原始生成的po进行扩展
private ItemsCustom itemsCustom;
}

《?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.itcast.ssm.mapper.ItemsMapperCustom"》

   《!--定义商品查询的sql片段,就是商品查询条件 --》
   《sqlid="query_items_where"》
   
    《!--商品查询条件通过ItemsQueryVo包装对象 中itemsCustom属性传递 --》
   
   
    items.name LIKE'%${itemsCustom.name}%'
   
   
   《/sql》
 
  《!-- 商品列表查询 --》
  《!-- parameterType传入包装对象(包装了查询条件)
  resultType建议使用扩展对象
  --》
  《select id="findItemsList"parameterType="cn.itcast.ssm.po.ItemsQueryVo"
 resultType="cn.itcast.ssm.po.ItemsCustom"》
  SELECT items.* FROM items 
  《where》
  《includerefid="query_items_where"》《/include》
  《/where》
  《/select》
 
《/mapper》



3.2 ItemsMapperCustom.java
public interface ItemsMapperCustom {
//商品查询列表
public List《ItemsCustom》 findItemsList(ItemsQueryVoitemsQueryVo)throws Exception;
}




4.整合service

让spring管理service接口。
public interface ItemsService {
//商品查询列表
public List《ItemsCustom》 findItemsList(ItemsQueryVoitemsQueryVo) throws Exception;
}






public class ItemsServiceImpl implements ItemsService{

@Autowired
private ItemsMapperCustom itemsMapperCustom;
@Override
public List《ItemsCustom》 findItemsList(ItemsQueryVoitemsQueryVo)
throws Exception {
//通过ItemsMapperCustom查询数据库
return itemsMapperCustom.findItemsList(itemsQueryVo);
}
}




4.1 在spring容器配置service(applicationContext-service.xml)

创建applicationContext-service.xml,文件中配置service。
《!-- 商品管理的service --》
《bean id="itemsService"class="cn.itcast.ssm.service.impl.ItemsServiceImpl"/》




4.2 事务控制(applicationContext-transaction.xml)
在applicationContext-transaction.xml中使用spring声明式事务控制方法。


《!-- 事务管理器 
对mybatis操作数据库事务控制,spring使用jdbc的事务控制类
--》
《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="save*" propagation="REQUIRED"/》
《tx:method name="delete*" propagation="REQUIRED"/》
《tx:method name="insert*" 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="select*" propagation="SUPPORTS"read-only="true"/》
《/tx:attributes》
《/tx:advice》
《!-- aop --》
《aop:config》
《aop:advisor advice-ref="txAdvice" pointcut="execution(*cn.itcast.ssm.service.impl.*.*(..))"/》
《/aop:config》









整合springmvc
1.创建springmvc.xml文件,配置处理器映射器、适配器、视图解析器。



《!-- 可以扫描controller、service、...
这里让扫描controller,指定controller的包
--》
《context:component-scanbase-package="cn.itcast.ssm.controller"》《/context:component-scan》
《!--注解映射器 --》
《!-- 《beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/》--》
《!--注解适配器 --》
《!-- 《beanclass="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter"/》--》
《!-- 使用 mvc:annotation-driven代替上边注解映射器和注解适配器配置
mvc:annotation-driven默认加载很多的参数绑定方法,
比如json转换解析器就默认加载了,如果使用mvc:annotation-driven不用配置上边的RequestMappingHandlerMapping和RequestMappingHandlerAdapter
实际开发时使用mvc:annotation-driven
--》
《mvc:annotation-drivenconversion-service="conversionService"》《/mvc:annotation-driven》

《!-- 视图解析器
解析jsp解析,默认使用jstl标签,classpath下的得有jstl的包
--》
《bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver"》
《!-- 配置jsp路径的前缀 --》
《property name="prefix" value="/WEB-INF/jsp/"/》
《!-- 配置jsp路径的后缀 --》
《property name="suffix" value=".jsp"/》
《/bean》
《!-- 自定义参数绑定 --》
《!-- 转换器 --》
《property name="converters"》
《list》
《!-- 日期类型转换 --》
《beanclass="cn.itcast.ssm.controller.converter.CustomDateConverter"/》
《/list》
《/property》
《/bean》


2.配置前端控制器

参考入门程序。
web.xml




3.编写Controller(就是Handler)

@Controller
//为了对url进行分类管理 ,可以在这里定义根路径,最终访问url是根路径+子路径
//比如:商品列表:/items/queryItems.action
@RequestMapping("/items")
public class ItemsController {

@Autowired
private ItemsService itemsService;

// 商品查询
@RequestMapping("/queryItems")
public ModelAndView queryItems(HttpServletRequest request)throws Exception {
//测试forward后request是否可以共享
System.out.println(request.getParameter("id"));

// 调用service查找 数据库,查询商品列表
List《ItemsCustom》 itemsList =itemsService.findItemsList(null);
// 返回ModelAndView
ModelAndView modelAndView = new ModelAndView();
// 相当 于request的setAttribut,在jsp页面中通过itemsList取数据
modelAndView.addObject("itemsList", itemsList);

// 指定视图
// 下边的路径,如果在视图解析器中配置jsp路径的前缀和jsp路径的后缀,修改为
//modelAndView.setViewName("/WEB-INF/jsp/items/itemsList.jsp");
// 上边的路径配置可以不在程序中指定jsp路径的前缀和jsp路径的后缀
modelAndView.setViewName("items/itemsList");

return modelAndView;

}
}



加载spring容器

将mapper、service、controller加载到spring容器中
 

建议使用通配符加载上边的配置文件。

在web.xml中,添加spring容器监听器,加载spring容器。


《!-- 加载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》
0 0
原创粉丝点击