SpringMvc配置和原理


运行原理

DispatcherServlet通过HandlerMapping在MVC的容器中找到处理请求的Controller,将请求提交给Controller,Controller对象调用业务层接口实现对应业务,并得到处理结果,返回ModelAndView,DispatcherServlet通过查找最适合的ViewResolver完成视图解析,完成HTTP响应

启动流程

ContextLoaderListener初始化,实例化IoC容器,并将此容器实例注册到ServletContext中,DispatcherServlet初始化。

DispatcherServlet配置

1.由Servlet拦截所有请求并发给Spring MVC控制器

在\webapp\WEB-INF\web.xml:



    Archetype Created Web Application

    
        dispatcherServlet
        org.springframework.web.servlet.DispatcherServlet
        
            contextConfigLocation
                        
            classpath:springmvc.xml
        
        1
    

    
        dispatcherServlet
            
        /
    
    
    
    
        characterEncodingFilter
        org.springframework.web.filter.CharacterEncodingFilter
        
            encoding
                        
            UTF-8
        
    
    
        characterEncodingFilter
        /*
    


备注:web.xml文件并不是web工程必须的,web.xml文件是用来初始化配置信息:比如Welcome页面、servlet、servlet-mapping、filter、listener、启动加载级别等

classpath:springmvc.xml


    
    



    

    

	 
	 
	 	
	 	
	 	
	 

ModelAndView对象

流程图

image-20200822223201901

注解扫描:

//在springBoot中,Controller的扫描范围默认同一个包内,包内的返回值将通过视图解析器解析
@Controller

//直接返回结果
@ResponceBody

@RestController=@ResponceBody+@Controller

webapp/web.xml


	
	
	
		mvc-dispatcher
		org.springframework.web.servlet.DispatcherServlet
		
		
			contextConfigLocation
			classpath:spring/spring-*.xml
		
	
	
		mvc-dispatcher
		
		/
	

@RequestParam与@PathVariable的区别

使用@RequestParam时,通过get方法提交时,URL是这样的host/path?id=1,通过表单提交时name属性需要和控制器中@RequestParam中的value属性值相同

使用@PathVariable时,URL是host/path/1

@RequestMapping(value="/user",method = RequestMethod.GET)  
   public @ResponseBody  
   User printUser(@RequestParam(value = "id", required = false, defaultValue = "0")  
   int id) {  
    User user = new User();  
       user = userService.getUserById(id);  
       return user;  
   }  
     
   @RequestMapping(value="/user/{id:\\d+}",method = RequestMethod.GET)  
   public @ResponseBody  
   User printUser2(@PathVariable int id) {  
       User user = new User();  
       user = userService.getUserById(id);  
       return user;  
   }  

将Controller的数据提交到页面

使用HttpServletRequest对象里的setAttribute方法将值回传html或者JSP页面中

@GetMapping("/")
public String test(HttpServletRequest request){
    request.setAttribute();
    return "";
}

使用Model或者Map的方式保存参数

@GetMapping("/")
public String test(Model model){
    model.addAttribute();
    return "";
}

或者使用ModelAndView的方式

@GetMapping("/")
public ModelAndView test(){
    ModelAndView mav = new ModelAndView();
    mav.addObject();
    return mav;
}