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

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

本文整理了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:

// str param 
String value = request.param("str").value(); 
// optional str 
String value = request.param("str").value("defs"); 
// int param 
int value = request.param("some").intValue(); 
// optional int param 
Optional 
  value = request.param("some").toOptional(Integer.class); 
// list param 
List 
  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:

get("/search", req -> ); 
post("/person", req ->  
Person person = req.form(Person.class); 
}); 
} 
}

form file upload

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

post("/upload", req  -> }); 
} 
}

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

// str param 
String value = request.param("str").value(); 
// optional str 
String value = request.param("str").value("defs"); 
// int param 
int value = request.param("some").intValue(); 
// optional int param 
Optional 
  value = request.param("some").toOptional(Integer.class); 
// list param 
List 
  values = request.param("some").toList(String.class);

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

get("/search", req -> ); 
post("/person", req ->  
Person person = req.form(Person.class); 
}); 
} 
}

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

post("/upload", req  -> }); 
} 
}

代码示例

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

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

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

@Override
public void handle(final Request req, final Response rsp, final Chain chain) throws Throwable {
 String error = req.param("error").toOptional().orElse("");
 String username = req.param("username").toOptional().orElse("");
 req.set("username", username);
 req.set("error", error);
 if (loginUrl.equals(req.path())) {
  // default login form
  rsp.type(MediaType.html).send(String.format(FORM, error, callback, username));
 } else {
  super.handle(req, rsp, chain);
 }
}

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

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

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

private String template(Request req) {
 String contextPath = req.contextPath();
 return "<script>"
   + "window.LiveReloadOptions = {"
   + "host: '" + req.hostname() + "',"
   + "port: '" + req.port() + contextPath + "'"
   + "};"
   + "</script>\n"
   + "<script src=\"" + contextPath + "/livereload.js\"></script>";
}

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

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

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

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

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

@Override
public void handle(final Request req, final Response rsp) throws Throwable {
 HealthCheckRegistry registry = req.require(HealthCheckRegistry.class);
 SortedMap<String, Result> checks = req.param("name").toOptional().map(name -> {
  SortedMap<String, Result> set = ImmutableSortedMap.of(name, registry.runHealthCheck(name));
  return set;
 }).orElseGet(() -> registry.runHealthChecks());
 final Status status;
 if (checks.isEmpty()) {
  status = Status.NOT_IMPLEMENTED;
 } else {
  status = checks.values().stream()
    .filter(it -> !it.isHealthy())
    .findFirst()
    .map(it -> Status.SERVER_ERROR)
    .orElse(Status.OK);
 }
 rsp.status(status)
   .header("Cache-Control", "must-revalidate,no-cache,no-store")
   .send(checks);
}

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

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

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

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

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

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

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

@SuppressWarnings("unchecked")
@Override
public void handle(final Request req, final Response rsp) throws Throwable {
 // DON'T create a session for JWT/param/header auth (a.k.a stateless)
 Optional<Session> ifSession = req.ifSession();
 if (ifSession.isPresent()) {
  Session session = ifSession.get();
  Optional<String> profileId = session.unset(Auth.ID).toOptional();
  if (profileId.isPresent()) {
   Optional<CommonProfile> profile = req.require(AuthStore.class).unset(profileId.get());
   log.debug("logout {}", profile);
   session.destroy();
  }
 } else {
  log.debug("nothing to logout from session");
 }
 String redirectTo = req.<String> ifGet("auth.logout.redirectTo").orElse(this.redirectTo);
 rsp.redirect(redirectTo);
}

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

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

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

long timestamp = req.timestamp();
sb.append(req.ip());
sb.append(SP).append(DASH).append(SP);
sb.append(userId.apply(req));
sb.append(BL).append(df.apply(timestamp)).append(BR);
sb.append(SP);
sb.append(Q).append(req.method());
sb.append(SP);
sb.append(req.path());
if (queryString) {
 req.queryString().ifPresent(s -> sb.append(QUERY).append(s));
sb.append(req.protocol());
sb.append(Q).append(SP);
int status = ersp.status().orElse(Status.OK).value();
if (extended) {
 sb.append(SP);
 sb.append(Q).append(req.header(REFERER).value(DASH)).append(Q).append(SP);
 sb.append(Q).append(req.header(USER_AGENT).value(DASH)).append(Q);

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

@Override
 public void handle(final Request req, final Response rsp, final Route.Chain chain)
   throws Throwable {

  /**
   * Get or generate a token
   */
  Session session = req.session();
  String token = session.get(name).toOptional().orElseGet(() -> {
   String newToken = generator.apply(req);
   session.set(name, newToken);
   return newToken;
  });

  req.set(name, token);

  if (requireToken.test(req)) {
   String candidate = req.header(name).toOptional()
     .orElseGet(() -> req.param(name).toOptional().orElse(null));
   if (!token.equals(candidate)) {
    throw new Err(Status.FORBIDDEN, "Invalid Csrf token: " + candidate);
   }
  }

  chain.next(req, rsp);
 }
}

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

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

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

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

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

@Override public void handle(Request req, Response rsp, Route.Chain chain) throws Throwable {
 try {
  WebContext context = req.require(WebContext.class);
  /** 1: don't save authentication urls: */
  String existingRequestedUrl = (String) context
    .getSessionAttribute(Pac4jConstants.REQUESTED_URL);
  boolean resetRequestedUrl = excludes.stream()
    .filter(it -> !it.endsWith("/**") && req.matches(it))
    .findFirst()
    .isPresent();
  conf.getSecurityLogic()
    .perform(context, conf, new Pac4jGrantAccessAdapter(req, rsp, chain),
      conf.getHttpActionAdapter(), clients, authorizers, matchers, multiProfile);
  /** 2: don't save authentication urls: */
  if (resetRequestedUrl && req.ifSession().isPresent()) {
   //        log.info("ignoring {} by {}", ctx.g, existingRequestedUrl);
   context.setSessionAttribute(Pac4jConstants.REQUESTED_URL, existingRequestedUrl);
  }
 } catch (TechnicalException x) {
  Throwable cause = x.getCause();
  if (!(cause instanceof Err)) {
   // Pac4j wrap everything as TechnicalException, it makes stacktrace ugly, so we rethrow
   // Err
   cause = x;
  }
  throw cause;
 }
 //    }
}

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

@Override
default void handle(final Request req, final Response rsp, final Chain chain) throws Throwable {
 Sse sse = req.require(Sse.class);
 String path = req.path();
 rsp.send(new Deferred(deferred -> {
  try {
   sse.handshake(req, () -> {
    Try.run(() -> handle(req, sse))
      .onSuccess(() -> deferred.resolve(null))
      .onFailure(ex -> {
       deferred.reject(ex);
       Logger log = LoggerFactory.getLogger(Sse.class);
       log.error("execution of {} resulted in error", path, ex);
      });
   });
  } catch (Exception ex) {
   deferred.reject(ex);
  }
 }));
}

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

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

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

static Provider profileProvider(AtomicReference<Registry> registry, Class profile,
   Function<Request, UserProfile> unauthenticated) {
  return () -> {
   Request req = registry.get().require(Request.class);
   ProfileManager pm = req.require(ProfileManager.class);
   Object result = pm.getAll(req.ifSession().isPresent()).stream()
     .filter(profile::isInstance)
     .findFirst()
     .orElse(null);
   if (result == null) {
    if (unauthenticated == null) {
     throw new Err(Status.FORBIDDEN, "Not found: " + profile.getSimpleName());
    }
    result = unauthenticated.apply(req);
   }
   return result;
  };
 }
}

相关文章