前言:
本篇继续在前一篇的基础上实现
之前只是实现了从sqlit数据库查询出数据,并简单显示,本篇实现一个简单的添加功能。涉及到Cutelyst无格式提交参数(get方法)
一、修改控制器源码
1.编辑src/books.h并输入以下方法:
public:
...
/**
* Create a book with the supplied title, rating, and author
*/
C_ATTR(url_create, :Local :Args(3))
void url_create(Context *c, const QString &title, const QString &rating, const QString &authorId);
Cutelyst无格式提交参数,处理url为http://localhost:3000/books/url_create
Cutelyst从URL中获取“额外的斜杠分隔信息”,并将其作为参数传入
:Args(3)表明有3个参数,通过"/"分开,3个参数分别对应到实现的函数参数上
完整的url请求为http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
2.编辑src/books.cpp,以实现插入数据库的方法
void Books::url_create(Context *c, const QString &title, const QString &rating, const QString &authorId)
{
// In addition to context, get the title, rating, &
// author_id args from the URL. Note that Cutelyst automatically
// puts extra information after the "/<controller_name>/<action_name/"
// as QStrings. The args are separated by the '/' char on the URL.
// Insert the book into it's table
QSqlQuery query = CPreparedSqlQueryThreadForDB("INSERT INTO book (title, rating) VALUES (:title, :rating)", "MyDB");
query.bindValue(":title", title);
query.bindValue(":rating", rating);
int bookId = 0;
bool error = true;
if (query.exec()) {
bookId = query.lastInsertId().toInt();
query = CPreparedSqlQueryThreadForDB("INSERT INTO book_author (book_id, author_id) VALUES (:book_id, :author_id)", "MyDB");
query.bindValue(":book_id", bookId);
query.bindValue(":author_id", authorId);
if (query.exec()) {
error = false;
}
}
// On error show the last one
if (error) {
c->stash()["error_msg"] = query.lastError().text();
}
QVariantHash book;
book["title"] = title;
book["rating"] = rating;
// Assign the Book object to the stash for display and set template
c->stash({
{"book", book},
{"template", "books/create_done.html"}
});
// Disable caching for this page
c->response()->setHeader("Cache-Control", "no-cache");
}
显式地设置了一个无缓存“Cache-Control”头,以强制使用该页面的浏览器每次都获取一个新副本
二、添加动作模板
创建root/src/books/create_done.html,并输入如下内容
{% comment %} Output information about the record that was added. First title.{% endcomment %}
<p>Added book '{{ book.title }}'.</p>
<p><a href="/books/list">Return to list</a></p>
三、编译并测试
直接编译,生成动态库,并运行服务,输出如下
可以看到又新增加了一个路径
在浏览器中访问http://localhost:3000/books/url_create/TCPIP_Illustrated_Vol-2/5/4
运行如下所示
点击Home,可以看到又多了一行数据
本测试源码下载
后记:
笔者出于好奇,多输入了几个参数,直接提示网页找不到,也就是说,参数必须完符合才行
下一篇,笔者仍然探究请求参数相关