Solon Web Development: 2. Development knowledge preparation

1. Agreement

//资源路径约定(不用配置;也不能配置)
resources/app.yml( 或 app.properties ) #为应用配置文件

resources/WEB-INF/static/ 或者 resources/static/     #为静态文件根目录(目录二选一,v2.2.10 后支持)
resources/WEB-INF/templates/   或者 resources/templates/  #为视图模板文件根目录,支持多种视图共存(目录二选一,v2.2.10 后支持)

//调试模式约定:
启动参数添加:--debug=1

2. Application startup process

Please refer to: The previous two paragraphs of "Application Life Cycle" .

3. Service port configuration

Specify in the main application configuration file:

server.port: 8081

System properties can be specified at runtime (higher priority):

java -Dserver.port=9091 -jar DemoApp.jar

Alternatively, specify it at runtime via startup parameters (higher priority):

java -jar DemoApp.jar -server.port=9091

4. Where to put static resources?

Solon's default static resource path is:

resources/static/

This default cannot be changed, but more can be added (for details, please refer to: "Ecology/solon.web.static" ):

#添加静态目录映射。(按需选择)#v1.11.0 后支持
solon.staticfiles.mappings:
  - path: "/img/" #路径,可以是目录或单文件
    repository: "/data/sss/app/" #1.添加本地绝对目录(仓库只能是目录)
  - path: "/"
    repository: "classpath:user" #2.添加资源路径(仓库只能是目录)
  - path: "/"
    repository: ":extend" #3.添加扩展目录

Under the default processing rules, all requests will first execute static file proxy. The static file agent will detect whether there is a static file and output it if it exists. If it does not, it will skip processing. The output static files will be 304 controlled.

The framework does not support the way "/" automatically jumps to "/index.html" (it is rare now and saves performance). If necessary, you can add filters to handle it manually:

@Component(index = 0) //index 为顺序位(不加,则默认为0)
public class AppFilter implements Filter {
    
    
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
    
    
        if("/".equals(ctx.pathNew())){
    
     //ContextPathFilter 就是类似原理实现的
            ctx.pathNew("/index.html");
        }

        chain.doFilter(ctx);
    }
} 

5. Path mapping expression description

symbol illustrate Example
** Any characters, no limit to the number of paragraphs **or/user/**
* any character /user/*
? Dispensable /user/?
/ Path segment start and separator characters /or/user
{name} Path variable declaration /user/{name}

For details, please refer to: "Common Annotations/@Mapping Usage Instructions"

6. Path redirection and forwarding

Path redirection

public class DemoController{
    
    
    @Mapping("/")
    public void home(Context ctx) {
    
    
        //通过302方式,通知客户端跳转到 “/index.html” (浏览器会发生2次请求,地址会变成/login)
        ctx.redirect("/index.html");
    }
}    

Path forwarding (forwarding to static files is not supported, static processing and routing processing are two systems)

public class DemoController{
    
    
    @Mapping("/")
    public void home(Context ctx) {
    
    
        //在服务端重新路由到 “/index.html” (浏览器发生1次请求,地址不会变)
        ctx.forward("/index.html");
    }
}    

7. Request parameter injection or manual acquisition

Supports direct injection of parameters in different forms such as queryString, form-data, x-www-form-urlencoded, path, json body, etc.:

//GET http://localhost:8080/test1?str=a&num=1
public class DemoController{
    
    
    @Mapping("/test1")
    public void test1(String str, int num) {
    
     //可自动注入 get, post, json body 形式的参数
        
    }
    
    @Mapping("/test2")
    public void test2(Context ctx) {
    
      
        //手动获取 get, post 参数
        String str = ctx.param("str");
        int num = ctx.paramAsInt("num", 0);
        
        //手动获取 body 请求的数据
        String body = ctx.body();
    }
}

Among them, queryString, form-data, x-www-form-urlencoded, and path parameters can be obtained uniformly through the ctx.param() interface.

8. Unified request exception handling and performance timing

//过滤所有因请求产生的异常(顺带加点别的)
@Slf4j
@Component
public class AppFilter implements Filter {
    
    
    @Override
    public void doFilter(Context ctx, FilterChain chain) throws Throwable {
    
    
        //1.开始计时(用于计算响应时长)
        long start = System.currentTimeMillis();
        try {
    
    
            chain.doFilter(ctx);

            //2.未处理设为404状态
            if(! ctx.getHandled()){
    
    
                ctx.status(404);
            }
            
            //3.404状态的定制(也可对别的状态处理)
            if (ctx.status() == 404) {
    
     
                ctx.setHandled(true);
                ctx.output("没有:(");
            }
        } catch (Throwable e) {
    
    
            //4.异常捕促与控制
            log.error(e);
        }

        //5.获得接口响应时长
        long times = System.currentTimeMillis() - start;
        System.out.println("用时:"+ times);
    }
}  

9. Read customized configuration files

//直接注入
@Configuration
public class Config{
    
    
    @Inject("${classpath:user.yml}")
    private UserModel user;
}

public class DemoApp{
    
    
    public static void main(String[] args){
    
    
        Solon.start(DemoApp.class, args, app->{
    
    
            //加载到应用配置
            app.cfg().loadAdd("user.yml");
        });
    }
}

10. There is also jsp support (not recommended)

Solon's jsp support is processed based on the positioning of the view template. The configuration differs slightly depending on the launcher component:

<!-- 添加 solon web 开发包 -->
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon-web</artifactId>
</dependency>

<!-- 添加 jetty 或 undertow 启动器 -->
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon.boot.jetty</artifactId>
</dependency>

<!-- 添加 jetty 或 undertow jsp 扩展支持包 -->
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon.boot.jetty.add.jsp</artifactId>
</dependency>

<!-- 添加 jsp 视图引擎 -->
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon.view.jsp</artifactId>
</dependency>

Guess you like

Origin blog.csdn.net/cwzb/article/details/131527107