当前位置: 首页>>代码示例>>Scala>>正文


Scala HttpServletResponse类代码示例

本文整理汇总了Scala中javax.servlet.http.HttpServletResponse的典型用法代码示例。如果您正苦于以下问题:Scala HttpServletResponse类的具体用法?Scala HttpServletResponse怎么用?Scala HttpServletResponse使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了HttpServletResponse类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Scala代码示例。

示例1: HttpUtil

//设置package包名称以及导入依赖的类
package org.eck.utils

import javax.servlet.http.{HttpServletResponse, HttpServletRequest}

import com.google.gson.{JsonElement, JsonParser, JsonObject}

object HttpUtil {
  def readBody(request: HttpServletRequest): String = {
    val reader = request.getReader
    val sb = new StringBuilder
    var line = ""
    while({line = reader.readLine();  line != null}) sb.append(line)
    sb.toString
  }

  def readBodyAsJson(request: HttpServletRequest): JsonObject = {
    val parser = new JsonParser
    parser.parse(readBody(request)).getAsJsonObject
  }

  def writeJson(response: HttpServletResponse, json: JsonElement) = {
    response.addHeader("Content-Type", "application/json")
    response.getWriter.print(json.toString)
  }
} 
开发者ID:erickzanardo,项目名称:spammer,代码行数:26,代码来源:HttpUtil.scala

示例2: CacheDisablingFilter

//设置package包名称以及导入依赖的类
package mesosphere.marathon.api

import javax.servlet._
import javax.servlet.http.HttpServletResponse

class CacheDisablingFilter extends Filter {
  override def init(filterConfig: FilterConfig): Unit = {}

  override def doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {
    response match {
      case httpResponse: HttpServletResponse =>
        httpResponse.setHeader("Cache-Control", "no-cache, no-store, must-revalidate") // HTTP 1.1
        httpResponse.setHeader("Pragma", "no-cache") // HTTP 1.0
        httpResponse.setHeader("Expires", "0") // Proxies
      case _ => // ignore other responses
    }

    chain.doFilter(request, response)
  }

  override def destroy(): Unit = {}
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:23,代码来源:CacheDisablingFilter.scala

示例3: CORSFilter

//设置package包名称以及导入依赖的类
package mesosphere.marathon
package api

import javax.inject.Inject
import javax.servlet._
import javax.servlet.http.{ HttpServletRequest, HttpServletResponse }

import mesosphere.marathon.stream._

class CORSFilter @Inject() (config: MarathonConf) extends Filter {

  // Map access_control_allow_origin flag into separate headers
  lazy val maybeOrigins: Option[Seq[String]] =
    config.accessControlAllowOrigin.get.map { configValue =>
      configValue.split(",").map(_.trim)(collection.breakOut)
    }

  override def init(filterConfig: FilterConfig): Unit = {}

  override def doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {

    response match {
      case httpResponse: HttpServletResponse if maybeOrigins.isDefined =>
        request match {
          case httpRequest: HttpServletRequest =>
            maybeOrigins.foreach { origins =>
              origins.foreach { origin =>
                httpResponse.setHeader("Access-Control-Allow-Origin", origin)
              }
            }

            // Add all headers from request as accepted headers
            // Unclear why `toTraversableOnce` isn't being applied implicitly here.
            val accessControlRequestHeaders =
              toTraversableOnce(httpRequest.getHeaders("Access-Control-Request-Headers")).flatMap(_.split(","))

            httpResponse.setHeader("Access-Control-Allow-Headers", accessControlRequestHeaders.mkString(", "))

            httpResponse.setHeader("Access-Control-Allow-Methods", "GET, HEAD, OPTIONS")
            httpResponse.setHeader("Access-Control-Max-Age", "86400")
          case _ =>
        }
      case _ => // Ignore other responses
    }
    chain.doFilter(request, response)
  }

  override def destroy(): Unit = {}
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:50,代码来源:CORSFilter.scala

示例4: LimitConcurrentRequestsFilter

//设置package包名称以及导入依赖的类
package mesosphere.marathon.api

import java.util.concurrent.Semaphore
import javax.servlet._
import javax.servlet.http.HttpServletResponse


class LimitConcurrentRequestsFilter(concurrentOption: Option[Int]) extends Filter {

  val concurrent = concurrentOption.getOrElse(0)
  val semaphore = new Semaphore(concurrent)
  val filterFunction = concurrentOption.map(_ => withSemaphore _).getOrElse(pass _)

  def withSemaphore(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {
    if (semaphore.tryAcquire()) {
      try { chain.doFilter(request, response) }
      finally { semaphore.release() }
    } else {
      response match {
        case r: HttpServletResponse => r.sendError(503, s"Too many concurrent requests! Allowed: $concurrent.")
        case r: ServletResponse => throw new IllegalArgumentException(s"Expected http response but got $response")
      }
    }
  }

  def pass(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {
    chain.doFilter(request, response)
  }

  override def doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {
    filterFunction(request, response, chain)
  }

  override def init(filterConfig: FilterConfig): Unit = {}
  override def destroy(): Unit = {}
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:37,代码来源:LimitConcurrentRequestsFilter.scala

示例5: HttpEventStreamServletTest

//设置package包名称以及导入依赖的类
package mesosphere.marathon.core.event.impl.stream

import javax.servlet.http.HttpServletResponse

import akka.actor.ActorRef
import mesosphere.marathon._
import mesosphere.marathon.api.TestAuthFixture
import mesosphere.marathon.test.{ MarathonSpec, Mockito }
import org.scalatest.{ GivenWhenThen, Matchers }

class HttpEventStreamServletTest extends MarathonSpec with Matchers with Mockito with GivenWhenThen {

  test("access without authentication is denied") {
    Given("An unauthenticated request")
    val f = new Fixture
    val resource = f.streamServlet()
    val response = mock[HttpServletResponse]
    f.auth.authenticated = false

    When("we try to attach to the event stream")
    resource.doGet(f.auth.request, response)

    Then("we receive a NotAuthenticated response")
    verify(response).setStatus(f.auth.NotAuthenticatedStatus)
  }

  test("access without authorization is denied") {
    Given("An unauthorized request")
    val f = new Fixture
    val resource = f.streamServlet()
    val response = mock[HttpServletResponse]
    f.auth.authenticated = true
    f.auth.authorized = false

    When("we try to attach to the event stream")
    resource.doGet(f.auth.request, response)

    Then("we receive a Unauthorized response")
    verify(response).setStatus(f.auth.UnauthorizedStatus)
  }

  class Fixture {
    val actor = mock[ActorRef]
    val auth = new TestAuthFixture
    val config = AllConf.withTestConfig("--event_subscriber", "http_callback")
    def streamServlet() = new HttpEventStreamServlet(actor, config, auth.auth, auth.auth)
  }
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:49,代码来源:HttpEventStreamServletTest.scala

示例6: TestAuthFixture

//设置package包名称以及导入依赖的类
package mesosphere.marathon.api

import java.util.Collections
import javax.servlet.http.{ HttpServletRequest, HttpServletResponse }

import mesosphere.marathon.plugin.auth.{ Authenticator, AuthorizedAction, Authorizer, Identity }
import mesosphere.marathon.plugin.http.{ HttpRequest, HttpResponse }
import mesosphere.marathon.test.Mockito

import scala.concurrent.Future

class TestAuthFixture() extends Mockito {

  type Auth = Authenticator with Authorizer

  var identity: Identity = new Identity {}

  var authenticated: Boolean = true
  var authorized: Boolean = true
  var authFn: Any => Boolean = { _ => true }

  val UnauthorizedStatus = 401
  val NotAuthenticatedStatus = 403

  def auth: Auth = new Authorizer with Authenticator {
    override def authenticate(request: HttpRequest): Future[Option[Identity]] = {
      Future.successful(if (authenticated) Some(identity) else None)
    }
    override def handleNotAuthenticated(request: HttpRequest, response: HttpResponse): Unit = {
      response.status(NotAuthenticatedStatus)
    }
    override def handleNotAuthorized(principal: Identity, response: HttpResponse): Unit = {
      response.status(UnauthorizedStatus)
    }
    override def isAuthorized[Resource](
      principal: Identity,
      action: AuthorizedAction[Resource],
      resource: Resource): Boolean = {
      authorized && authFn(resource)
    }
  }

  var request: HttpServletRequest = {
    val req = mock[HttpServletRequest]
    req.getHeaderNames returns Collections.emptyEnumeration()
    req.getHeaders(any) returns Collections.emptyEnumeration()
    req
  }
  var response: HttpServletResponse = mock[HttpServletResponse]
} 
开发者ID:xiaozai512,项目名称:marathon,代码行数:51,代码来源:TestAuthFixture.scala

示例7: LoginController

//设置package包名称以及导入依赖的类
package co.informatica.mvc.controllers

import javax.servlet.http.{HttpServletRequest, HttpServletResponse}

import co.informatica.mvc.models.User
import co.informatica.mvc.views.LoginFormTemplate

class LoginController extends BaseController {
  override lazy val template = LoginFormTemplate

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
    super.doGet(req, resp)

    resp.setCharacterEncoding("UTF-8")
    resp.getWriter().print("<!DOCTYPE html>" + template.message())

  }

  override def doPost(req: HttpServletRequest, resp: HttpServletResponse) = {
    super.doPost(req, resp)

    val id = ""
    val name = req.getParameter("name")
    val email = req.getParameter("email")

    val user = new User(id, name, email)

    val findUser = User.find(user)

    findUser match {
      case Some(findUser) => {
        val user = findUser
        val session = req.getSession()

        session.setAttribute("id", user.id)
        session.setAttribute("name", user.name)
        session.setAttribute("email", user.email)

        println("Logged User:")
        println(user.name)
        println(user.email)

        resp.sendRedirect("/")
      }
      case None => {
        resp.sendRedirect("/login")
      }
    }

  }
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:52,代码来源:LoginController.scala

示例8: UsersController

//设置package包名称以及导入依赖的类
package co.informatica.mvc.controllers

import javax.servlet.http.{HttpServletRequest, HttpServletResponse, HttpSession}

import co.informatica.mvc.models.User
import co.informatica.mvc.views.{UserFormTemplate, UsersTemplate}

class UsersController extends BaseController {

  override lazy val template = UsersTemplate

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
    super.doGet(req, resp)

    val session: HttpSession = req.getSession(false)

    if (session != null) {
      val name = session.getAttribute("name").toString()
      resp.setCharacterEncoding("UTF-8")

      if (req.getPathInfo == null) {
        val users = User.getAll

        template.entities = Option(users)
        resp.getWriter().print("<!DOCTYPE html>" + template.message(name))
      } else if (req.getPathInfo() == "/create") {
        resp.getWriter().print("<!DOCTYPE html>" + UserFormTemplate.message(name))
      } else if (req.getPathInfo() contains "delete") {
        val oid = req.getPathInfo().substring(req.getPathInfo().lastIndexOf("/") + 1)
        User.delete(oid)

        resp.sendRedirect("/users")
      } else {
        resp.sendRedirect("/users")
      }
    } else {
      resp.sendRedirect("/login")
    }

  }

  override def doPost(req: HttpServletRequest, resp: HttpServletResponse) = {
    super.doPost(req, resp)

    val id = ""
    val name = req.getParameter("name")
    val email = req.getParameter("email")

    val user = new User(id, name, email)

    val createdUser = User.create(user)
    println("Created User:")
    println(createdUser.id)
    println(createdUser.name)
    println(createdUser.email)

    resp.sendRedirect("/users")

  }
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:61,代码来源:UsersController.scala

示例9: doGet

//设置package包名称以及导入依赖的类
package co.informatica.mvc.controllers

import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}

import co.informatica.mvc.models.Model
import co.informatica.mvc.views.BaseTemplate

trait BaseController extends HttpServlet {
  lazy val model: Model = null
  lazy val template: BaseTemplate = null

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
    println("GET: " + this.getClass.getName)
    println("getPathInfo:")
    println(req.getPathInfo())
  }

  override def doPost(req: HttpServletRequest, resp: HttpServletResponse) = {
    println("POST: " + this.getClass.getName)
  }

} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:23,代码来源:BaseController.scala

示例10: GZipServletResponseWrapper

//设置package包名称以及导入依赖的类
package co.informatica.mvc.filters

import java.io.{IOException, OutputStreamWriter, PrintWriter}
import javax.servlet.ServletOutputStream
import javax.servlet.http.{HttpServletResponse, HttpServletResponseWrapper}

class GZipServletResponseWrapper(val response: HttpServletResponse) extends HttpServletResponseWrapper(response) {
  private var gzipOutputStream: GZipServletOutputStream = null
  private var printWriter: PrintWriter = null

  def close(): Unit = { //PrintWriter.close does not throw exceptions.
    //Hence no try-catch block.
    if (this.printWriter != null) this.printWriter.close()
    if (this.gzipOutputStream != null) this.gzipOutputStream.close
  }

  override def flushBuffer(): Unit = { //PrintWriter.flush() does not throw exception
    if (this.printWriter != null) this.printWriter.flush()
    var exception1: IOException = null
    try
        if (this.gzipOutputStream != null) this.gzipOutputStream.flush
    catch {
      case e: IOException =>
        exception1 = e
    }
    var exception2: IOException = null
    try
      super.flushBuffer()
    catch {
      case e: IOException =>
        exception2 = e
    }
    if (exception1 != null) throw exception1
    if (exception2 != null) throw exception2
  }

  override def getOutputStream: ServletOutputStream = {
    if (this.printWriter != null) throw new IllegalStateException("PrintWriter obtained already - cannot get OutputStream")
    if (this.gzipOutputStream == null) this.gzipOutputStream = new GZipServletOutputStream(getResponse.getOutputStream)
    this.gzipOutputStream
  }

  override def getWriter: PrintWriter = {
    if (this.printWriter == null && this.gzipOutputStream != null) throw new IllegalStateException("OutputStream obtained already - cannot get PrintWriter")
    if (this.printWriter == null) {
      this.gzipOutputStream = new GZipServletOutputStream(getResponse.getOutputStream)
      this.printWriter = new PrintWriter(new OutputStreamWriter(this.gzipOutputStream, getResponse.getCharacterEncoding))
    }
    this.printWriter
  }

  override def setContentLength(len: Int): Unit = {
    //ignore, since content length of zipped content
    //does not match content length of unzipped content.
  }
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:57,代码来源:GZipServletResponseWrapper.scala

示例11: GZipServletFilter

//设置package包名称以及导入依赖的类
package co.informatica.mvc.filters

import java.io.IOException
import javax.servlet._
import javax.servlet.http.{HttpServletRequest, HttpServletResponse}


class GZipServletFilter extends Filter {
  @throws[ServletException]
  override def init(filterConfig: FilterConfig): Unit = {
  }

  override def destroy(): Unit = {
  }

  @throws[IOException]
  @throws[ServletException]
  override def doFilter(request: ServletRequest, response: ServletResponse, chain: FilterChain): Unit = {
    val httpRequest = request.asInstanceOf[HttpServletRequest]
    val httpResponse = response.asInstanceOf[HttpServletResponse]
    if (acceptsGZipEncoding(httpRequest)) {
      httpResponse.addHeader("Content-Encoding", "gzip")
      val gzipResponse = new GZipServletResponseWrapper(httpResponse)
      chain.doFilter(request, gzipResponse)
      gzipResponse.close
    }
    else chain.doFilter(request, response)
  }

  private def acceptsGZipEncoding(httpRequest: HttpServletRequest) = {
    val acceptEncoding = httpRequest.getHeader("Accept-Encoding")
    acceptEncoding != null && acceptEncoding.indexOf("gzip") != -1
  }
} 
开发者ID:jkevingutierrez,项目名称:MVC,代码行数:35,代码来源:GZipServletFilter.scala

示例12: Server

//设置package包名称以及导入依赖的类
package com.arangodb

import scala.beans.BeanProperty

import org.eclipse.jetty.server.Request
import org.eclipse.jetty.server.handler.AbstractHandler

import com.arangodb.Server.Movie
import com.arangodb.util.MapBuilder

import javax.servlet.http.HttpServletRequest
import javax.servlet.http.HttpServletResponse

object Server {

  private val COLLECTION_NAME = "ring_movies"

  class Handler(arangoDB: ArangoDB) extends AbstractHandler {
    override def handle(target: String,
                        req: Request,
                        httpReq: HttpServletRequest,
                        httpRes: HttpServletResponse) = {
      httpRes.setContentType("text/html")
      httpRes.setStatus(HttpServletResponse.SC_OK)
      httpRes.getWriter().println("<h1>all movies that have \"Lord.*Rings\" in their title</h1>")
      val cursor = getMovies(arangoDB)
      while (cursor.hasNext()) {
        httpRes.getWriter().println(cursor.next().title + "<br />")
      }
      req.setHandled(true)
    }
  }

  def main(args: Array[String]): Unit = {
    val arangoDB = new ArangoDB.Builder().host("arangodb-proxy.marathon.mesos").user("root").build();
    val server = new org.eclipse.jetty.server.Server(8080)
    server.setHandler(new Handler(arangoDB))
    server.start
  }

  def getMovies(arangoDB: ArangoDB): ArangoCursor[Movie] = {
    arangoDB.db().query("for doc in @@col return doc", new MapBuilder().put("@col", COLLECTION_NAME).get(), null, classOf[Movie])
  }

  case class Movie(@BeanProperty title: String) {
    def this() = this(title = null)
  }

} 
开发者ID:arangodb,项目名称:arangodb-spark-example,代码行数:50,代码来源:Server.scala

示例13: AdminServlet

//设置package包名称以及导入依赖的类
package org.eck.servlets

import java.util.logging.Logger
import javax.servlet.http.{HttpServletResponse, HttpServletRequest, HttpServlet}

import com.google.gson.JsonParser
import org.eck.entities.Settings

class AdminServlet extends HttpServlet {
  val logger = Logger.getLogger("AdminServlet")

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) = {
    if (req.getParameter("json") != null) {
      val json = new JsonParser().parse(req.getParameter("json")).getAsJsonObject
      logger.info("Updating settings data " + json.toString)
      Settings.fromJson(json)
    }

    printForm(resp)
  }

  def printForm(resp: HttpServletResponse) = {
    resp.setContentType("text/html")
    resp.getWriter.append("<form action=\"/admin\">")
    resp.getWriter.append(" <textarea name=\"json\" rows=\"30\">")
    resp.getWriter.append(Settings.asJson.toString)
    resp.getWriter.append(" </textarea>")
    resp.getWriter.append(" <br/>")
    resp.getWriter.append(" <button type=\"submit\">Save</button>")
  }
} 
开发者ID:erickzanardo,项目名称:spammer,代码行数:32,代码来源:AdminServlet.scala

示例14: PlayerServlet

//设置package包名称以及导入依赖的类
package org.leanpoker.player

import javax.servlet.annotation.WebServlet
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}

import com.google.gson.JsonParser

@WebServlet(Array("/"))
class PlayerServlet extends HttpServlet {

  override def doGet(req: HttpServletRequest, resp: HttpServletResponse) {
    resp.getWriter.print("Scala player is running")
  }

  @Override
  override def doPost(req: HttpServletRequest, resp: HttpServletResponse) {
    req.getParameter("action") match {
      case "bet_request" =>
        val gameState = req.getParameter("game_state")
        resp.getWriter.print(Player.betRequest(new JsonParser().parse(gameState)))
      case "showdown" =>
        val gameState = req.getParameter("game_state")
        Player.showdown(new JsonParser().parse(gameState))
      case _ =>
        resp.getWriter.print(Player.VERSION)
    }
  }
} 
开发者ID:wlk,项目名称:poker-player-funny-chicken,代码行数:29,代码来源:PlayerServlet.scala

示例15: doGet

//设置package包名称以及导入依赖的类
package com.clay.web.servlets

import java.io._
import java.util.ResourceBundle
import javax.activation.MimetypesFileTypeMap
import javax.servlet.ServletConfig
import javax.servlet.annotation.WebServlet
import javax.servlet.http.{HttpServlet, HttpServletRequest, HttpServletResponse}

import org.springframework.util.StreamUtils



    override def doGet(req: HttpServletRequest, response: HttpServletResponse): Unit = {
        // We only support HTTP/1.0 and HTTP/1.1
        if (!req.getProtocol.endsWith("1.0") && !req.getProtocol.endsWith("1.1")) {
            throw new BadRequestServletErrorException()
        }

        val file = new File(resourcePath + "/" + req.getPathInfo)
        if (file.isDirectory) {
            throw new UnauthorizedServletErrorException()
        }

        if (!file.exists()) {
            throw new NotFoundServletErrorException()
        }

        var in: InputStream = null
        try {
            in = new FileInputStream(file)
            response.setContentType(mimeType.getContentType(file))
            response.setContentLength(in.available())
            StreamUtils.copy(in, response.getOutputStream.asInstanceOf[OutputStream])
        } finally {
            if (in != null) {
                try {
                    in.close()
                } catch {
                    case ex: Exception => // Ignore
                }
            }
        }

    }
} 
开发者ID:guynir,项目名称:clay,代码行数:47,代码来源:ResourcesServlet.scala


注:本文中的javax.servlet.http.HttpServletResponse类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。