Spring学习--1. @RequestMapping的路径参数

一、@RequestMapping的路径参数

package cays.mymvc;

import cays.domain.DemoObj;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;

/**
 * @ClassName DemoAnnoController
 * @Description TODO
 * @Author Cays
 * @Date 2019/5/30 9:02
 * @Version 1.0
 **/
@Controller    // 1. 声明控制器
@RequestMapping("/anno")   // 2. 声明访问路径
public class DemoAnnoController {
    // 3. 未注明路径即/anno
    @RequestMapping(produces = "text/plain;charset=UTF-8") //produces指定response的媒体类型,字符集
    public @ResponseBody String index(HttpServletRequest request){
        return "url:"+request.getRequestURI()+" can access.";
    }

    @RequestMapping(value = "/pathvar/{str}", produces = "text/plain;charset=UTF-8") // 3. 演示接收路径参数/pathvar/1
    public @ResponseBody String demoPathVar(@PathVariable String str,HttpServletRequest request){
        return "url:"+request.getRequestURI()+" can access, str " + str;
    }
    @RequestMapping(value = "/requestParam",produces = "text/plain;charset=UTF-8")// 4. 常规参数获取 /requestParam?id=1
    public @ResponseBody String passRequestParam(Long id,HttpServletRequest request){
        return "url:"+request.getRequestURI()+" can access,id:"+id;
    }

    @RequestMapping(value = "/obj", produces = "application/json;charset=UTF-8")// 5. 解释参数到对象 /obj?id=1&name=cays
    @ResponseBody
    public String passObj(DemoObj obj,HttpServletRequest request){
        return "url:"+request.getRequestURI()+" can access,obj id:"+obj.getId()
                +" obj name:"+obj.getName();
    }
    @RequestMapping(value = {"/name1","/name2"},produces = "text/plain;charset=UTF-8")// 6. 映射不同的路径
    public @ResponseBody String remove(HttpServletRequest request){
        return "url:"+request.getRequestURI()+" can access.";
    }
}

Spring学习--1. @RequestMapping的路径参数_第1张图片

你可能感兴趣的:(Spring)