Solon v2.7.5

A、MVC 常用注解

</> markdown

更多内容可参考:@Mapping 用法说明

1、主要注解

注解说明
@Controller控制器注解(只有一个注解,会自动通过不同的返回值做不同的处理)
@Param注入请求参数(包括:QueryString、Form、Path)。主要提供默认值等支持
@Header注入请求 header
@Cookie注入请求 cookie
@Path注入请求 path 变量(因为框架会自动处理,所以这个只是标识下方便文档生成用)
@Body注入请求体(一般会自动处理。仅在主体的 String, Steam, Map 时才需要)
@Mapping路由关系印射注解
@Get@Mapping 的辅助注解,便于 RESTful 开发
@Post@Mapping 的辅助注解,便于 RESTful 开发
@Put@Mapping 的辅助注解,便于 RESTful 开发
@Delete@Mapping 的辅助注解,便于 RESTful 开发
@Patch@Mapping 的辅助注解,便于 RESTful 开发
@Produces输出内容类型申明
@Consumes输入内容类型申明(当输出内容类型未包函 @Consumes,则响应为 415 状态码)

2、组合效果

@Controller
public class DemoController{
    @Get
    @Mapping("/test1/")
    public void test1(){
        //没返回
    }
    
    @Produces(MimeType.APPLICATION_JSON_VALUE)
    @Get
    @Mapping("/test2/")
    public String test2(){
        return "{\"message\":\"返回字符串并输出\"}";
    }
    
    @Mapping("/test3/")
    public UseModel test3(@Param(defaultValue="world") String name){ //接收请求name参数
        //返回个模型,默认会渲染为json格式输出
        return new UseModel(2, name); 
    }
    
    @Mapping("/test4/{qb_dp}")
    public ModelAndView test4(String qb_dp, @Body String bodyStr){//接收路径变量和主体字符串
        //返回模型与视图,会被视图引擎渲染后再输出,默认是html格式
        Map<String,String> map = new HashMap<>();
        map.put("name", qb_dp);
        map.put("body", bodyStr);
        
        return new ModelAndView("view path", map); 
    }
    
    @Mapping("/test5/")
    public void test5(int id, String name, Context ctx){ //可自动接收:get, post, json body 参数
        ModelAndView vm = new ModelAndView("view path");  
        vm.put("id", id);
        vm.put("name", name);
        
        //渲染拼直接返回(不输出)
        String html = ctx.renderAndReturn(vm);
        
        db.table("test").set("html", html).insert();
    }
}