在qt中使用qtwebapp搭建http服务器的详细步骤-kb88凯时官网登录

来自:网络
时间:2024-09-10
阅读:
免费资源网,https://freexyz.cn/

前言

最近在开发qt的http服务器功能,研究比较了一番,选择了qtwebapp方案,相对其他开源库,比较推荐使用该方案,功能齐全,简单易用,如果赶项目的话,极力推荐。

下面介绍一下qt集成qtwebapp步骤:

一、qt集成qtwebapp步骤:

1、下载qtwebapp源码:把源码拉下来到本地,将httpsever目录整个移植到自己的项目工程下。

在qt中使用qtwebapp搭建http服务器的详细步骤

在qt中使用qtwebapp搭建http服务器的详细步骤

在qt中使用qtwebapp搭建http服务器的详细步骤

2、在pro文件包含httpserver

include ($$pwd/httpserver/httpserver.pri)

这样就完成集成源码了,剩下的就是根据你自己的业务需求去开发了,细节可以参考demo1和demo2。

二、在qt中使用qtwebapp搭建http服务器

第一步 下载qtwebapp导入工程中

工程示例:

在qt中使用qtwebapp搭建http服务器的详细步骤

第二步 编写配置文件webapp.ini

host=192.168.255.128	;服务ip地址
port=8080				;端口号
minthreads=4			;4个线程始终保持运行状态
maxthreads=100			;并发工作线程的最大数量
cleanupinterval=60000
readtimeout=60000
maxrequestsize=16000
maxmultipartsize=10000000

第三步 加载配置文件,创建http侦听器对象

main.cpp

#include "httplistener.h"
#include "httprequesthandler.h"
#include "requestmapper.h" //自定义类请求映射器类
    qsettings* listenersettings=
            new qsettings(qcoreapplication::applicationdirpath() "/webapp.ini",qsettings::iniformat);
    new stefanfrings::httplistener(listenersettings, new requestmapper());

第四步 自定义类请求映射器类

requestmapper.h

#ifndef requestmapper_h
#define requestmapper_h
#include "httprequesthandler.h"
using namespace stefanfrings;
#include "hellocontroller.h"
class requestmapper:public httprequesthandler
{
public:
    requestmapper();
    void service(httprequest& request, httpresponse& response);
private:
    hellocontroller m_hellocontroller;
};
#endif // requestmapper_h

requestmapper.cpp

#include "requestmapper.h"
#include "json.hpp"
#include 
using namespace std;
using namespace nlohmann;
requestmapper::requestmapper()
{
}
void requestmapper::service(httprequest &request, httpresponse &response)
{
    qbytearray path=request.getpath();
    qbytearray method = request.getmethod();
    qbytearray nm = request.getparameter("nm");
    qdebug() << "requestmapper: path=" << path.data();
    qdebug() << "requestmapper: method=" << method.data();
     qdebug() << "requestmapper: nm=" << nm.data();
    if ( path=="/hello") {
        m_hellocontroller.service(request,response);
    }
}

第五步 自定义业务请求处理类

hellocontroller .h

#ifndef hellocontroller_h
#define hellocontroller_h
#include 
#include "httprequesthandler.h"
using namespace stefanfrings;
#include "json.hpp"
using namespace nlohmann;
#include 
using namespace std;
class hellocontroller : public qobject
{
    q_object
public:
    explicit hellocontroller(qobject *parent = 0);
    void service(httprequest& request, httpresponse& response);
signals:
public slots:
};
#endif // hellocontroller_h

hellocontroller.cpp

#include "hellocontroller.h"
hellocontroller::hellocontroller(qobject *parent) : qobject(parent)
{
}
void hellocontroller::service(httprequest &request, httpresponse &response)
{
   qbytearray body = request.getbody();
   qdebug() << body;
    json res;
    res["code"] = 200;
    res["mesage"] = "success";
    string str = res.dump(4);
    //    response.setstatus(404);
    response.write(str.c_str());
}

第六步 测试

服务运行示例

在qt中使用qtwebapp搭建http服务器的详细步骤

浏览器发请求示例

在qt中使用qtwebapp搭建http服务器的详细步骤

另外:其他的映射和控制器写法:

requestmapper.h
#ifndef requestmapper_h
#define requestmapper_h
#include "qtwebapp/httpserver/httprequesthandler.h"
using namespace stefanfrings;
/*
  the request mapper dispatches incoming http requests to controller classes
  depending on the requested path.
*/
class requestmapper : public httprequesthandler {
    q_object
    q_disable_copy(requestmapper)
public:
    /*
      constructor.
      @param parent parent object
    */
    requestmapper(qobject* parent=0);
    /*
      destructor.
    */
    ~requestmapper();
    /*
      dispatch incoming http requests to different controllers depending on the url.
      @param request the received http request
      @param response must be used to return the response
    */
    void service(httprequest& request, httpresponse& response);
    // 拦截未授权操作
    bool prehandle(httprequest& request, httpresponse& response);
};
#endif // requestmapper_h

requestmapper.cpp

#include "requestmapper.h"
#include "global.h"
#include "controller/logincontroller.h"
#include "controller/funcvercodecontroller.h"
#include "controller/sysmsgcontroller.h"
#include "controller/sysusercontroller.h"
#include "controller/commoncontroller.h"
#include "controller/sysmenucontroller.h"
#include "controller/sysdiccontroller.h"
#include "controller/sysrolecontroller.h"
#include "controller/sysdeptcontroller.h"
#include "controller/syslogcontroller.h"
#include "controller/funcmonitorcontroller.h"
#include "controller/sysusermsgcontroller.h"
#include "controller/funcsmscontroller.h"
#include "controller/funcemailcontroller.h"
#include "controller/funcloadcontroller.h"
#include "controller/funcexportcontroller.h"
#include
requestmapper::requestmapper(qobject* parent)
    :httprequesthandler(parent)
{
    qdebug("requestmapper: created");
    qdebug()<<".................requestmapper created......................currentthreadid():"<service(request, response);
    }
    qdebug("requestmapper: finished request");
    // clear the log buffer
    if (logger)
    {
    //   logger->clear();
    }
}
// 拦截未授权操作
bool requestmapper::prehandle(httprequest& request, httpresponse& response)
{
    // token校验不通过,返回1001
    resultjson result(1001, false, qstringliteral("token已失效"));
    qstring accesstoken = request.getheader("access_token");
    if(accesstoken == null || accesstoken.isempty())
        accesstoken = request.getparameter("access_token");
    if(accesstoken == null || accesstoken.isempty())
    {
        result.failedmsg(qstringliteral("找不到token"));
        responseutil::replyjson(response, result);
        //staticfilecontroller->service(request, response);
        return false;
    }
    //根据token登录
    qstring username = jwtutil::getusername(accesstoken);
    if(username == null || username.isempty())
    {
        responseutil::replyjson(response, result);
        //staticfilecontroller->service(request, response);
        return false;
    }
    //判断token是否有效
    qstring token_key = username   "_token";
    qstring savetoken = cacheapi::instance()->get(token_key);
    if(savetoken != accesstoken)
    {
        responseutil::replyjson(response, result);
        //staticfilecontroller->service(request, response);
        return false;
    }
    //刷新token
    cacheapi::instance()->insert(token_key, accesstoken, jwtutil::expired_time);
    return true;
}
logincontroller.h
#ifndef logincontroller_h
#define logincontroller_h
#include "global.h"
#include 
using namespace stefanfrings;
class logincontroller: public httprequesthandler {
    q_object
    q_disable_copy(logincontroller)
public:
    logincontroller();
    void service(httprequest& request, httpresponse& response);
    void   login(httprequest& request, httpresponse& response); //登录
    void  logout(httprequest& request, httpresponse& response); //退出
private:
    sqlhelper* m_phelper;
    typedef void (logincontroller::*pservfunc)(httprequest& request, httpresponse& response);
    qmap m_mapfunc;
};
#endif // logincontroller_h
logincontroller.cpp
#include "logincontroller.h"
#include 
#include 
logincontroller::logincontroller()
{
    qdebug()<<"....................logincontroller........................currentthreadid():"<initdb("qtwebadmin.db");
    m_mapfunc.insert("/login",   &logincontroller::login);      //登录
    m_mapfunc.insert("/logout",  &logincontroller::logout);     //登出
}
void logincontroller::service(httprequest& request, httpresponse& response)
{
    qdebug()<<"...................logincontroller::service........................currentthreadid():"<*func)(request, response);
    }
}
void logincontroller::login(httprequest& request, httpresponse& response)
{
    qdebug()<<"..................logincontroller::login...................currentthreadid():"<getsession(request, response, true);
    if(username.isempty())
    {
        ret.failedmsg(qstringliteral("用户名为空"));
        response.write(ret.tostring().tolocal8bit());
        return;
    }
    if(password.isempty())
    {
        ret.failedmsg(qstringliteral("密码为空"));
        response.write(ret.tostring().tolocal8bit());
        return;
    }
    if(vercode.isempty())
    {
        ret.failedmsg(qstringliteral("验证码为空"));
        response.write(ret.tostring().tolocal8bit());
        return;
    }
    //
//    if(!session.contains("vercode"))
//    {
//        ret.failedmsg(qstringliteral("未找到验证码"));
//        response.write(ret.tostring().tolocal8bit());
//        return;
//    }
    //跨域情况下,以网页请求时附带uuid,作为验证码标志
    qstring sessioncode = cacheapi::instance()->get(codeid   "_vercode");
    if(sessioncode.isnull())
    {
        ret.failedmsg(qstringliteral("未找到验证码或验证码已过期"));
        response.write(ret.tostring().tolocal8bit());
        return;
    }
    //qstring sessioncode = session.get("vercode").tostring();
    if(sessioncode.tolower() != vercode.tolower())
    {
        ret.failedmsg(qstringliteral("验证码不匹配"));
        response.write(ret.tostring().tolocal8bit());
        return;
    }
    //................检查密码
    sysuser loginuser;
    if(!m_phelper->selectuserbyname(loginuser, username))
    {
        ret.failedmsg(qstringliteral("未找到用户或密码不正确!"));
        response.write(ret.tostring().tolocal8bit());
        return;
    }
    syslog log("system", syslog::login, qstringliteral("用户登录"),
                username,
               qstring(__file__),
               qstring(__function__),
                globalfunc::jsontostring(request.getparameterjson()),
                request.getpeeraddress().tostring(),
                request.getheader("user-agent"),
                qstringliteral("用户成功登录"));
    qstring pwdandsalt = password   loginuser.getsalt();
    qstring md5pwd = qstring(qcryptographichash::hash(pwdandsalt.tolocal8bit(), qcryptographichash::md5).tohex());
    if(md5pwd != loginuser.getpassword())
    {
        ret.failedmsg(qstringliteral("密码不正确!"));
        response.write(ret.tostring().tolocal8bit());
        log.setmemo(qstringliteral("密码不正确!"));
        m_phelper->insertentity(&log);
        return;
    }
    //jwt获取,并存入缓存
    qstring accesstoken = jwtutil::sign(username, password);
    cacheapi::instance()->insert(username   "_token", accesstoken, jwtutil::expired_time);
    //session保存账户名和登录时间
    session.set("username", username);
    session.set("logintime", qtime::currenttime());
    //返回token
    ret.setdata("access_token", accesstoken);
    responseutil::replyjson(response, ret);
    m_phelper->insertentity(&log);
}
// /logout?access_token=?
void logincontroller::logout(httprequest& request, httpresponse& response)
{
    qstring access_token = request.getparameter("access_token");
    qstring username = jwtutil::getusername(access_token);
    cacheapi::instance()->remove(username   "_token");
    qjsonobject objparam = request.getparameterjson();
    objparam.insert("access_token", "?");
//    responseutil::replyjson(response, resultjson(0, true, qstringliteral("操作成功")));
    syslog log("system", syslog::logout, qstringliteral("用户退出"),
                username,
                qstring(__file__),
                qstring(__function__),
                globalfunc::jsontostring(objparam),
                request.getpeeraddress().tostring(),
                request.getheader("user-agent"),
                qstringliteral("用户退出成功"));
    m_phelper->insertentity(&log);
}

总结 

免费资源网,https://freexyz.cn/
返回顶部
顶部
网站地图