本文整理汇总了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)
}
}
示例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 = {}
}
示例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 = {}
}
示例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 = {}
}
示例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)
}
}
示例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]
}
示例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")
}
}
}
}
示例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")
}
}
示例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)
}
}
示例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.
}
}
示例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
}
}
示例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)
}
}
示例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>")
}
}
示例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)
}
}
}
示例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
}
}
}
}
}