// GET 方式或 POST 方式且满足: // Content-Type: application/x-www-form-urlencoded bool doParams(HttpServletRequest& req, HttpServletResponse& res) { param1_ = req.getParameter("name1"); param2_ = req.getParameter("name2"); param3_ = req.getParameter("name2"); return doResponse(req, res); }
void Products::process(HttpServletRequest& request, HttpServletResponse &response) { map<string,string> params; params["category_id"]=request.getParameter("category_id"); params["s_keyword"]=request.getParameter("s_keyword"); params["price_from"]=request.getParameter("price_from"); params["price_to"]=request.getParameter("price_to"); const string WHERE = where_part(params) ; string query = "SELECT * FROM store_products" + WHERE + order_part(request.getParameter("productsOrder"), request.getParameter("productsDir")) + limit_part(request.getParameter("productsPageSize"), request.getParameter("productsPage")); products_t products = fetch(query); request.setAttribute("products", products); query = "SELECT COUNT(*) FROM store_products" + WHERE; int ResultsFound = count(query); request.setAttribute("ResultsFound", ResultsFound); int pageSize = getPageSize(request.getParameter("productsPageSize")); int pageCount = static_cast<int>( ceilf(static_cast<float>(ResultsFound)/pageSize) ); request.setAttribute("pageCount", pageCount); int currentPage = 1; string s_currentPage = request.getParameter("productsPage"); if(!s_currentPage.empty()) currentPage = lexical_cast<int>(s_currentPage); request.setAttribute("currentPage", currentPage); request.setAttribute("naviLink",make_naviLink(request)); }
void doGet(HttpServletRequest& req, HttpServletResponse &res) { res.setContentType("text/plain"); ostream& out = res.getOutputStream(); out << "pid: " << getpid() << endl << endl; string action = req.getParameter("action"); if(action == "list") { servlet::loader& loader = servlet::loader::instance(); out << "Loaded servlets(" << loader.pool.size() << "):" << endl; int cnt = 0; char timebuf[256]; for(std::map<std::string, servlet::loader::pool_entry>::const_iterator i = loader.pool.begin(); i != loader.pool.end(); ++i) { apr_rfc822_date(timebuf, i->second.atime); HttpServlet* servlet = i->second.servlet; out << ++cnt << ": " << (servlet ? typeid(*servlet).name() : "NULL") << "\t(Access: " << timebuf << ", Load: "; apr_rfc822_date(timebuf, i->second.ltime); out << timebuf << ")" << endl; } }else if(action == "load") { string path = req.getParameter("path"); servlet::loader::instance().load(path); out << "Loaded " << path << endl; }else { out << "Unknown action: " << action << endl; } }
void ProductDetails::add_to_cart(HttpServletRequest& request, HttpServletResponse &response) { HttpSession* session = request.getSession(false); if(!session) throw runtime_error("no session"); typedef vector<cart_item> shopping_cart; shopping_cart cart = session->getAttribute<shopping_cart>("cart"); cart_item item; item.quantity = boost::lexical_cast<int>(request.getParameter("quantity")); item.product = fetch(request.getParameter("product_id")); if(item.quantity <= 0) throw runtime_error("Quantity is invalid. It must be a positive number"); cart.push_back(item); session->setAttribute("cart",cart); response.sendRedirect("ShoppingCart.sxx"); }
virtual bool doPost(HttpServletRequest& req, HttpServletResponse& res) { const char* sid = req.getSession().getAttribute("sid"); if (*sid == 0) req.getSession().setAttribute("sid", "xxxxxx"); sid = req.getSession().getAttribute("sid"); const char* cookie1 = req.getCookieValue("name1"); const char* cookie2 = req.getCookieValue("name2"); // 创建 HTTP 响应头 res.addCookie("name1", "value1"); res.addCookie("name2", "value2", ".test.com", "/", 3600 * 24); // res.setStatus(400); // 可以设置返回的状态码 // 两种方式都可以设置字符集 if (0) res.setContentType("text/xml; charset=gb2312"); else { res.setContentType("text/xml"); res.setCharacterEncoding("gb2312"); } const char* param1 = req.getParameter("name1"); const char* param2 = req.getParameter("name2"); // 创建 xml 格式的数据体 xml body; body.get_root().add_child("root", true) .add_child("sessions", true) .add_child("session", true) .add_attr("sid", sid ? sid : "null") .get_parent() .get_parent() .add_child("cookies", true) .add_child("cookie", true) .add_attr("name1", cookie1 ? cookie1 : "null") .get_parent() .add_child("cookie", true) .add_attr("name2", cookie2 ? cookie2 : "null") .get_parent() .get_parent() .add_child("params", true) .add_child("param", true) .add_attr("name1", param1 ? param1 : "null") .get_parent() .add_child("param", true) .add_attr("name2", param2 ? param2 : "null"); string buf; body.build_xml(buf); // 发送 http 响应头 if (res.sendHeader() == false) return false; // 发送 http 响应体 if (res.getOutputStream().write(buf) == -1) return false; return true; }
void FormTestServlet::doGet(HttpServletRequest& req, HttpServletResponse& resp) { ServletOutputStream& ostr = resp.getOutputStream(); ostr << "<html>\n" "<head>\n" "<title>POCO Form Server Sample</title>\n" "</head>\n" "<body>\n" "<h1>POCO Form Server Sample</h1>\n" "<h2>GET Form</h2>\n" "<form method=\"GET\" action=\"/ServletTest/FormTestServlet\">\n" "<input type=\"text\" name=\"text\" size=\"31\">\n" "<input type=\"submit\" value=\"GET\">\n" "</form>\n" "<h2>POST Form</h2>\n" "<form method=\"POST\" action=\"/ServletTest/FormTestServlet\">\n" "<input type=\"text\" name=\"text\" size=\"31\">\n" "<input type=\"submit\" value=\"POST\">\n" "</form>\n"; ostr << "<h2>Request</h2><p>\n"; ostr << "Method: " << req.getMethod() << "<br>\n"; ostr << "URI: " << req.getRequestURI() << "<br>\n"; std::vector<std::string> names = req.getParameterNames(); std::vector<std::string>::iterator it = names.begin(); for(; it != names.end(); ++it) ostr << *it << ":" << req.getParameter(*it); ostr << "</p>"; ostr << "</body>\n"; }
void ProductDetails::show_product(HttpServletRequest& request, HttpServletResponse &response) { string id = request.getParameter("product_id"); if(id.empty()) throw runtime_error("ProductDetails: product_id parameter not supplyed"); Product product = fetch(id); request.setAttribute("product", product); request.getRequestDispatcher("ProductDetailsView.csp")->forward(request,response); }
void TestServlet::doGet(HttpServletRequest& req, HttpServletResponse& resp) { std::ostringstream ss(""); ss << ++_counter << ") TestServlet:" << std::endl; std::cout << ss.str() << std::endl; log(ss.str()); log("TestServlet: This is a hello from TestServlet\n"); ServletOutputStream& out = resp.getOutputStream(); ss.str(""); ss << "<html><body>Servlet access count: " << _counter; out.println(ss.str()); if("" == _sessionId) { const HttpSession* pSession = req.getSession(); if(pSession) _sessionId = pSession->getId(); } out.println("<br> Servlet Name:" + getServletName()); out.println("<br> Session Id:" + _sessionId); out.println("<hr>"); std::vector<std::string> names = getInitParameterNames(); std::vector<std::string>::iterator it = names.begin(); out.println("<ul><b>Servlet Init Parameters:</b><br>"); for(; it != names.end(); ++it) { ss.str(""); ss << "<li><b>" << *it << "</b>: " << getInitParameter(*it) << "<br>"; out.println(ss.str()); } out.println("</ul>"); names = req.getParameterNames(); out.println("<ul><b>Request Parameters:</b><br>"); it = names.begin(); for(; it != names.end(); ++it) { ss.str(""); ss << "<li><b>" << *it << "</b>:" << req.getParameter(*it) << "<br>"; out.println(ss.str()); } out.println("</ul>"); out.println("</body></html>"); }
string Products::make_naviLink(HttpServletRequest& request) { auto_ptr< vector<string> > names_ptr = request.getParameterNames(); vector<string>& names = *names_ptr; string link; for(unsigned i=0;i<names.size(); ++i) { if(names[i] == "productsPage") continue; link += link.empty()?'?':'&'; link += names[i] + "=" + request.getParameter(names[i]); } link += (link.empty()?'?':'&') + string("productsPage="); return ("Products.sxx"+link); }
void DefaultTestServlet::doGet(HttpServletRequest& req, HttpServletResponse& resp) { std::ostringstream ss(""); ss << ++_counter << ") TestServlet:" << std::endl; log(ss.str()); log("TestServlet: This is a log entry from DefaultTestServlet\n"); ServletOutputStream& out = resp.getOutputStream(); ss.str(""); std::string sessionId = req.getSession()->getId(); ss << "<html><body>Hello world #" << _counter << "<br>from servlet [" << this->getServletName() << "]<br>Session ID: [" << sessionId << ']'; out.println(ss.str()); std::vector<std::string> names = getInitParameterNames(); std::vector<std::string>::iterator it = names.begin(); out.println("<ul><b>Servlet Init Parameters:</b><br>"); for(; it != names.end(); ++it) { ss.str(""); ss << "<li><b>" << *it << "</b>: " << getInitParameter(*it) << "<br>"; out.println(ss.str()); } out.println("</ul>"); names = req.getParameterNames(); out.println("<ul><b>Request Parameters:</b><br>"); it = names.begin(); for(; it != names.end(); ++it) { ss.str(""); ss << "<li><b>" << *it << "</b>:" << req.getParameter(*it) << "<br>"; out.println(ss.str()); } out.println("</ul>"); out.println("</body></html>"); }
// POST 方式且满足: // Content-Type: multipart/form-data; boundary=xxx bool doUpload(HttpServletRequest& req, HttpServletResponse& res) { // 先获得 Content-Type 对应的 http_ctype 对象 http_mime* mime = req.getHttpMime(); if (mime == NULL) { logger_error("http_mime null"); return false; } // 获得数据体的长度 long long int len = req.getContentLength(); if (len <= 0) { logger_error("body empty"); return false; } // 获得输入流 istream& in = req.getInputStream(); char buf[8192]; int ret; bool finish = false; const char* filepath = "./var/mime_file"; ofstream out; out.open_write(filepath); // 设置原始文件存入路径 mime->set_saved_path(filepath); size_t k; // 读取 HTTP 客户端请求数据 while (len > 0) { k = (size_t) len > sizeof(buf) ? sizeof(buf) : (size_t) len; ret = in.read(buf, k, false); if (ret == -1) { logger_error("read POST data error"); return false; } out.write(buf, ret); len -= ret; // 将读得到的数据输入至解析器进行解析 if (!finish && mime->update(buf, ret) == true) finish = true; } out.close(); if (len != 0 || finish == false) logger_warn("not read all data from client"); param1_ = req.getParameter("name1"); param2_ = req.getParameter("name2"); param3_ = req.getParameter("name3"); string path; // 遍历所有的 MIME 结点,找出其中为文件结点的部分进行转储 const std::list<http_mime_node*>& nodes = mime->get_nodes(); std::list<http_mime_node*>::const_iterator cit = nodes.begin(); for (; cit != nodes.end(); ++cit) { const char* name = (*cit)->get_name(); if (name == NULL) continue; http_mime_t mime_type = (*cit)->get_mime_type(); if (mime_type == HTTP_MIME_FILE) { const char* filename = (*cit)->get_filename(); if (filename == NULL) { logger("filename null"); continue; } if (strcmp(name, "file1") == 0) file1_ = filename; else if (strcmp(name, "file2") == 0) file2_ = filename; else if (strcmp(name, "file3") == 0) file3_ = filename; // 有的浏览器(如IE)上传文件时会带着文件路径,所以 // 需要先将路径去掉 filename = acl_safe_basename(filename); #ifdef WIN32 path.format("var\\%s", filename); #else path.format("./var/%s", filename); #endif (void) (*cit)->save(path.c_str()); } } // 查找上载的某个文件并转储 const http_mime_node* node = mime->get_node("file1"); if (node && node->get_mime_type() == HTTP_MIME_FILE) { const char* ptr = node->get_filename(); if (ptr) { // 有的浏览器(如IE)上传文件时会带着文件路径,所以 // 需要先将路径去掉 ptr = acl_safe_basename(ptr); #ifdef WIN32 path.format(".\\var\\1_%s", ptr); #else path.format("./var/1_%s", ptr); #endif (void) node->save(path.c_str()); } } return doResponse(req, res); }