Java Code Examples for javax.servlet.http.HttpServletResponse.getWriter()

The following are Jave code examples for showing how to use getWriter() of the javax.servlet.http.HttpServletResponse class. You can vote up the examples you like. Your votes will be used in our system to get more good examples.
+ Save this method
Example 1
Project: urule   File: PackageServletHandler.java   View Source Code Vote up 6 votes
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String method=retriveMethod(req);
	if(method!=null){
		invokeMethod(method, req, resp);
	}else{
		VelocityContext context = new VelocityContext();
		context.put("contextPath", req.getContextPath());
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		Template template=ve.getTemplate("html/package-editor.html","utf-8");
		PrintWriter writer=resp.getWriter();
		template.merge(context, writer);
		writer.close();
	}
}
 
Example 2
Project: hockey-game   File: CustomBasicAuthenticationEntryPoint.java   View Source Code Vote up 6 votes
@Override
public void commence(final HttpServletRequest request, final HttpServletResponse response, final AuthenticationException authException) throws IOException, ServletException {

	// Authentication failed, send error response.
	response.setStatus(HttpServletResponse.SC_UNAUTHORIZED);
	response.addHeader("WWW-Authenticate", "Basic realm=" + getRealmName() + "");

	PrintWriter writer = response.getWriter();
	writer.println("HTTP Status 401 : " + authException.getMessage());
}
 
Example 3
Project: Servlet_Applet_Communication   File: LoginServlet.java   View Source Code Vote up 6 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
    PrintWriter out = response.getWriter();

    String uname = request.getParameter("uname");
       String upwd = request.getParameter("upwd");

    if(uname.equals("root") && upwd.equals("root")) {
        out.println("Login Success"); 
        }else {
      out.println("Login Failure");
    }
}
 
Example 4
Project: oscm   File: NotificationServlet.java   View Source Code Vote up 6 votes
/**
 * Displays some error output in the HTML response.
 */
private void printError(final String locale, HttpServletResponse resp,
        String errorText) throws IOException {
    resp.setCharacterEncoding("UTF-8");
    resp.setContentType("text/html; charset=UTF-8");

    String title = Messages.get(locale, "servlet_notification_title");
    String error = Messages.get(locale, "servlet_notification_error",
            new Object[] { errorText });

    String html = Messages.get(locale, "servlet_notification_html",
            new Object[] { title, title, error });
    PrintWriter out = resp.getWriter();

    out.println(html);
    out.close();
}
 
Example 5
Project: TITAN   File: LoginInterceptor.java   View Source Code Vote up 6 votes
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response,Object arg2) throws Exception {
	//1、获取请求的参数
	String requestUrl = request.getServletPath(); 
	String ticket = CookieUtil.getCookieValueByName(request,TitanConstant.TICKET_PREFIX);
	//2、验证url
	if((null != uncheckUrls) && (0 < uncheckUrls.size()) && (uncheckUrls.contains(requestUrl))){
		return true;
	}else{
		 //3、验证ticket
		String ticketInRedis = jedisCluster.get(TitanConstant.TICKET_PREFIX + ticket);
		if(StringUtils.isBlank(ticket) || StringUtils.isBlank(ticketInRedis)) {
			logger.warn("登录拦截,requestUrl:{},ticket:{},ticketInRedis:{}",requestUrl,ticket,ticketInRedis);
			PrintWriter out = response.getWriter();  
	        out.println("<html>");      
	        out.println("<script>");      
	        out.println("window.open ('"+request.getContextPath()+"/login.html','_top')");      
	        out.println("</script>");      
	        out.println("</html>"); 
		}else {
			return true;
		}
	}
	return false;
}
 
Example 6
Project: xxpay-master   File: Notify4AliPayController.java   View Source Code Vote up 6 votes
/**
 * 支付宝移动支付后台通知响应
 * @param request
 * @param response
 * @return
 * @throws ServletException
 * @throws IOException
    */
@RequestMapping(value = "/pay/aliPayNotifyRes.htm")
public void aliPayNotifyRes(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	String result =  doAliPayRes(request, response);
	if(result != null) {
		_log.info("alipay notify response: {}", result);
		response.setContentType("text/html");
		PrintWriter pw;
		try {
			pw = response.getWriter();
			pw.print(result);

		} catch (IOException e) {
			_log.error("Pay response write exception.", e);
		}
	}

}
 
Example 7
Project: hotelbook-JavaWeb   File: QueryOrderInfoServlet.java   View Source Code Vote up 6 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws IOException {

        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=utf-8");
        PrintWriter out = response.getWriter();

        // 获取值
        String orderId = request.getParameter("orderId");

        OrderInfo orderInfo = new OrderInfoServiceImpl().query(orderId);

        OrderToTable toTable = new OrderToTable(orderInfo.getOrderId(), orderInfo.getOrderName(), orderInfo.getOrderPhone()
                , orderInfo.getOrderIDcard(), orderInfo.getArrireDate(), orderInfo.getLeaveDate()
                , new RoomTypeServiceImpl().query(orderInfo.getTypeId().getTypeId()).getTypeId()
                , orderInfo.getCheckNum(), orderInfo.getPrice(), orderInfo.getCheckPrice()
                , orderInfo.getDiscount(), orderInfo.getDiscountReason(), orderInfo.getAddBed()
                , orderInfo.getAddBedPrice(), orderInfo.getOrderMoney(), orderInfo.getOrderState()
                , orderInfo.getRemark(), orderInfo.getOperatorId().getLoginName());

        Gson gson = new Gson();
        out.print(gson.toJson(toTable));
    }
 
Example 8
Project: urule   File: DecisionTreeEditorServletHandler.java   View Source Code Vote up 6 votes
@Override
public void execute(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
	String method=retriveMethod(req);
	if(method!=null){
		invokeMethod(method, req, resp);
	}else{
		VelocityContext context = new VelocityContext();
		context.put("contextPath", req.getContextPath());
		String file=req.getParameter("file");
		String project = buildProjectNameFromFile(file);
		if(project!=null){
			context.put("project", project);
		}
		resp.setContentType("text/html");
		resp.setCharacterEncoding("utf-8");
		Template template=ve.getTemplate("html/decisiontree-editor.html","utf-8");
		PrintWriter writer=resp.getWriter();
		template.merge(context, writer);
		writer.close();
	}
}
 
Example 9
Project: openNaEF   File: DifferenceServlet.java   View Source Code Vote up 6 votes
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    log.info("ip[" + req.getRemoteAddr() + "] requestURL[" + req.getRequestURL() + "] Query["
            + req.getQueryString() + "]");

    try {
        flow.execute(getServletContext(), req, resp);
    } catch (Exception e) {
        log.error("flow execution error", e);
        resp.setContentType("text/plane; charset=UTF-8");
        resp.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
        PrintWriter pw = resp.getWriter();
        pw.println(e.getMessage());
        pw.close();
    }
}
 
Example 10
Project: bdf2   File: LoadProcessController.java   View Source Code Vote up 6 votes
@Override
protected ModelAndView doHandleRequest(HttpServletRequest request,
		HttpServletResponse response) throws Exception {
	String lobId=request.getParameter("lobId");
	String xml=lobStoreService.getString(lobId);
	response.setContentType("text/plain; charset=UTF-8");
	response.setHeader("Pragma", "No-cache");
       response.setHeader("Cache-Control", "no-cache");
       response.setDateHeader("Expires", 0);
       PrintWriter writer=response.getWriter();
       xml=(xml==null)?"":xml;
       writer.write(xml);
       writer.flush();
       writer.close();
	return null;
}
 
Example 11
Project: bulbasaur   File: DTSController.java   View Source Code Vote up 5 votes
@Override
public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
	StringBuilder result = new StringBuilder();
	ScheduleMachine m = scheduleMachineFactory.newInstance(String.valueOf(System.currentTimeMillis()), "dtstest");
	m.addContext("goto", 2);
	m.addContext("_i", 3);
	m.run();

	response.setContentType("text/html;charset=utf-8");
	PrintWriter out = response.getWriter();
	out.println(result);
	return null;
}
 
Example 12
Project: spring-boot-start-current   File: JwtAuthenticationEntryPoint.java   View Source Code Vote up 5 votes
@Override
public void commence ( HttpServletRequest request ,
					   HttpServletResponse response ,
					   AuthenticationException authException ) throws IOException {
	response.setHeader( "Content-type" , MediaType.APPLICATION_JSON_UTF8_VALUE );
	response.setCharacterEncoding( StandardCharsets.UTF_8.displayName() );
	try ( PrintWriter out = response.getWriter() ) {
		out.print( JsonUtils.toCustomizationJson( ResponseEntityPro.unauthorized( "未经授权:身份验证令牌丢失或无效。" ) ) );
	}
}
 
Example 13
Project: cas-5.1.0   File: SamlMetadataController.java   View Source Code Vote up 5 votes
/**
 * Displays the identity provider metadata.
 * Checks to make sure metadata exists, and if not, generates it first.
 *
 * @param response servlet response
 * @throws IOException the iO exception
 */
@GetMapping(path = SamlIdPConstants.ENDPOINT_IDP_METADATA)
public void generateMetadataForIdp(final HttpServletResponse response) throws IOException {
    final File metadataFile = this.metadataAndCertificatesGenerationService.performGenerationSteps();
    final String contents = FileUtils.readFileToString(metadataFile, StandardCharsets.UTF_8);
    response.setContentType(CONTENT_TYPE);
    response.setStatus(HttpServletResponse.SC_OK);
    try (PrintWriter writer = response.getWriter()) {
        LOGGER.debug("Producing metadata for the response");
        writer.write(contents);
        writer.flush();
    }
}
 
Example 14
Project: spring-boot-start-current   File: DefaultInjectionAttackHandler.java   View Source Code Vote up 5 votes
@Override
public void attackHandle ( HttpServletRequest request , HttpServletResponse response , String parameters ) throws
                                                                                                           IOException {
    response.setHeader( "Content-type" , MediaType.APPLICATION_JSON_UTF8_VALUE );
    response.setCharacterEncoding( StandardCharsets.UTF_8.displayName() );
    try ( PrintWriter out = response.getWriter() ) {
        out.print( JsonUtils.toCustomizationJson( ResponseEntityPro.badRequest( "请求内容包含非法字符,原请求内容:\n" + parameters ) ) );
    }
}
 
Example 15
Project: logistimo-web-service   File: CreateEntityServlet.java   View Source Code Vote up 4 votes
private void saveManagedEntitiesOrdering(HttpServletRequest req, HttpServletResponse resp,
                                         EntitiesService as, ResourceBundle backendMessages,
                                         ResourceBundle messages) throws IOException {
  xLogger.fine("Entering saveManagedEntitiesOrdering");
  String userId = req.getParameter(USERID);
  if (userId == null || userId.isEmpty()) {
    xLogger.severe("Invalid, null or empty userId. {0}", userId);
    return;
  }
  String routeQueryString = req.getParameter("routequerystring");
  if (routeQueryString == null || routeQueryString.isEmpty()) {
    xLogger.severe("Invalid, null or empty routeQueryString. {0}", routeQueryString);
    return;
  }

  String message = null;
  xLogger.fine("userId = {0}", userId);
  xLogger.fine("routeQueryString = {0}", routeQueryString);
  // Get the domain Id
  SecureUserDetails sUser = SecurityMgr.getUserDetails(req.getSession());
  Long domainId = SessionMgr.getCurrentDomain(req.getSession(), sUser.getUsername());

  try {
    as.updateManagedEntitiesOrdering(domainId, userId, routeQueryString);
  } catch (ServiceException e) {
    xLogger.severe("Exception when saving managed entities route for userID {0}", userId);
    message = backendMessages.getString("error") + ": " + e.getMessage();
  }
  String jsonString = null;
  if (message != null && !message.isEmpty()) {
    // There was an error
    jsonString = "{ \"st\" : \"1\", \"msg\" : \"" + message + "\" } ";
    resp.setStatus(500);
  } else {
    // Success
    jsonString = "{ \"st\" : \"0\", \"msg\" : \"\" }";
    resp.setStatus(200);
  }
  resp.setContentType(JsonRestServlet.JSON_UTF8);
  PrintWriter pw = resp.getWriter();
  pw.write(jsonString);
  pw.close();
  xLogger.fine("Exiting saveManagedEntitiesOrdering");
}
 
Example 16
Project: logistimo-web-service   File: CreateEntityServlet.java   View Source Code Vote up 4 votes
private void saveRelatedEntitiesOrdering(HttpServletRequest req, HttpServletResponse resp,
                                         EntitiesService as, ResourceBundle backendMessages,
                                         ResourceBundle messages) throws IOException {
  xLogger.fine("Entering saveRelatedEntitiesOrdering");
  String kioskIdStr = req.getParameter(KIOSKID);
  if (kioskIdStr == null || kioskIdStr.isEmpty()) {
    xLogger.severe("Invalid, null or empty kioskIdStr. {0}", kioskIdStr);
    return;
  }
  Long kioskId = Long.valueOf(kioskIdStr);
  String routeQueryString = req.getParameter("routequerystring");
  if (routeQueryString == null || routeQueryString.isEmpty()) {
    xLogger.severe("Invalid, null or empty routeQueryString. {0}", routeQueryString);
    return;
  }
  String linkType = req.getParameter("linktype");
  if (linkType == null || linkType.isEmpty()) {
    xLogger.severe("Invalid, null or empty linkType. {0}", linkType);
    return;
  }

  String message = null;
  xLogger.fine("kioskId = {0}", kioskId);
  xLogger.fine("routeQueryString = {0}", routeQueryString);
  // Get the domain Id
  SecureUserDetails sUser = SecurityMgr.getUserDetails(req.getSession());
  Long domainId = SessionMgr.getCurrentDomain(req.getSession(), sUser.getUsername());

  try {
    as.updateRelatedEntitiesOrdering(domainId, kioskId, linkType, routeQueryString);
  } catch (ServiceException e) {
    xLogger.severe("Exception when saving linked kiosk route for userID {0}", kioskId);
    message = backendMessages.getString("error") + ": " + e.getMessage();
  }
  String jsonString = null;
  if (message != null && !message.isEmpty()) {
    // There was an error
    jsonString = "{ \"st\" : \"1\", \"msg\" : \"" + message + "\" } ";
    resp.setStatus(500);
  } else {
    // Success
    jsonString = "{ \"st\" : \"0\", \"msg\" : \"\" }";
    resp.setStatus(200);
  }
  resp.setContentType(JsonRestServlet.JSON_UTF8);
  PrintWriter pw = resp.getWriter();
  pw.write(jsonString);
  pw.close();

  xLogger.fine("Exiting saveRelatedEntitiesOrdering");
}
 
Example 17
Project: DDNS_Server   File: UpdateServlet.java   View Source Code Vote up 4 votes
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
	
	DB dbProperties = new DB(getServletContext().getInitParameter("dbHost"), getServletContext().getInitParameter("dbPort"), getServletContext().getInitParameter("dbName"), getServletContext().getInitParameter("dbUser"), getServletContext().getInitParameter("dbPassword"));
   			
	PrintWriter out = response.getWriter();
	String authHeader = request.getHeader("authorization");
	String encodedValue = authHeader.split(" ")[1];
	byte[] decoded = Base64.decodeBase64(encodedValue);
	String decodedValue =  new String(decoded, StandardCharsets.UTF_8);
	DynUser current = LoginDao.validate( decodedValue.split(":")[0], decodedValue.split(":")[1], request, dbProperties);
	
	if ( current != null ) {
		String myip = request.getParameter("myip");
		if (myip == null) {
			myip = request.getHeader("X-FORWARDED-FOR");   
			if(myip==null)	{
			    myip = request.getRemoteAddr();
			}
		}
		if (isValidInetAddress(myip)) {
			String hostname = request.getParameter("hostname");
			List<String> hostnames;
			hostnames = Arrays.asList(hostname.split("\\s*,\\s*"));
			ArrayList<String> hostlist = new ArrayList<String>(hostnames); 
			if (hostlist.size() < 11) {  // 10 or less hosts as 10 is max for users
				
				ArrayList<Integer> hostID = UpdateDao.checkHosts(hostlist, current, dbProperties);
				if (hostID != null) {
					if (!UpdateDao.isTheSame(myip, hostlist, current, dbProperties)) {
						//update records
						UpdateDao.updateAddress(myip, hostID, dbProperties);
						UpdateDao.updateDNSAddress(myip, hostID, dbProperties);
						out.println("good");
						out.println(myip);
					} else {
						// no change needed.
						out.println("nochg");
					}
					
				} else {
					out.println("nohost");
				}
				
			} else {
				out.println("numhost");
			}
			
		} else {
			out.println("badaddress");
		}
	} else {
		out.println("badauth");
	}
}
 
Example 18
Project: tomcat7   File: HostManagerServlet.java   View Source Code Vote up 4 votes
/**
 * Process a GET request for the specified resource.
 *
 * @param request The servlet request we are processing
 * @param response The servlet response we are creating
 *
 * @exception IOException if an input/output error occurs
 * @exception ServletException if a servlet-specified error occurs
 */
@Override
public void doGet(HttpServletRequest request,
                  HttpServletResponse response)
    throws IOException, ServletException {

    StringManager smClient = StringManager.getManager(
            Constants.Package, request.getLocales());

    // Identify the request parameters that we need
    String command = request.getPathInfo();
    if (command == null)
        command = request.getServletPath();
    String name = request.getParameter("name");
  
    // Prepare our output writer to generate the response message
    response.setContentType("text/plain; charset=" + Constants.CHARSET);
    PrintWriter writer = response.getWriter();

    // Process the requested command
    if (command == null) {
        writer.println(sm.getString("hostManagerServlet.noCommand"));
    } else if (command.equals("/add")) {
        add(request, writer, name, false, smClient);
    } else if (command.equals("/remove")) {
        remove(writer, name, smClient);
    } else if (command.equals("/list")) {
        list(writer, smClient);
    } else if (command.equals("/start")) {
        start(writer, name, smClient);
    } else if (command.equals("/stop")) {
        stop(writer, name, smClient);
    } else {
        writer.println(sm.getString("hostManagerServlet.unknownCommand",
                                    command));
    }

    // Finish up the response
    writer.flush();
    writer.close();

}
 
Example 19
Project: parabuild-ci   File: JUnitServletTest.java   View Source Code Vote up 4 votes
protected void doGet( HttpServletRequest req, HttpServletResponse resp ) throws ServletException, IOException {
    resp.setContentType( "text/html" );
    PrintWriter pw = resp.getWriter();
    pw.print( RESPONSE_TEXT );
    pw.close();
}
 
Example 20
Project: PCloud_Server_v3   File: UserLoginAction.java   View Source Code Vote up 4 votes
@Override
public void execute(HttpServletRequest request,
		HttpServletResponse response, HttpServlet httpServlet) {
	
	try {
		//输出对象
		PrintWriter writer = response.getWriter();
		//构建Json字符串工具类
		ActionJson aJson = new ActionJson(getActionName());
		//读取请求参数
		String username = getRequestParameter("username");
		String password = getRequestParameter("password");
		try {
			// 数据库操作 - 获取用户的token(会触发SQLException)
			JSONObject json = SqlDataProvider.UserLogin(username, password);

			// 向ActionJson对象赋值
			// 标记操作成功
			aJson.setFlag(true);
			// 设置内容为token
			aJson.setContent(json.toString());

		} catch (SQLException e) {
			// 标记操作失败
			aJson.setFlag(false);
			
			//获取逻辑错误的提示信息
			String info = getPromptFromSQLException(e);
			//判断是否是逻辑错误,设置相应提示信息
			if(info!=null){
				aJson.setMessage(info);
			}else{
				aJson.setMessage("数据库未知错误.");
				//显示错误信息
				e.printStackTrace();
			}
		} finally {
			// 返回请求数据并关闭连接
			writer.println(aJson.toString());
			//关闭连接
			writer.flush();
			writer.close();
		}
	} catch (IOException e1) {
		e1.printStackTrace();
	}
}