org.jooby.Request类的使用及代码示例

x33g5p2x  于2022-01-29 转载在 其他  
字(12.6k)|赞(0)|评价(0)|浏览(364)

本文整理了Java中org.jooby.Request类的一些代码示例,展示了Request类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Request类的具体详情如下:
包路径:org.jooby.Request
类名称:Request

Request介绍

[英]Give you access at the current HTTP request in order to read parameters, headers and body. HTTP parameter and headers

Access to HTTP parameter/header is available via #param(String) and #header(String) methods. See some examples:

  1. // str param
  2. String value = request.param("str").value();
  3. // optional str
  4. String value = request.param("str").value("defs");
  5. // int param
  6. int value = request.param("some").intValue();
  7. // optional int param
  8. Optional
  9. value = request.param("some").toOptional(Integer.class);
  10. // list param
  11. List
  12. values = request.param("some").toList(String.class);

form post/multi-param request

Due that form post are treated as HTTP params you can collect all them into a Java Object via #params(Class) or #form(Class) methods:

  1. get("/search", req -> );
  2. post("/person", req ->
  3. Person person = req.form(Person.class);
  4. });
  5. }
  6. }

form file upload

Form post file upload are available via #files(String) or #file(String) methods:

  1. post("/upload", req -> });
  2. }
  3. }

[中]允许您在当前HTTP请求下访问,以便读取参数、头和正文。HTTP参数和头
可以通过#param(String)和#header(String)方法访问HTTP参数/头。参见一些例子:

  1. // str param
  2. String value = request.param("str").value();
  3. // optional str
  4. String value = request.param("str").value("defs");
  5. // int param
  6. int value = request.param("some").intValue();
  7. // optional int param
  8. Optional
  9. value = request.param("some").toOptional(Integer.class);
  10. // list param
  11. List
  12. values = request.param("some").toList(String.class);

表单post/多参数请求
由于form post被视为HTTP参数,您可以通过#params(类)或#form(类)方法将它们收集到Java对象中:

  1. get("/search", req -> );
  2. post("/person", req ->
  3. Person person = req.form(Person.class);
  4. });
  5. }
  6. }

表单文件上传
表单post文件上传可通过#文件(字符串)或#文件(字符串)方法进行:

  1. post("/upload", req -> });
  2. }
  3. }

代码示例

代码示例来源:origin: jooby-project/jooby

  1. @Override
  2. public <T> T require(final Class<T> type) {
  3. return req.require(type);
  4. }

代码示例来源:origin: jooby-project/jooby

  1. @Override
  2. public void handle(final Request req, final Response rsp, final Chain chain) throws Throwable {
  3. String error = req.param("error").toOptional().orElse("");
  4. String username = req.param("username").toOptional().orElse("");
  5. req.set("username", username);
  6. req.set("error", error);
  7. if (loginUrl.equals(req.path())) {
  8. // default login form
  9. rsp.type(MediaType.html).send(String.format(FORM, error, callback, username));
  10. } else {
  11. super.handle(req, rsp, chain);
  12. }
  13. }

代码示例来源:origin: jooby-project/jooby

  1. @Override
  2. public String getFullRequestURL() {
  3. String query = req.queryString().map(it -> "?" + it).orElse("");
  4. return getScheme() + "://" + getServerName() + ":" + getServerPort() + req.contextPath() + req
  5. .path() + query;
  6. }

代码示例来源:origin: jooby-project/jooby

  1. private String template(Request req) {
  2. String contextPath = req.contextPath();
  3. return "<script>"
  4. + "window.LiveReloadOptions = {"
  5. + "host: '" + req.hostname() + "',"
  6. + "port: '" + req.port() + contextPath + "'"
  7. + "};"
  8. + "</script>\n"
  9. + "<script src=\"" + contextPath + "/livereload.js\"></script>";
  10. }

代码示例来源:origin: jooby-project/jooby

  1. protected void handshake(final Request req, final Runnable handler) throws Exception {
  2. this.injector = req.require(Injector.class);
  3. this.renderers = ImmutableList.copyOf(injector.getInstance(Renderer.KEY));
  4. this.produces = req.route().produces();
  5. this.locals = req.attributes();
  6. this.lastEventId = req.header("Last-Event-ID");
  7. this.locale = req.locale();
  8. handshake(handler);
  9. }

代码示例来源:origin: jooby-project/jooby

  1. @SuppressWarnings({"unchecked"})
  2. @Override
  3. public void handle(final Request req, final Response rsp) throws Throwable {
  4. Clients clients = req.require(Clients.class);
  5. String clientName = req.param(clients.getClientNameParameter()).value(this.clientName);
  6. WebContext ctx = req.require(WebContext.class);
  7. ClientFinder finder = req.require(ClientFinder.class);
  8. AuthStore<CommonProfile> store = req.require(AuthStore.class);
  9. log.debug("profile: {}", identity);
  10. if (identity != null) {
  11. req.set(Auth.ID, identity.getId());
  12. req.set(Auth.CNAME, client.getName());
  13. store.set(identity);
  14. String queryString = req.queryString().map(it -> "?" + it).orElse("");
  15. final String requestedUrl = req.path() + queryString;
  16. log.debug("requestedUrl: {}", requestedUrl);
  17. ctx.setSessionAttribute(Pac4jConstants.REQUESTED_URL, requestedUrl);

代码示例来源:origin: jooby-project/jooby

  1. @Override
  2. public void handle(final Request req, final Response rsp) throws Throwable {
  3. HealthCheckRegistry registry = req.require(HealthCheckRegistry.class);
  4. SortedMap<String, Result> checks = req.param("name").toOptional().map(name -> {
  5. SortedMap<String, Result> set = ImmutableSortedMap.of(name, registry.runHealthCheck(name));
  6. return set;
  7. }).orElseGet(() -> registry.runHealthChecks());
  8. final Status status;
  9. if (checks.isEmpty()) {
  10. status = Status.NOT_IMPLEMENTED;
  11. } else {
  12. status = checks.values().stream()
  13. .filter(it -> !it.isHealthy())
  14. .findFirst()
  15. .map(it -> Status.SERVER_ERROR)
  16. .orElse(Status.OK);
  17. }
  18. rsp.status(status)
  19. .header("Cache-Control", "must-revalidate,no-cache,no-store")
  20. .send(checks);
  21. }

代码示例来源:origin: jooby-project/jooby

  1. @Override
  2. public void handle(final Request req, final Response rsp, final Err ex) throws Throwable {
  3. log.error("execution of: {}{} resulted in exception\nRoute:\n{}\n\nStacktrace:",
  4. req.method(), req.path(), req.route().print(6), ex);
  5. Config conf = req.require(Config.class);
  6. boolean stackstrace = Try.apply(() -> conf.getBoolean("err.stacktrace"))
  7. .orElse(req.require(Env.class).name().equals("dev"));
  8. rsp.send(
  9. Results
  10. .when(MediaType.html, () -> Results.html(VIEW).put("err", ex.toMap(stackstrace)))
  11. .when(MediaType.all, () -> ex.toMap(stackstrace)));
  12. }

代码示例来源:origin: jooby-project/jooby

  1. Swagger base = Json.mapper().convertValue(hash, Swagger.class);
  2. Swagger swagger = new SwaggerBuilder(options.tagger)
  3. .build(base, provider.apply(req.require(M)));
  4. boolean json = req.path().endsWith(".json");
  5. if (configurer != null) {
  6. configurer.accept(swagger);
  7. boolean json = req.path().endsWith(".json");
  8. if (json) {
  9. return Results.json(Json.mapper().writer().writeValueAsBytes(swagger));
  10. String page = Optional.ofNullable(req.param("theme").value(options.theme))
  11. .map(theme -> index.replace("<style>", "<link rel=\"stylesheet\" "
  12. + "type=\"text/css\" href=\"" + fullStaticPath + "theme-" + theme.toLowerCase()

代码示例来源:origin: jooby-project/jooby

  1. if (req.accepts(MediaType.html).isPresent()) {
  2. Route route = req.route();
  3. ImmutableMap.Builder<String, Object> map = ImmutableMap.builder();
  4. return map
  5. }));
  6. envdata.put("request params", dump(() -> req.params().toMap()));
  7. req.ifSession().ifPresent(s -> envdata.put("session", dump(s::attributes)));
  8. req.method(), req.path(), req.route().print(6), err);
  9. rsp.type(MediaType.html).send(writer.toString());

代码示例来源:origin: jooby-project/jooby

  1. @SuppressWarnings("unchecked")
  2. @Override
  3. public void handle(final Request req, final Response rsp) throws Throwable {
  4. // DON'T create a session for JWT/param/header auth (a.k.a stateless)
  5. Optional<Session> ifSession = req.ifSession();
  6. if (ifSession.isPresent()) {
  7. Session session = ifSession.get();
  8. Optional<String> profileId = session.unset(Auth.ID).toOptional();
  9. if (profileId.isPresent()) {
  10. Optional<CommonProfile> profile = req.require(AuthStore.class).unset(profileId.get());
  11. log.debug("logout {}", profile);
  12. session.destroy();
  13. }
  14. } else {
  15. log.debug("nothing to logout from session");
  16. }
  17. String redirectTo = req.<String> ifGet("auth.logout.redirectTo").orElse(this.redirectTo);
  18. rsp.redirect(redirectTo);
  19. }

代码示例来源:origin: jooby-project/jooby

  1. static void install(final Env env, final Config conf) {
  2. String path = conf.getString("crash.httpshell.path");
  3. Router router = env.router();
  4. router.get(path + "/{cmd:.*}", router.promise("direct", (req, deferred) -> {
  5. MediaType type = req.accepts(MediaType.json)
  6. .map(it -> MediaType.json)
  7. .orElse(MediaType.html);
  8. PluginContext ctx = req.require(PluginContext.class);
  9. ShellFactory shellFactory = ctx.getPlugin(ShellFactory.class);
  10. Shell shell = shellFactory.create(null);
  11. String cmd = req.param("cmd").value().replaceAll("/", " ");
  12. ShellProcess process = shell.createProcess(cmd);
  13. ShellProcessContext spc = new SimpleProcessContext(
  14. result -> deferred.resolve(result.type(type)));
  15. process.execute(spc);
  16. }));
  17. }

代码示例来源:origin: jooby-project/jooby

  1. long timestamp = req.timestamp();
  2. sb.append(req.ip());
  3. sb.append(SP).append(DASH).append(SP);
  4. sb.append(userId.apply(req));
  5. sb.append(BL).append(df.apply(timestamp)).append(BR);
  6. sb.append(SP);
  7. sb.append(Q).append(req.method());
  8. sb.append(SP);
  9. sb.append(req.path());
  10. if (queryString) {
  11. req.queryString().ifPresent(s -> sb.append(QUERY).append(s));
  12. sb.append(req.protocol());
  13. sb.append(Q).append(SP);
  14. int status = ersp.status().orElse(Status.OK).value();
  15. if (extended) {
  16. sb.append(SP);
  17. sb.append(Q).append(req.header(REFERER).value(DASH)).append(Q).append(SP);
  18. sb.append(Q).append(req.header(USER_AGENT).value(DASH)).append(Q);

代码示例来源:origin: jooby-project/jooby

  1. @Override
  2. public void handle(final Request req, final Response rsp, final Route.Chain chain)
  3. throws Throwable {
  4. /**
  5. * Get or generate a token
  6. */
  7. Session session = req.session();
  8. String token = session.get(name).toOptional().orElseGet(() -> {
  9. String newToken = generator.apply(req);
  10. session.set(name, newToken);
  11. return newToken;
  12. });
  13. req.set(name, token);
  14. if (requireToken.test(req)) {
  15. String candidate = req.header(name).toOptional()
  16. .orElseGet(() -> req.param(name).toOptional().orElse(null));
  17. if (!token.equals(candidate)) {
  18. throw new Err(Status.FORBIDDEN, "Invalid Csrf token: " + candidate);
  19. }
  20. }
  21. chain.next(req, rsp);
  22. }
  23. }

代码示例来源:origin: jooby-project/jooby

  1. @Override
  2. public Request set(final Key<?> key, final Object value) {
  3. req.set(key, value);
  4. return this;
  5. }

代码示例来源:origin: jooby-project/jooby

  1. @Override
  2. public void handle(final Request req, final Response rsp) throws Throwable {
  3. String error = req.param("error").value("");
  4. String username = req.param("username").value("");
  5. req.set("username", username);
  6. req.set("error", error);
  7. // default login form
  8. rsp.type(MediaType.html).send(String.format(FORM, error, callback, username));
  9. }

代码示例来源:origin: jooby-project/jooby

  1. @Override public void handle(Request req, Response rsp, Route.Chain chain) throws Throwable {
  2. try {
  3. WebContext context = req.require(WebContext.class);
  4. /** 1: don't save authentication urls: */
  5. String existingRequestedUrl = (String) context
  6. .getSessionAttribute(Pac4jConstants.REQUESTED_URL);
  7. boolean resetRequestedUrl = excludes.stream()
  8. .filter(it -> !it.endsWith("/**") && req.matches(it))
  9. .findFirst()
  10. .isPresent();
  11. conf.getSecurityLogic()
  12. .perform(context, conf, new Pac4jGrantAccessAdapter(req, rsp, chain),
  13. conf.getHttpActionAdapter(), clients, authorizers, matchers, multiProfile);
  14. /** 2: don't save authentication urls: */
  15. if (resetRequestedUrl && req.ifSession().isPresent()) {
  16. // log.info("ignoring {} by {}", ctx.g, existingRequestedUrl);
  17. context.setSessionAttribute(Pac4jConstants.REQUESTED_URL, existingRequestedUrl);
  18. }
  19. } catch (TechnicalException x) {
  20. Throwable cause = x.getCause();
  21. if (!(cause instanceof Err)) {
  22. // Pac4j wrap everything as TechnicalException, it makes stacktrace ugly, so we rethrow
  23. // Err
  24. cause = x;
  25. }
  26. throw cause;
  27. }
  28. // }
  29. }

代码示例来源:origin: jooby-project/jooby

  1. @Override
  2. default void handle(final Request req, final Response rsp, final Chain chain) throws Throwable {
  3. Sse sse = req.require(Sse.class);
  4. String path = req.path();
  5. rsp.send(new Deferred(deferred -> {
  6. try {
  7. sse.handshake(req, () -> {
  8. Try.run(() -> handle(req, sse))
  9. .onSuccess(() -> deferred.resolve(null))
  10. .onFailure(ex -> {
  11. deferred.reject(ex);
  12. Logger log = LoggerFactory.getLogger(Sse.class);
  13. log.error("execution of {} resulted in error", path, ex);
  14. });
  15. });
  16. } catch (Exception ex) {
  17. deferred.reject(ex);
  18. }
  19. }));
  20. }

代码示例来源:origin: jooby-project/jooby

  1. @Override public void handle(Request req, Response rsp) {
  2. WebContext context = req.require(WebContext.class);
  3. String redirectTo = req.<String>ifGet("pac4j.logout.redirectTo").orElse(defaultUrl);
  4. conf.getLogoutLogic()
  5. .perform(context, conf, conf.getHttpActionAdapter(), redirectTo, logoutUrlPattern,
  6. localLogout, destroySession, centralLogout);
  7. }
  8. }

代码示例来源:origin: jooby-project/jooby

  1. static Provider profileProvider(AtomicReference<Registry> registry, Class profile,
  2. Function<Request, UserProfile> unauthenticated) {
  3. return () -> {
  4. Request req = registry.get().require(Request.class);
  5. ProfileManager pm = req.require(ProfileManager.class);
  6. Object result = pm.getAll(req.ifSession().isPresent()).stream()
  7. .filter(profile::isInstance)
  8. .findFirst()
  9. .orElse(null);
  10. if (result == null) {
  11. if (unauthenticated == null) {
  12. throw new Err(Status.FORBIDDEN, "Not found: " + profile.getSimpleName());
  13. }
  14. result = unauthenticated.apply(req);
  15. }
  16. return result;
  17. };
  18. }
  19. }

相关文章