栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

【SpringMVC框架入门】-01-整体结构,前端控制器 三大组件(处理器映射器,处理器适配器,视图解析器) spring mybatis ssm整合 参数绑定 struts2区别

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

【SpringMVC框架入门】-01-整体结构,前端控制器 三大组件(处理器映射器,处理器适配器,视图解析器) spring mybatis ssm整合 参数绑定 struts2区别

1. springMvc:是一个表现层框架,
作用:就是从请求中接收传入的参数,
     将处理后的结果数据返回给页面展示

Spring web mvc和Struts2都属于表现层的框架,它是Spring框架的一部分,我们可以从Spring的整体结构中看得出来:

Spring的整体结构

SpringMVC处理流程


架构流程

1、用户发送请求至前端控制器DispatcherServlet
2、DispatcherServlet收到请求调用HandlerMapping处理器映射器。
3、处理器映射器根据请求url找到具体的处理器,生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。
4、DispatcherServlet通过HandlerAdapter处理器适配器调用处理器
5、执行处理器(Controller,也叫后端控制器)。
6、Controller执行完成返回ModelAndView
7、HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet
8、DispatcherServlet将ModelAndView传给ViewReslover视图解析器
9、ViewReslover解析后返回具体View
10、DispatcherServlet对View进行渲染视图(即将模型数据填充至视图中)。
11、DispatcherServlet响应用户

组件说明

以下组件通常使用框架提供实现:

DispatcherServlet:前端控制器

用户请求到达前端控制器,它就相当于mvc模式中的c,dispatcherServlet是整个流程控制的中心,由它调用其它组件处理用户的请求,dispatcherServlet的存在降低了组件之间的耦合性。

HandlerMapping:处理器映射器

HandlerMapping负责根据用户请求找到Handler即处理器,springmvc提供了不同的映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。

Handler:处理器

Handler 是继DispatcherServlet前端控制器的后端控制器,在DispatcherServlet的控制下Handler对具体的用户请求进行处理。
由于Handler涉及到具体的用户业务请求,所以一般情况需要程序员根据业务需求开发Handler。

HandlAdapter:处理器适配器

通过HandlerAdapter对处理器进行执行,这是适配器模式的应用,通过扩展适配器可以对更多类型的处理器进行执行。

View Resolver:视图解析器

View Resolver负责将处理结果生成View视图,View Resolver首先根据逻辑视图名解析成物理视图名即具体的页面地址,再生成View视图对象,最后对View进行渲染将处理结果通过页面展示给用户。

View:视图

springmvc框架提供了很多的View视图类型的支持,包括:jstlView、freemarkerView、pdfView等。我们最常用的视图就是jsp。
一般情况下需要通过页面标签或页面模版技术将模型数据通过页面展示给用户,需要由程序员根据业务需求开发具体的页面。

springmvc的三大组件

说明:在springmvc的各个组件中,处理器映射器、处理器适配器、视图解析器称为springmvc的三大组件。
需要用户开放的组件有handler、view

4.4框架默认加载组件

SpringMVC DEMO web.xml

  
  	spirngMvc0523
  	org.springframework.web.servlet.DispatcherServlet
  	
  	
  	
  	
  		contextConfigLocation
  		classpath:SpringMvc.xml
  	
  	
  	
  	1
  
  
  	spirngMvc0523
  	*.action
  
SpringMvc.xml


        
        
        
        
        
        
        

        

        
        

        


	
	
	
	
	
		
		
		
		
		
	
	
	

Items.java
public class Items {
	
    private Integer id;
    private String name;
    private Float price;
    private String pic;
    private Date createtime;
    private String detail;
itemList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>




查询商品列表

 
查询条件:
商品列表:
商品名称 商品价格 生产日期 商品描述 操作
${item.name } ${item.price } ${item.detail } 修改
ItemsController.java 注解形式
@Controller
public class ItemsController {

	//指定url到请求方法的映射
	//url中输入一个地址,找到这个方法.例如:localhost:8081/springmvc0523/list.action
	@RequestMapping("/list")
	public ModelAndView  itemsList() throws Exception{
		List itemList = new ArrayList<>();
		
		//商品列表
		Items items_1 = new Items();
		items_1.setName("联想笔记本_3");
		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苹果手机!");
		
		itemList.add(items_1);
		itemList.add(items_2);
		
		//模型和视图
		//model模型: 模型对象中存放了返回给页面的数据
		//view视图: 视图对象中指定了返回的页面的位置
		ModelAndView modelAndView = new ModelAndView();
		
		//将返回给页面的数据放入模型和视图对象中
		modelAndView.addObject("itemList", itemList);
		
		//指定返回的页面位置
		modelAndView.setViewName("itemList");
		//modelAndView.setViewName("/WEB-INF/jsp/itemList.jsp");
		
		
		return modelAndView;

	}
}

springmvc与struts2不同

1、springmvc的入口是一个servlet即前端控制器,而struts2入口是一个filter过虑器。
2、springmvc是基于方法开发(一个url对应一个方法),请求参数传递到方法的形参,可以设计为单例或多例(建议单例),struts2是基于类开发,传递参数是通过类的属性,只能设计为多例。
3、Struts采用值栈存储请求和响应的数据,通过OGNL存取数据, springmvc通过参数解析器是将request请求内容解析,并给方法形参赋值,将数据和视图封装成ModelAndView对象,最后又将ModelAndView中的模型数据通过reques域传输到页面。Jsp视图解析器默认使用jstl。

2. ssm整合: 1)Dao层
	pojo和映射文件以及接口使用逆向工程生成
	SqlMapConfig.xml   mybatis核心配置文件
	ApplicationContext-dao.xml 整合后spring在dao层的配置
		数据源
		会话工厂
		扫描Mapper
SqlMapConfig.xml



	


ApplicationContext-dao.xml



	
	
	
	
		
		
		
		
		
		
	
	
	
	
	
		
		
		
		
	
	
	
	
		
	



db.properties
jdbc.driver=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/springssh?characterEncoding=utf-8
jdbc.username=root
jdbc.password=123456
Items.java
public class Items {
    private Integer id;

    private String name;

    private Float price;

    private String pic;

    private Date createtime;

    private String detail;

ItemsExample.java
public class ItemsExample {
    protected String orderByClause;

    protected boolean distinct;

    protected List oredCriteria;

    public ItemsExample() {
        oredCriteria = new ArrayList();
    }
2)service层
	事务			ApplicationContext-trans.xml
	@Service注解扫描	ApplicationContext-service.xml
ApplicationContext-service.xml



	
	

ApplicationContext-trans.xml



	
	
		
		
	
	
	
	
		
			
			
			
			
			
			
			
		
	
	
	
	
		
	
	

3)controller层
	SpringMvc.xml 
		注解扫描:扫描@Controller注解
		注解驱动:替我们显示的配置了最新版的处理器映射器和处理器适配器
		视图解析器:显示的配置是为了在controller中不用每个方法都写页面的全路径
SpringMvc.xml


    
    
    
    
    
    
    
    
	
		
		
		
		
		
	
	
	
	
		
			
				
				
			
		
	
	


4)web.xml
	springMvc前端控制器配置
	spring监听
web.xml


  ssm0523
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
  
  
	
		contextConfigLocation
		classpath:ApplicationContext-*.xml
	
	
		org.springframework.web.context.ContextLoaderListener
	
  
  
  
  
  	springMvc
  	org.springframework.web.servlet.DispatcherServlet
  	
  		contextConfigLocation
  		classpath:SpringMvc.xml
  	
  	
  	1
  
  
  	springMvc
  	*.action
  
  
  
  
		CharacterEncodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			utf-8
		
	
	
		CharacterEncodingFilter
		
	@RequestMapping("/itemEdit")
	public String itemEdit(HttpServletRequest reuqest, 
			 Model model) throws Exception{
		
		String idStr = reuqest.getParameter("id");
		Items items = itmesService.findItemsById(Integer.parseInt(idStr));
		
		//Model模型:模型中放入了返回给页面的数据
		//model底层其实就是用的request域来传递数据,但是对request域进行了扩展.
		model.addAttribute("item", items);
		
		//如果springMvc方法返回一个简单的string字符串,那么springMvc就会认为这个字符串就是页面的名称
		return "editItem";
	}
2)基本类型:string,double,float,integer,long.boolean
//springMvc可以直接接收基本数据类型,包括string.spirngMvc可以帮你自动进行类型转换.
	//controller方法接收的参数的变量名称必须要等于页面上input框的name属性值
	@RequestMapping("/updateitem")
	public String update(Integer id, String name, Float price, String detail) throws Exception{
	
	//spirngMvc可以直接接收pojo类型:要求页面上input框的name属性名称必须等于pojo的属性名称
	public String update(Items items) throws Exception{
		itmesService.updateItems(items);
		
		return "success";
	}
@RequestParam
public String update(@RequestParam(value="item_id",required=true,defaultvalue=1) Integer id, String name, Float price, String detail) throws Exception{
)pojo类型:页面上input框的name属性值必须要等于pojo的属性名称
	//spirngMvc可以直接接收pojo类型:要求页面上input框的name属性名称必须等于pojo的属性名称
	@RequestMapping("/updateitem")
	public String update(Items items) throws Exception{
		itmesService.updateItems(items);
		
		return "success";
	}

4)vo类型:页面上input框的name属性值必须要等于vo中的属性.属性.属性…
//如果Controller中接收的是Vo,那么页面上input框的name属性值要等于vo的属性.属性.属性.....
	@RequestMapping("/search")
	public ModelAndView search(QueryVo vo) throws Exception{
		System.out.println(vo);
		
		List list = itmesService.query(vo);
		
		ModelAndView modelAndView = new ModelAndView();
		
		modelAndView.addObject("itemList", list);
		modelAndView.setViewName("itemList");
		
		return modelAndView;
	}

商品名称:
商品价格:

Controller方法定义如下:

//如果Controller中接收的是Vo,那么页面上input框的name属性值要等于vo的属性.属性.属性.....
	@RequestMapping("/search")
	public ModelAndView search(QueryVo vo) throws Exception{
5)自定义转换器converter:
	作用:由于springMvc无法将string自动转换成date所以需要自己手动编写类型转换器
	需要编写一个类实现Converter接口
	在springMvc.xml中配置自定义转换器
	在springMvc.xml中将自定义转换器配置到注解驱动上
CustomGlobalStrToDateConverter.java
public class CustomGlobalStrToDateConverter implements Converter {

	@Override
	public Date convert(String source) {
		try {
			Date date = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss").parse(source);
			return date;
		} catch (ParseException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}

}

6)POST GET请求乱码

		CharacterEncodingFilter
		org.springframework.web.filter.CharacterEncodingFilter
		
			encoding
			utf-8
		
	
	
		CharacterEncodingFilter
		/*
	

对于get请求中文参数出现乱码解决方法有两个:

修改tomcat配置文件添加编码与工程编码一致,如下:


另外一种方法对参数进行重新编码:
ISO8859-1是tomcat默认编码,需要将tomcat编码后的内容按utf-8编码

String userName new 
String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
ItemsController.java
@Controller
public class ItemsController {

	@Autowired
	private ItemsService itmesService;
	
	@RequestMapping("/list")
	public ModelAndView itemsList() throws Exception{
		List list = itmesService.list();
		
		ModelAndView modelAndView = new ModelAndView();
		
		modelAndView.addObject("itemList", list);
		modelAndView.setViewName("itemList");
		
		return modelAndView;
	}
ItemsService.java
public interface ItemsService {

	
	public List list() throws Exception;
	
	public Items findItemsById(Integer id) throws Exception;
	
	public void updateItems(Items items) throws Exception;

	public List query(QueryVo vo);
	
}

ItemsServiceImpl.java
@Service
public class ItemsServiceImpl implements ItemsService {

	@Autowired
	private ItemsMapper itemsMapper;

	@Override
	public List list() throws Exception {
		//如果不需要任何查询条件,直接将example对象new出来即可
		ItemsExample example = new ItemsExample();
		List 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);
	}

	@Override
	public List query(QueryVo vo) {
		// TODO Auto-generated method stub
		//QueryVo [items=Items [id=null, name=111, price=222.0, pic=null, createtime=null, detail=null]]
		
		ItemsExample example = new ItemsExample();
		Criteria criteria = example.createCriteria();
		
		String name =vo.getItems().getName();
		
		Float price =vo.getItems().getPrice();
		
		if(name != null && "" != name ) {
			criteria.andNameLike("%"+name+"%");
		}
		
		if(price != null  ) {
			criteria.andPriceGreaterThanOrEqualTo(price);
		}
		
		List list = itemsMapper.selectByExampleWithBLOBs(example);
		
		return list;
		
	}
	
	
}
ItemsMapper.java
public interface ItemsMapper {
    int countByExample(ItemsExample example);

    int deleteByExample(ItemsExample example);

    int deleteByPrimaryKey(Integer id);

    int insert(Items record);

    int insertSelective(Items record);

    List selectByExampleWithBLOBs(ItemsExample example);

    List selectByExample(ItemsExample example);

    Items selectByPrimaryKey(Integer id);

    int updateByExampleSelective(@Param("record") Items record, @Param("example") ItemsExample example);

    int updateByExampleWithBLOBs(@Param("record") Items record, @Param("example") ItemsExample example);

    int updateByExample(@Param("record") Items record, @Param("example") ItemsExample example);

    int updateByPrimaryKeySelective(Items record);

    int updateByPrimaryKeyWithBLOBs(Items record);

    int updateByPrimaryKey(Items record);
}
ItemsMapper.xml selectByExampleWithBLOBs
 
    id, name, price, pic, createtime
  
  
    detail
  
  
    select count(*) from user
    
      
    
  

itemList.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>




查询商品列表

 
查询条件:
商品名称: 商品价格:
商品列表:
商品名称 商品价格 生产日期 商品描述 操作
${item.name } ${item.price } ${item.detail } 修改
editItem.jsp.java
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/fmt"  prefix="fmt"%>




查询商品列表

 
查询条件:
商品名称: 商品价格:
商品列表:
商品名称 商品价格 生产日期 商品描述 操作
${item.name } ${item.price } ${item.detail } 修改
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/644421.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号