時(shí)間:2023-07-09 23:27:01 | 來(lái)源:網(wǎng)站運(yùn)營(yíng)
時(shí)間:2023-07-09 23:27:01 來(lái)源:網(wǎng)站運(yùn)營(yíng)
C++ Web服務(wù)器 - 用戶登錄(三):#pragma once#include "network/http/http_controller.h"class user_ctl :public network::http::controller{public: // 登錄 network::http::response_type login(); // 退出登錄 network::http::response_type outlogin(); // 取個(gè)人資料 network::http::response_type get_info();};
新建 src/user_ctl.cpp#include "user_ctl.h"#include "util/json.h"#include "mysql/mysql_plus.h"#include "public/environment.h"#include "define.h"network::http::response_type user_ctl::get_info(){ auto session = request()->session("cppsession"); newobj::json rep; rep["username"] = (*session)["username"].to<nstring>(); rep["sex"] = (*session)["sex"].to<bool>(); rep["age"] = (*session)["age"].to<int32>(); response()->send(rep); return RT_OK;}network::http::response_type user_ctl::login(){ nstring username = request()->parser()->json()["username"].to<nstring>(); nstring password = request()->parser()->json()["password"].to<nstring>(); // 回復(fù)JSON newobj::json rep; // 查詢(xún)是否已登錄 auto session = request()->session("cppsession"); if((*session)["username"].to<nstring>().empty() == false){ rep["result"] = true; rep["msg"] = "已登錄"; response()->send(rep); return RT_OK; } // 獲取可自動(dòng)釋放的MYSQL連接 conn_autofree<mysql_plus::conn> conn(MYSQL_POOL->get()); auto ppst = conn->setsql("SELECT id,sex,age FROM users WHERE username = ? and password = ? LIMIT 1"); ppst->set_string(1,username); ppst->set_string(2,password); auto result = ppst->query(); if(result->row_count() == 0){ // 沒(méi)有記錄,則賬號(hào)密碼錯(cuò)誤 rep["result"] = false; rep["msg"] = "賬號(hào)或密碼錯(cuò)誤"; response()->send(rep); return RT_OK; } result->next(); // 找到記錄,賬號(hào)密碼正確,登錄成功 // // 寫(xiě)入session (*session)["username"] = username; (*session)["age"] = result->get_int32("age"); (*session)["sex"] = result->get_boolean("sex"); rep["result"] = true; rep["msg"] = "登錄成功"; response()->send(rep); return RT_OK;}network::http::response_type user_ctl::outlogin(){ auto session = request()->session("cppsession"); session->destory(); response()->send((nstring)"已注銷(xiāo)"); return RT_OK;}
新建 www/index.html<html> <head> <meta charset="utf-8"> </head> <body> <h1>賬號(hào):</h1> <input id="username" type="text" /> <h1>密碼:</h1> <input id="password" type="text" /> <br> <input id="login" type="button" value="登錄" /> <input id="outlogin" type="button" value="注銷(xiāo)" /> <input id="get_info" type="button" value="獲取資料" /> <script src="jquery.min.js"></script> <script> $(document).ready(function(){ $("#outlogin").click(function(){ $.ajax({ type: "get", url: "/user/outlogin", success: function(data, status) { alert(data.msg) } }) }) $("#login").click(function(){ var data = {}; data.username = $("#username").val(); data.password = $("#password").val(); $.ajax({ type: "post", url: "/user/login", contentType: "application/json", data: JSON.stringify(data), dataType: "json", success: function(data, status) { alert(data.msg) } }) }) $("#get_info").click(function(){ var data = {}; $.ajax({ type: "get", url: "/user/get_info", dataType: "json", success: function(data, status) { alert(JSON.stringify(data)) } }) }) }) </script> </body></html>
main.cpp#include <iostream>#include <regex>#include "public/environment.h"#include "util/system.h"#include "util/time.h"#include "network/http/http_client_plus.h"#include "network/http/http_center.h"#include "network/http/http_request.h"#include "network/http/http_response.h"#include "network/http/http_reqpack.h"#include "network/http/http_router.h"#include "network/http/http_interceptor.h"#include "network/http/http_website.h"#include "user_ctl.h"#include <tuple>#include "define.h"#include "mysql/mysql_plus.h"int main(){ // 配置文件 newobj::json config; config.parse_file("./res/config.json"); /*初始化MYSQL連接池*/ { mysql_plus::mysql_conn_info info; // JSON配置寫(xiě)入結(jié)構(gòu)體 info.charset = "utf8mb4"; info.database = config["mysql"]["database"].to<nstring>(); info.ipaddress = config["mysql"]["ipaddress"].to<nstring>(); info.password = config["mysql"]["password"].to<nstring>(); info.username = config["mysql"]["username"].to<nstring>(); info.port = config["mysql"]["port"].to<uint32>(); // 創(chuàng)建連接池指針 mysql_plus::pool* pool = new mysql_plus::pool(); if(pool->start(info,10/*連接最大數(shù)量*/) == false){ newobj::log->fatal(pool->last_error()); return 0; } // 設(shè)置為全局環(huán)境變量 newobj::env->set<mysql_plus::pool>("mysql_pool",pool); } // 創(chuàng)建控制中心 auto center = new network::http::center; center->create(config); // 通過(guò)域名獲取 website 站點(diǎn)對(duì)象指針 auto website = center->website("0.0.0.0"); /************************ 添加控制器/攔截器/靜態(tài)文件處理 **********************************/ // 獲取路由 auto router = website->router(); // 獲取攔截器 auto interceptor = router->interceptor(); // 攔截所有 /user/ 目錄下請(qǐng)求,該目錄為管理器權(quán)限 interceptor->add("/user/.*",[](network::http::reqpack* reqpack/*請(qǐng)求包*/)->bool{ auto session = reqpack->request()->session("cppsession"); std::cout<<session->session_id().c_str()<<std::endl; if(session->session_id().empty()){ session->init(""); reqpack->response()->headers()->emplace("Set-Cookie","cppsession="+session->session_id()); } // 判斷是否為登錄請(qǐng)求,登錄請(qǐng)求不用攔截。 if(reqpack->filepath() == "/user/login"){ return true; } if(reqpack->filepath() == "/user/outlogin"){ return true; } if((*session)["username"].to<nstring>().empty()){ reqpack->response()->send((nstring)"Please Login"); // 未登錄 return false; } // 已登錄 return true; }); // 增加請(qǐng)求處理 (lamaba 方式) router->subscribe("/hello",network::http::GET,[](network::http::request* request,network::http::response* response){ // 發(fā)送 文本 response->send((nstring)"<h1>Hello!,This is newobj Web Server</h1>"); }); // 其它處理 router->other([](network::http::request* request,network::http::response* response){ auto filepath = request->filepath(); if(filepath == "/") filepath = "/index.html"; if(response->send_file(filepath) == false){ response->send((nstring)"404",404,"Not Found"); } return; }); // 增加請(qǐng)求處理集 (對(duì)象方式) SUBSCRIBE(router,user_ctl,get_info,"/user/get_info",network::http::GET); SUBSCRIBE(router,user_ctl,outlogin,"/user/outlogin",network::http::GET); SUBSCRIBE(router,user_ctl,login,"/user/login",network::http::POST); // 啟動(dòng)控制中心 if (center->start() == false) { newobj::log->fatal(center->last_error()); return 0; } newobj::log->info("start success"); while (true) { system::sleep_msec(1000); } return 0;}
config.json{ "website":[ { "host":[ { "host":"0.0.0.0:6699", "ssl":false } ], "router":{ "threadpool":{ "queuemax":10000, "size":5 } }, "rootdir":"/home/ubuntu/project/webserver/www" } ], "mysql":{ "ipaddress":"127.0.0.1", "password":"xeMjCwGLKsdwT6A7", "port":3306, "username":"blog", "database":"blog" }}
最終效果如上,實(shí)現(xiàn)登錄、獲取信息、注銷(xiāo)登錄三部操作,屏幕前的你可以嘗試補(bǔ)全更新資料功能哦~關(guān)鍵詞:用戶,服務(wù)
客戶&案例
營(yíng)銷(xiāo)資訊
關(guān)于我們
客戶&案例
營(yíng)銷(xiāo)資訊
關(guān)于我們
微信公眾號(hào)
版權(quán)所有? 億企邦 1997-2025 保留一切法律許可權(quán)利。