1. 程式人生 > 實用技巧 >Solon詳解(三)- Solon的web開發

Solon詳解(三)- Solon的web開發

一、Web基礎配置

//資源路徑說明(不用配置;也不能配置)
resources/application.properties(或 application.yml) 為應用配置檔案
resources/static/ 為靜態檔案根目標
resources/WEB-INF/view/ 為檢視模板檔案根目標(支援多檢視共存)

//除錯模式:
啟動引數新增:-deubg=1

1、訪問靜態資源

Solon 的預設靜態資源的路徑為:(這個沒得改,也不讓改;為了簡化套路)

resources/static/

在默放的處理規則下,所有請求,都會先執行靜態檔案代理。靜態檔案代理會檢測是否存在靜態檔案,有則輸出,沒有則跳過處理。輸出的靜態檔案會做304控制。

2、自定義攔截器

Solon裡所有的處理,都屬於XHandler。可以用handler 的模式寫,也可以用controller的模式寫(XAction 也是 XHandler)

// handler模式
//
XApp.global().before("/hello/", ctx->{
    if(ctx.param("name") == null){    
        ctx.setHandled(true);    //如果沒有name, 則終止處理
    }
});

// controller模式(只是換了個註解)
//
@XInterceptor
public class HelloInterceptor  {
    @XMapping(value = "/hello/" , before = true)
    public void handle(XContext ctx, String name) {
        if(name == null){            
            ctx.setHandled(true);  //如果沒有name, 則終止處理
        }
    }
}

3、讀取外部的配置檔案

@XConfiguration
public class Config{
    @XInject("${classpath:user.yml}")
    private UserModel user;
}

4、HikariCP DataSource的配置

HiKariCP是資料庫連線池的一個後起之秀,號稱效能最好,可以完美地PK掉其他連線池。作者特別喜歡它。

a.引入依賴
<dependency>
    <groupId>com.zaxxer</groupId>
    <artifactId>HikariCP</artifactId>
    <version>3.3.1</version>
</dependency>

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>8.0.18</version>
</dependency>
b.新增配置
test.db1:
    schema: "rock"
    jdbcUrl: "jdbc:mysql://localdb:3306/rock?useUnicode=true&characterEncoding=utf8&autoReconnect=true&rewriteBatchedStatements=true"
    driverClassName: "com.mysql.cj.jdbc.Driver"
    username: "demo"
    password: "UL0hHlg0Ybq60xyb"
    maxLifetime: 1000000
c.配置HikariCP資料來源

建議這種操作,都安排在 @XConfiguration 配置類裡執行。

//註解模式
//
@XConfiguration
public class Config{
    
    @XBean
    pubblic HikariDataSource dataSource(@XInject("${test.db1}") HikariDataSource dataSource){
        retun dataSource;
    }
}

//靜態類模式
//
//public class Config{
//    pubblic static HikariDataSource dataSource = XApp.cfg().getBean("test.db1", HikariDataSource.class);
//}

之後就可以通過@XInject註解得到這個資料來源了。實際上一般不會直接使用資料來源。

6、資料庫操作框架整合

a.Weed3整合

Wee3是和Solon一樣輕巧的一個框架,配置起來自然是簡單的。

在pom.xml中引用weed3擴充套件元件

<dependency>
    <groupId>org.noear</groupId>
    <artifactId>weed3-solon-plugin</artifactId>
</dependency>

修改剛才的Config配置類及使用示例,先以單資料來源場景演示:

//修改剛才的配置
//
@XConfiguration
public class Config{
    
    @XBean // @XBean("db1") 為多源模式
    public DbContext db1(@XInject("${test.db1}") HikariDataSource dataSource) {
        String schema = dataSource.getSchema();
        return new DbContext(schema, dataSource);
    }
}

//使用示例
@XController
public class DemoController{
    @Db   //@Db("db1") 為多源模式  //@Db是weed3在Solon裡的擴充套件註解 //可以注入 Mapper, BaseMapper, DbContext
    BaseMapper<UserModel> userDao;
    
    @XMapping("/user/")
    pubblic UserModel geUser(long puid){
        return userDao.selectById(puid);
    }
}
b.Mybatis整合

在pom.xml中引用mybatis擴充套件元件

<dependency>
    <groupId>org.noear</groupId>
    <artifactId>mybatis-solon-plugin</artifactId>
</dependency>

新增mybatis mappers及相關的屬性配置

mybatis:
    typeAliases:    #支援包名 或 類名(.class 結尾)
        - "webapp.model"
    mappers:        #支援包名 或 類名(.class 結尾)或 xml(.xml結尾);配置的mappers 會 mapperScan並交由Ioc容器託管
        - "webapp.dso.mapper.UserMapper.class"

#mybatis.db1:  #多源配置模式
#    typeAliases:   
#        - "webapp.model"
#    mappers:     
#        - "webapp.dso.mapper.UserMapper.class"

修改剛才的Config配置類及使用示例

//修改剛才的配置
//
@XConfiguration
public class Config{
    
    @XBean    //@XBean("db1") 為多源模式
    public SqlSessionFactory db1(@XInject("${test.db1}") HikariDataSource dataSource) {
        return new MybatisAdapter(dataSource)
                .mapperScan()   //此方法會掃描配置的mappers,並進行託管  //這塊比Spring要簡便些
                .getFactory();
    }
}

//使用示例
@XController
public class DemoController{
    @Db    //@Db("db1") 為多源模式    //@Db 可注入 SqlSessionFactory,SqlSession,Mapper
    UserMapper userDao;  //UserMapper 已被 db1 mapperScan並已託管,也可用 @XInject 注入
    
    @XMapping("/user/")
    pubblic UserModel geUser(long puid){
        return userDao.geUser(puid);
    }
}

7、使用事務

Solon中推薦使用@XTran註解來申明和管理事務。

@XTran 支援單源事務和多源事務,且使用方便

a.Weed3的事務
//使用示例
@XController
public class DemoController{
    @Db  //@Db("db1") 為多源模式
    BaseMapper<UserModel> userDao;
    
    @XTran     //@XTran("db1")  為多源模式
    @XMapping("/user/add")
    pubblic Long addUser(UserModel user){
        return userDao.insert(user, true); 
    }
}
b.Mybatis的事務
@XController
public class DemoController{
    @Db  
    UserMapper userDao;  //UserMapper 已被 db1 mapperScan並已託管,也可用 @XInject 注入
    
    @XTran    //@XTran("db1")  為多源模式
    @XMapping("/user/add")
    pubblic Long addUser(UserModel user){
        return userDao.addUser(user); 
    }
}
c.混合多源事務(這個時候,我們需要Service層參演了)
@XService
public class UserService{
    @XTran("db1")
    public void addUser(UserModel user){
        //....
    }
}

@XService
public class AccountService{
    @XTran("db2")
    public void addAccount(UserModel user){
        //....
    }
}

@XController
public class DemoController{
    @XInject
    AccountService accountService; 
    
    @XInject
    UserService userService; 
    
    @XTran(multisource = true) //混合多源事務
    @XMapping("/user/add")
    pubblic Long geUser(UserModel user){
        Long puid = userService.addUser(user);     //會執行db1事務
        
        accountService.addAccount(user);    //會執行db2事務
        
        return puid;
    }
}

8、開始jsp支援(不建議用)

solon 的jsp支援,是基於檢視模板的定位去處理的。根據啟動器元件的不同,配置略有不同:

<!-- 新增 solon web 開發包 -->
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon-web</artifactId>
    <type>pom</type>
    <exclusions>
        <!-- 排除預設的 jlhttp 啟動器 -->
        <exclusion>
            <groupId>org.noear</groupId>
            <artifactId>solon.boot.jlhttp</artifactId>
        </exclusion>
    </exclusions>
</dependency>

<!-- 新增 jetty 或 undertow 啟動器 -->
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon.boot.jetty</artifactId>
</dependency>

<!-- 新增 jetty 或 undertow jsp 擴充套件支援包 -->
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon.extend.jetty.jsp</artifactId>
    <type>pom</type>
</dependency>

<!-- 新增 jsp 檢視引擎 -->
<dependency>
    <groupId>org.noear</groupId>
    <artifactId>solon.view.jsp</artifactId>
</dependency>

二、Web開發進階

1、Solon的MVC註解

a.@XController

控制器,只有一個註解。會自動通過不同的返回值做不同的處理

@XController
public class DemoController{
    @XMapping("/test1/")
    public void test1(){
        //沒返回
    }
    
    @XMapping("/test2/")
    public String test2(){
        return "返回字串並輸出";
    }
    
    @XMapping("/test3/")
    public UseModel test3(){
        return new UseModel(2, "noear"); //返回個模型,預設會渲染為json格式輸出
    }
    
    @XMapping("/test4/")
    public ModelAndView test4(){
        return new ModelAndView("view path", map); //返回模型與檢視,會被檢視引擎渲染後再輸出,預設是html格式
    }
}
b.@XMapping(value, method, produces)

預設只需要設定value值即可,method預設為XMethod.HTTP,即接收所有的http方法請求。

@XMapping("/user/")

2、檢視模板開發

freemaerker 檢視

<!doctype html>
<html>
<head>
    <meta charset="UTF-8">
    <title>${title}</title>
</head>
<body>
<div>
     ${message}
</div>
</body>
</html>

控制器

@XController
public class HelloworldController {
    @XMapping("/helloworld")
    public Object helloworld(){
        ModelAndView vm = new ModelAndView("helloworld.ftl");

        vm.put("title","demo");
        vm.put("message","hello world!");

        return vm;
    }
}

3、模板除錯模式(即:模板修改後,瀏覽器重新整理即可)

//除錯模式:
啟動引數新增:-deubg=1 或 --deubg=1

4、資料校驗

Solon框架不存在這塊,因為 lombok 框架已經很好了,用著就是。業務層面的資料較驗後面會做個專門的介紹。

5、統一異常處理

XApp.start(source, args)
    .onError(err->err.printStackTrace()); //或者記錄到日誌系統

三、打包與部署

1、在pom.xml中配置打包的相關外掛

Solon 的專案必須開啟編譯引數:-parameters

<build>
    <finalName>${project.name}</finalName>
    <plugins>

        <!-- 配置編譯外掛 -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <configuration>
                <compilerArgument>-parameters</compilerArgument> 
                <source>1.8</source>
                <target>1.8</target>
                <encoding>UTF-8</encoding>
            </configuration>
        </plugin>

        <!-- 配置打包外掛(設定主類,並打包成胖包) -->
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <configuration>
                <finalName>${project.name}</finalName>
                <appendAssemblyId>false</appendAssemblyId>
                <descriptorRefs>
                    <descriptorRef>jar-with-dependencies</descriptorRef>
                </descriptorRefs>
                <archive>
                    <manifest>
                        <mainClass>webapp.DemoApp</mainClass>
                    </manifest>
                </archive>
            </configuration>
            <executions>
                <execution>
                    <id>make-assembly</id>
                    <phase>package</phase>
                    <goals>
                        <goal>single</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
    </plugins>
</build>

2、執行 maven 的 package 指令完成打包(IDEA的左測介面,就有這個選單)

3、終端執行:java -jar DemoApp.jar 即可啟動