使用RequestMapping处理同一url不同参数请求

文章目录

    • 提要
    • 转载RequestMapping注解API
      • @RequestMapping
        • 1、 value, method;
        • 2、 consumes,produces;
        • 3、 params,headers;
      • 每个参数的示例
        • 1、value / method 示例
        • 2 consumes、produces 示例
        • 3 params、headers 示例
    • 总结

提要

最近碰到个问题,例如我有一个api.do
index.do访问返回请求
index.do?id=1访问返回json数据
index.do?id=1&imgBase=sdWGawqe1cSd21CW访问返回json数据
但是自己在尝试着玩的时候
是这样玩的

@Controller
public class IndexController {

    @RequestMapping(value = "index")
    public ModelAndView showIndex(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("index");
        RequestContext context = new RequestContext(request);
        String indexTitle = context.getMessage("index.Body.title");
        view.getModel().put("IndexTitle", indexTitle);
        return view;
    }

    @RequestMapping(value = "index")
    public ModelAndView showIndexJson(HttpServletRequest request, Integer id) {
        ModelAndView view = new ModelAndView("index");
        RequestContext context = new RequestContext(request);
        String indexTitle = context.getMessage("index.Body.title");
        view.getModel().put("IndexTitle", indexTitle);
        return view;
    }
}

按照我的想法,用户访问api.do会走到第一个Mapping映射去,访问api.do?id=xx会走到第二个去,然后我尝试了启动服务器!

意思就是说出现了冲突的映射,说明我这样配置是不能够走通Spring的启动初始化了,于是查询了一下@RequestMapping注解的详细API,如下

提示:下面内容较多,如果不想阅读可以直接点击【目录->总结】

此区域内容为转载,无意冒犯及侵权,有问题的话联系删除,再此对该文章表示感谢。
原文来自:@RequestMapping注解详解

转载RequestMapping注解API

@RequestMapping

RequestMapping是一个用来处理请求地址映射的注解,可用于类或方法上。用于类上,表示类中的所有响应请求的方法都是以该地址作为父路径。

RequestMapping注解有六个属性,下面我们把她分成三类进行说明。

1、 value, method;

value: 指定请求的实际地址,指定的地址可以是URI Template 模式(后面将会说明);

method: 指定请求的method类型, GET、POST、PUT、DELETE等;

2、 consumes,produces;

consumes: 指定处理请求的提交内容类型(Content-Type),例如application/json, text/html;

produces: 指定返回的内容类型,仅当request请求头中的(Accept)类型中包含该指定类型才返回;

3、 params,headers;

params: 指定request中必须包含某些参数值是,才让该方法处理。

headers: 指定request中必须包含某些指定的header值,才能让该方法处理请求。

每个参数的示例

1、value / method 示例

默认RequestMapping("…str…")即为value的值;

@Controller
@RequestMapping("/appointments")
public class AppointmentsController {

    private AppointmentBook appointmentBook;
    
    @Autowired
    public AppointmentsController(AppointmentBook appointmentBook) {
        this.appointmentBook = appointmentBook;
    }

    @RequestMapping(method = RequestMethod.GET)
    public Map<String, Appointment> get() {
        return appointmentBook.getAppointmentsForToday();
    }

    @RequestMapping(value="/{day}", method = RequestMethod.GET)
    public Map<String, Appointment> getForDay(@PathVariable @DateTimeFormat(iso=ISO.DATE) Date day, Model model) {
        return appointmentBook.getAppointmentsForDay(day);
    }

    @RequestMapping(value="/new", method = RequestMethod.GET)
    public AppointmentForm getNewForm() {
        return new AppointmentForm();
    }

    @RequestMapping(method = RequestMethod.POST)
    public String add(@Valid AppointmentForm appointment, BindingResult result) {
        if (result.hasErrors()) {
            return "appointments/new";
        }
        appointmentBook.addAppointment(appointment);
        return "redirect:/appointments";
    }
}

value的uri值为以下三类:

  1. 可以指定为普通的具体值;
  2. 可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);可以指定为含有某变量的一类值(URI Template Patterns with Path Variables);
  3. 可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);可以指定为含正则表达式的一类值( URI Template Patterns with Regular Expressions);
@RequestMapping(value="/owners/{ownerId}", method=RequestMethod.GET)
public String findOwner(@PathVariable String ownerId, Model model) {
	Owner owner = ownerService.findOwner(ownerId);  
	model.addAttribute("owner", owner);  
	return "displayOwner"; 
}
@RequestMapping("/spring-web/{symbolicName:\[a-z-\]+}-{version:\\d\\.\\d\\.\\d}.{extension:\\.\[a-z\]}")
	public void handle(@PathVariable String version, @PathVariable String extension) {    
		// ...
	}
}

2 consumes、produces 示例

cousumes的样例:

@Controller
@RequestMapping(value = "/pets", method = RequestMethod.POST, consumes="application/json")
public void addPet(@RequestBody Pet pet, Model model) {    
	// implementation omitted
}

方法仅处理request Content-Type为“application/json”类型的请求。

produces的样例:

@Controller
@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, produces="application/json")
@ResponseBody
public Pet getPet(@PathVariable String petId, Model model) {    
	// implementation omitted
}

方法仅处理request请求中Accept头中包含了"application/json"的请求,同时暗示了返回的内容类型为application/json;

3 params、headers 示例

params的样例:

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {
	
	@RequestMapping(value = "/pets/{petId}", method = RequestMethod.GET, params="myParam=myValue")
	public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
		// implementation omitted
	}
}

仅处理请求中包含了名为“myParam”,值为“myValue”的请求;

headers的样例:

@Controller
@RequestMapping("/owners/{ownerId}")
public class RelativePathUriTemplateController {

	@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")
	public void findPet(@PathVariable String ownerId, @PathVariable String petId, Model model) {    
		// implementation omitted
	}
}

仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求;

总结

可以通过在@RequestMapping的params参数中设置可以传入的参数,且支持简单的表达式,如以下格式:

@RequestMapping(value = "index", params = {"id", "imgBase", "key!=null", "key"})

我们直接使用通过设置@RequestMapping的参数params即可,例如我还是最先的需求,那么我可以这样写

package biuaxia.mvc.controller;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.support.RequestContext;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/** * Class Describe: * * @author biuaxia * @date 2018/11/21 * @time 10:16 */
@Controller
public class IndexController {

    @RequestMapping(value = "index")
    public ModelAndView showIndex(HttpServletRequest request) {
        ModelAndView view = new ModelAndView("index");
        RequestContext context = new RequestContext(request);
        String indexTitle = context.getMessage("index.Body.title");
        view.getModel().put("IndexTitle", indexTitle);
        return view;
    }

    @RequestMapping(value = "index", params = "id")
    @ResponseBody
    public Object showIndexJsonById(HttpServletRequest request, Integer id) {
        Map<String, Object> maps = new HashMap<>(2);
        RequestContext context = new RequestContext(request);
        String testMsg = context.getMessage("index.Body.testMsg");
        maps.put("status", 200);
        maps.put("info", testMsg);
        maps.put("msg", id);
        return maps;
    }

    @RequestMapping(value = "index", params = {"id", "imgBase"})
    @ResponseBody
    public Object showIndexJsonByIdAndImgBase(HttpServletRequest request, Integer id, String imgBase) {
        Map<String, Object> maps = new HashMap<>(2);
        RequestContext context = new RequestContext(request);
        String testMsg = context.getMessage("index.Body.testMsg");
        maps.put("status", 200);
        maps.put("info", testMsg);
        maps.put("msg", id);
        maps.put("imgBase", imgBase);
        return maps;
    }

    @RequestMapping(value = "index", params = {"id", "imgBase", "key!=null", "key"})
    @ResponseBody
    public Object showIndexJsonByIdAndImgBaseAndKey(HttpServletRequest request, Integer id, String imgBase, String key) {
        Map<String, Object> maps = new HashMap<>(2);
        RequestContext context = new RequestContext(request);
        String testMsg = context.getMessage("index.Body.testMsg");
        maps.put("status", 200);
        maps.put("info", testMsg);
        maps.put("msg", id);
        maps.put("imgBase", imgBase);
        maps.put("key", key);
        return maps;
    }

}

他们分别对应了请求
index.do展示view视图index
index.do?id=返回包含id的json数据
index.do?id=&imgBase=返回包含id和imgBase的json数据
index.do?id=&imgBase=&key=这里会判断key不等于null,如果等于调上面那个方法

例如第四个调用截图
key为null时:

key只要不等于null即可,截图:

完结撒花~✿✿ヽ(°▽°)ノ✿

你可能感兴趣的:(Java笔记)