1 Star 0 Fork 23

tide2046 / jfast

forked from 跳动的小营哥 / jfast 
加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
贡献代码
同步代码
取消
提示: 由于 Git 不支持空文件夾,创建文件夹后会生成空的 .keep 文件
Loading...
README
Apache-2.0

jfast是javaEE的一款简易mvc框架.


范例:

配置web.xml

<?xml version="1.0" encoding="UTF-8"?>

<web-app version="2.4"
     xmlns="http://java.sun.com/xml/ns/j2ee"
     xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
     xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd">

     <filter>
         <filter-name>JFast</filter-name>
         <filter-class>cn.jfast.framework.web.core.ApiFilter</filter-class>
     </filter>

     <filter-mapping>
        <filter-name>JFast</filter-name>
        <url-pattern>/*</url-pattern>
     </filter-mapping>

     <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
     </welcome-file-list>

</web-app>

jfast配置文件(src根目录下)

<?xml version="1.0" encoding="UTF-8"?>

<context xmlns="http://www.jfast.cn/context"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://www.jfast.cn/context
                            http://www.jfast.cn/context/jfast-context.xsd">

    <!-- 数据库参数配置 -->
    <jdbc jdbcUser="****"
          jdbcPassword="****"
          jdbcUrl="jdbc:mysql://******:3306/jfast?characterEncoding=utf8"
          jdbcDriver="com.mysql.jdbc.Driver"/>

    <!-- 日志属性配置 -->
    <log isInfoEnable="true"
         isWarnEnable="true"
         isDebugEnable="true"
         isErrorEnable="true"/>
    <web isDevMode="true" characterEncoding="UTF-8"/>

    <!-- 微信公众号配置 -->
    <wx aesKey="******"
        appId="******"
        appSecret="******"
        token="******"
        handler="cn.app.wx.logic.WxApiHandler"/>

    <!-- 静态资源配置,现在这个功能还没做 -->
    <resources location="/js" mapping="/js"/>
    <resources location="/image" mapping="/image"/>

</context>

创建MVC的M模型层

模型层就是普通的pojo对象,不需要做任何改动.


创建Dao层

package cn.app.wx.dao;

import cn.app.wx.model.User;
import cn.jfast.framework.jdbc.annotation.Body;
import cn.jfast.framework.jdbc.annotation.Dao;
import cn.jfast.framework.jdbc.annotation.Select;
import cn.jfast.framework.jdbc.db.ConnectionFactory;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
java.util.Map;

@Dao
public class UserDao {

  private Connection conn;
  private PreparedStatement ps;
  private ResultSet rs;

  @Body  //该方法将执行方法体中的复杂操作(内容可以替换为其他的任何orm框架,实现jfast与其他框架兼容)
  public User selectAllFromUserByEmailPassword(String email, String password) throws SQLException, ClassNotFoundException {
     User user = new User();
     conn = ConnectionFactory.getThreadLocalConnection();
     ps = conn.prepareStatement("select * from user where email = ? and password = ?");
     ps.setString(1,email);
     ps.setString(2,password);
     rs = ps.executeQuery();
     if(rs.next()){
        user.setBirthday(rs.getDate("birthday"));
        user.setEmail(rs.getString("email"));
        user.setPassword(rs.getString("password"));
        user.setPhone(rs.getString("phone"));
        user.setSex(rs.getString("sex"));
        user.setUserid(rs.getInt("userid"));
        user.setUsername(rs.getString("username"));
        if(rs.next())
           throw new SQLException("查询目标为一条,但是查出了多条记录.");
     }
     return user;
  }

  /**
  * 像这种没有@Body注解的方法,jfast会解析方法名,参数,返回值,自动生成sql
  */
  public boolean deleteFromUserByEmail(String email){
     return false;
  }

  public int updateUserSetPasswordByEmail(String Email, String password){
     return 1;
  }

  /**
  * 像有Select,Update,Delete,Insert注解的方法,jfast则以注解的sql为准
  */
  @Select(sql = "select * from user where email = :email")
  public Map<String,Object> select(String email){
     return null;
  }

}

jfast对dao的支持与以往的框架不同:

1. Dao类类名需要加@Dao注解,
2. 如果Dao类类名加@Body注解,那么执行该dao类的方法时,都执行方法体中的内容,比如示例中的第一个方法,执行userDao.selectAllFromUserByEmailPassword(**)时,会使用方法体中的操作;如果没有@Body注解,则jfast会根据方法名以及注解的属性来生成sql
3. 如果方法名上没有@Select,@Update,@Insert,@Delete中的任何一个注解,那么jfast就根据方法名成来生成sql,具体生成规则:
        update表名Set更改字段By依据字段
        deleteFrom表名By依据字段
        select查询字段From表名By依据字段
        insertInto表名Values插入字段

创建MVC中的C控制器层

package cn.app.wx.controller;

import cn.app.wx.dao.UserDao;
import cn.app.wx.model.User;
import cn.jfast.framework.base.util.ApiCaller;
import cn.jfast.framework.jdbc.annotation.Transaction;
import cn.jfast.framework.web.api.annotation.*;
import cn.jfast.framework.web.view.Route;
import cn.jfast.framework.web.view.viewtype.Json;
import cn.jfast.framework.web.view.viewtype.Jsp;
import cn.jfast.framework.web.view.viewtype.Text;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.sql.SQLException;
import java.util.Map;

@Api("/jsp")
public class LoginController {

    @Resource
    UserDao userDao; //自动注入Dao类,java类名上有@Resource注解时,也可以用@Resource实现注入

    @Transaction  //启动事务管理
    @Post("login")  //接收post请求,请求全路径:/jsp/login
    public Json login(String email,String password,HttpServletRequest request) throws SQLException, ClassNotFoundException {
        User user = userDao.selectAllFromUserByEmailPassword(email,password);
        if(null != user) {
            request.getSession().setAttribute("user", user);
            return new Json("{login:true}");
        } else {
            return new Json("{login:false}");
        }
    }

    @Post("home") //该方法接收Post请求,请求全路径:/jsp/home
    @Get("home")  //该方法也可以接收Get请求,请求全路径:/jsp/home
    public Jsp home(HttpServletRequest request){
        //测试Dao类操作
        Map<String,Object> userMap = userDao.select("*****@**.com");
        boolean user =userDao.deleteFromUserByEmail("****@**.com");
        int result = userDao.updateUserSetPasswordByEmail("******@**.com","123456");

        if(null != request.getSession().getAttribute("user"))
            return new Jsp("jsp/home", Route.REDIRECT);
        else
            return null;
    }

    @Post("logout")
    public Json logout(HttpServletRequest request){
        ResultDemo resutl = (ResultDemo)ApiCaller.put("jsp/doLogOut",
                    request.getSession().getAttribute("user")); //调用jsp/doLogOut服务,返回服务结果对象
        if(resutl.errCode.equals("1"))
            return new Json("{logout:true}");
        else
            return new Json("{logout:false}");
    }

    @Put("doLogOut")
    public Callback put(@RemoteObject User user){ //返回服务回调对象
        if(null != user)
            return new Callback(new ResultDemo("1","注销成功"));
        else
            return new Callback(new ResultDemo("2","未获取到登录账户"));
    }

    class ResultDemo implements Serializable{
        String errCode;
        String errInfo;

        ResultDemo(String errCode,String errInfo){
            this.errCode = errCode;
            this.errInfo = errInfo;
        }
    }

}

创建拦截器

package cn.app.wx.interceptor;

import cn.jfast.framework.web.aop.AopHandler;
import cn.jfast.framework.web.aop.AopScope;
import cn.jfast.framework.web.aop.annotation.Aop;
import cn.jfast.framework.web.api.ApiInvocation;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

@Aop(scope = AopScope.Global)
public class LoginStatusInterceptor extends AopHandler {
    @Override
    public void beforeHandle(ApiInvocation apiInvocation, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, List<Exception> list) throws Exception {
        apiInvocation.invoke(); //最后必须调用invoke()方法,否则,请求不会传到指定的Api方法中
    }

    @Override
    public void afterHandle(ApiInvocation apiInvocation, HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, List<Exception> list) throws Exception {
        apiInvocation.invoke(); //最后必须调用invoke()方法,否则,后面的拦截器后置方法不会执行
    }
}

创建定时任务类

package cn.app.wx.task;

import cn.jfast.framework.log.LogFactory;
import cn.jfast.framework.log.Logger;
import cn.jfast.framework.web.api.annotation.Schedule;
import cn.jfast.framework.web.api.annotation.ScheduleJob;

@ScheduleJob
public class SimpleTask {

    private Logger log = LogFactory.getLogger(SimpleTask.class);

    @Schedule(cron = "0 1-5 * * * 2016")
    public void run1(){
        log.info("CRON类定时任务启动...");
    }

    @Schedule(delay = 0,repeat = 5,repeatInterval = 500000)
    public void run2(){
        log.info("延时类定时任务启动...");
    }
}

创建JFast单元测试

package cn.app.wx.dao.test;

import cn.app.wx.dao.UserDao;
import cn.app.wx.model.User;
import cn.jfast.framework.log.LogFactory;
import cn.jfast.framework.log.Logger;
import cn.jfast.framework.web.core.junit.JfastJUnit4ClassRunner;
import org.junit.Test;
import org.junit.runner.RunWith;
import javax.annotation.Resource;
import java.sql.SQLException;

@RunWith(JfastJUnit4ClassRunner.class)  //jfast项目单元测试,需要配置该注解,启动jfast环境
public class UserTest {

    @Resource
    private UserDao userDao;

    private Logger log = LogFactory.getLogger(UserTest.class);

    @Test
    public void test() throws SQLException, ClassNotFoundException {
        User user = userDao.selectAllFromUserByEmailPassword("1297450431@qq.com","123456");
        userDao.updateUserSetPasswordByEmail("1297450431@qq.com", "123456");
        userDao.deleteFromUserByEmail("123");
        userDao.select("1297450431@qq.com").get("password");
    }

}

jfast注解介绍:

控制器注解

@Api
其参数为该类对应的请求路径,有该注解的类,在应用启动时,被加载到控制器缓存中.
@DateFormat
如果参数对象中包含日期类型或者参数本身就是日期类型,那么参数前需要有该注解,否则,日期参数将不能正确解析.
@RemoteObject
使用ApiCaller调用的服务可以传递java对象,目标服务方法中的用来接收远程对象的参数需要有@RemoteObject
注解 (这里要注意ApiCaller是服务调用,和浏览器发出的请求是不同的)
@RequireParam
如果参数名和请求传递到后台的名称不同,那么jfast解析该参数时,
取@RequireParam注解指定的参数名,如果其属性required为true,则该参数不可为空.
@Post,
@Get
表示该方法只能接受对应方式的请求,其参数值为方法对应的请求路径,
POST,GET请求可以由浏览器等所有实现http协议的终端发出
@Put,
@Delete,
@Head,
@Options,
@Trace
表示该方法只能接受对应方式的请求,其参数值为方法对应的请求路径,
PUT,DELETE,HEAD,OPTIONS,TRACE请求可以由ApiCaller或者某些http工具发出.
@Copy,
@Connect,
@Lock,
@Unlock,
@Move,
@Mkcol,
@Patch,
@Porpfind,
@Proppatch,
@Search
表示该方法只能接受对应方式的请求,请求可由完整实现http协议的终端发出.
@Transaction
声明该方法需要事务管理

拦截器注解

@Aop
jfast拦截器类需要继承AopHandler类,并且有@Aop注解
全局拦截器: Aop注解属性(scope=AopScope.Global) 代表全局拦截器,在应用启动时,被加载到拦截器缓存中,
方法拦截器: Aop注解属性(scope=AopScope.Method) 代表方法级拦截器(方法拦截器也可以不配置该属性).

DAO类注解

@Dao
Dao类声明注解.
@Select
select语句注解
@Update
update语句注解
@Delete
delete语句注解
@Insert
insert语句注解
@Body
该注解表示,调用该数据接口时,执行该方法的方法体来进行数据操作.否则jfast会解析方法名注解等来执行数据操作

定时任务注解

@ScheduleJob
有该注解的类,在应用启动时,被加载到定时任务缓存中.
@Schedule
其参数:cron有值时,jfast解析cron表达式来执行定时任务,否则按照 delay(延时多少毫秒启动),
repeat(任务执行次数),repeatInterval(重复任务的间隔毫秒数) 的规则执行;
JFast CRON表达式:
"* * * * * *" 代表 秒 分 时 日 月 年,
其中 每个参数都可以使用 1或者 1,2,3 或者 5-10 或者 1,2-5,7-8,10等形式


jfast控制方法返回视图介绍

Text视图:返回普通文本给前台
Jsp视图:返回JSP页面
Download视图:发送文件给客户端下载,
Json视图:返回Json数据
Api视图:转发请求到指定Api(只能携带原请求参数,需要在Api中调用其他Api,且自定义参数时,使用ApiCaller来调用服务)
Callback:当Api作为远程服务时,返回可序列化对象

Apache License Version 2.0, January 2004 http://www.apache.org/licenses/ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 1. Definitions. "License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document. "Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License. "Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity. "You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License. "Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files. "Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types. "Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below). "Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof. "Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution." "Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work. 2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form. 3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed. 4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions: You must give any other recipients of the Work or Derivative Works a copy of this License; and You must cause any modified files to carry prominent notices stating that You changed the files; and You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License. You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License. 5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions. 6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file. 7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License. 8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages. 9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability. END OF TERMS AND CONDITIONS APPENDIX: How to apply the Apache License to your work To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "{}" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives. Copyright 2015 泛泛o0之辈 Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

简介

javaEE 快速MVC开发框架 展开 收起
Apache-2.0
取消

发行版

暂无发行版

贡献者

全部

近期动态

加载更多
不能加载更多了
1
https://gitee.com/tide2046/jfast.git
git@gitee.com:tide2046/jfast.git
tide2046
jfast
jfast
master

搜索帮助