Spring MVC文件配置以及参数传递示例详解

web.xml文件配置

创建好一个SpringMVC项目后,需要在需要在WB-INF文件夹下配置web.xml文件




  SpringMVCdemo
  
    index.jsp
  

  
  
    contextConfigLocation
    classpath*:springMVC.xml
  

  
    org.springframework.web.context.ContextLoaderListener
  

  
    dispatcher
    
    org.springframework.web.servlet.DispatcherServlet
    1
  
  
    dispatcher
    
    *.do
  

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

springMVC.xml文件配置

在src文件夹下创建springMVC.xml文件




  
  

  
  
  
  

  
  
    
    
    
  

第一个SpringMVC实例

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>

 
  $Title$
 
 
 哈哈哈哈哈
 

测试类:

package cn.zhc.test;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

@Controller
public class Test {
  @RequestMapping("/hello.do")
  public String hello(){
    System.out.println("hhhhhhhhhhhh");
    return "index";
  }
}

在项目运行后,在前端页面路径后输入/hello.do,控制台会输出hhhhhhhhhhhh

Spring MVC文件配置以及参数传递示例详解_第1张图片 

参数传递

view到controller 四种方式

	@RequestMapping("/hello.do")
  public String hello(String name){
    //路径后加?name=  不加会传null
    System.out.println(name);
    return "index";
  }

  //Controller方法方法中参数前加@RequestParam进行直接入参

  @RequestMapping("/hello.do")
  public String hello(@RequestParam String name){
    //不传参会请求错误400
    System.out.println(name);
    return "index";
  }

  @RequestMapping("/hello.do")
  public String hello(@RequestParam(value = "name" ,required = false) String name){
    //required是否需要传参
    System.out.println(name);
    return "index";
  }

  @RequestMapping(value = "/hello.do",method = RequestMethod.GET,params = "name")
  public String hello(String name){
    //不传参会请求错误400
    System.out.println(name);
    return "index";
  }

controller到view 三种方式

	@RequestMapping("/hello.do")
  public ModelAndView hello(){
    ModelAndView mv = new ModelAndView();
    mv.addObject("name","zhu");//添加模型数据
    mv.setViewName("index");//设置视图名称
    return mv;
  }

  @RequestMapping("/hello.do")
  public String hello(Model model){
    model.addAttribute("name","huai");
    model.addAttribute("chang");
    //在model中若不指定key,则使用默认对象的类型作为key
    return "index";
  }

  @RequestMapping("/hello.do")
  public String hello(Map map){
    map.put("name","lisa");
    return "index";
  }

总结

到此这篇关于Spring MVC文件配置以及参数传递的文章就介绍到这了,更多相关SpringMVC文件配置参数传递内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

你可能感兴趣的:(Spring MVC文件配置以及参数传递示例详解)