示例#1
1
  @Override
  public ActionForward execute(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws Exception {

    String text = null;

    try {
      text = getText(mapping, form, request, response);
    } catch (Exception e) {
      PortalUtil.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e, request, response);

      return null;
    }

    response.setContentType(ContentTypes.TEXT_PLAIN_UTF8);
    response.setHeader(HttpHeaders.CACHE_CONTROL, HttpHeaders.CACHE_CONTROL_NO_CACHE_VALUE);

    PrintWriter printWriter = response.getWriter();

    printWriter.write(text);

    printWriter.close();

    return null;
  }
  public ActionForward createClassifications(
      ActionMapping mapping,
      ActionForm form,
      HttpServletRequest request,
      HttpServletResponse response)
      throws FenixFilterException, FenixServiceException, IOException {

    IUserView userView = UserView.getUser();

    DynaActionForm dynaActionForm = (DynaActionForm) form;
    Integer degreeCurricularPlanID = (Integer) dynaActionForm.get("degreeCurricularPlanID");
    Integer[] entryGradeLimits = (Integer[]) dynaActionForm.get("entryGradeLimits");
    Integer[] approvationRatioLimits = (Integer[]) dynaActionForm.get("approvationRatioLimits");
    Integer[] arithmeticMeanLimits = (Integer[]) dynaActionForm.get("arithmeticMeanLimits");

    Object[] args = {
      entryGradeLimits, approvationRatioLimits, arithmeticMeanLimits, degreeCurricularPlanID
    };
    ByteArrayOutputStream resultStream =
        (ByteArrayOutputStream)
            ServiceUtils.executeService("CreateClassificationsForStudents", args);

    String currentDate = new SimpleDateFormat("dd-MMM-yy.HH-mm").format(new Date());
    response.setHeader(
        "Content-disposition",
        "attachment;filename=" + degreeCurricularPlanID + "_" + currentDate + ".zip");
    response.setContentType("application/zip");
    DataOutputStream dos = new DataOutputStream(response.getOutputStream());
    dos.write(resultStream.toByteArray());
    dos.close();

    return null;
  }
  public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
      throws IOException, ServletException {
    HttpServletRequest req = (HttpServletRequest) request;
    String fileName = req.getRequestURI().split("/")[req.getRequestURI().split("/").length - 1];
    boolean bExcept = false;
    for (String prefix : exceptList) {
      if (fileName.startsWith(prefix)) {
        bExcept = true;
        break;
      }
    }

    if (!bExcept) {
      HttpSession session = ((HttpServletRequest) request).getSession();
      if (!(session != null && session.getAttribute("user") != null)) {
        session.setAttribute("lastFileName", fileName);
        HttpServletResponse resp = (HttpServletResponse) response;
        resp.sendRedirect("login.jsp");
        return;
      }
    }
    //    String browserDet = ((HttpServletRequest) request).getHeader("User-Agent").toLowerCase();
    //    if (browserDet.indexOf("msie") != -1) {
    //      PrintWriter out = response.getWriter();
    //      out.println("<html><head></head><body>");
    //      out.println("<h1>Sorry, page cannot be displayed!</h1>");
    //      out.println("</body></html>");
    //      out.flush();
    //      return;
    //    }
    chain.doFilter(request, response);
  }
示例#4
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    request.setCharacterEncoding("UTF-8");
    String first_name = request.getParameter("firstName");
    String last_name = request.getParameter("lastName");
    String email = request.getParameter("email");
    String addrid = request.getParameter("addr");

    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    String date = df.format(new Date());
    String sql =
        "INSERT INTO customer(first_name,last_name,email,address_id,store_id,create_date) VALUES('"
            + first_name
            + "','"
            + last_name
            + "','"
            + email
            + "',"
            + addrid
            + ",1,'"
            + date
            + "')"; // 日期自动添加
    // TODO Auto-generated method stub
    int i = DbOperater.DML(sql);
    response.getWriter().print("<script>alert('success')</script>");
    response.sendRedirect("index.jsp");
  }
  /**
   * This method is requesting the front page since that is all this servlet does (apart from config
   * initialisation and sharing). Return it here.
   */
  @Override
  protected void doGet(HttpServletRequest req, HttpServletResponse response)
      throws ServletException, IOException {
    /* HTTP 1.1 */
    response.setHeader("Cache-Control", "no-cache");
    /* HTTP 1.0 */
    response.setHeader("Pragma", "no-cache");
    /* Prevents caching at the proxy server */
    response.setDateHeader("Expires", 0);
    /*
     * Just return the front page. If we want some more (dynamic) web pages
     * available here, we need to do some extra handling of what the URL
     * actually says
     */
    Template template = velocityEngine.getTemplate("templates/index.vm");
    VelocityContext context = new VelocityContext();
    EventCartridge ec = new EventCartridge();
    ec.addEventHandler(new EscapeHtmlReference());
    ec.attachToContext(context);

    context.put("catalogue", catalogue);
    context.put("config", catalogue.getConfig());
    context.put("GISUtils", GISUtils.class);
    context.put("supportedImageFormats", ImageFormat.getSupportedMimeTypes());
    template.merge(context, response.getWriter());
  }
示例#6
0
 @Override
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String pathInfo = request.getPathInfo();
   if (pathInfo == null) {
     response.setStatus(HttpServletResponse.SC_NOT_FOUND);
   } else {
     try {
       // Handle JSP requests.
       if (pathInfo.endsWith(".jsp")) {
         if (handleDevJSP(pathInfo, request, response)) {
           return;
         }
         handleJSP(pathInfo, request, response);
       }
       // Handle servlet requests.
       else if (getServlet(pathInfo) != null) {
         handleServlet(pathInfo, request, response);
       }
       // Handle image/other requests.
       else {
         handleOtherRequest(pathInfo, response);
       }
     } catch (Exception e) {
       Log.error(e.getMessage(), e);
       response.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
     }
   }
 }
 @Override
 public void doGet(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   res.setContentType("application/json");
   Pair<DateTime, DateTime> fromTo = fromTo(req);
   orla.writeHourlyPercentiles(res.getOutputStream(), fromTo.getLeft(), fromTo.getRight());
 }
示例#8
0
  public static void destroySubscribe(HttpServletRequest req, HttpServletResponse res) {

    try {
      AsyncMessage message = new AsyncMessage();
      message.setMessageType("test_subscribe");

      SubscriberController controller =
          (SubscriberController) BeanFactory.getBean("publish_subscribe_controller");
      controller.unregist(message);
      //			String mseq = req.getParameter("mseq");
      HttpSession session = req.getSession(false);
      //			SSysOperatorsList list =
      // (SSysOperatorsList)req.getSession(false).getAttribute(mseq);
      //			int size = list.size();
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
      res.getWriter().println("<pre>");
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
    } catch (Exception e) {
      try {
        res.getWriter().println("<pre>");
        e.printStackTrace(res.getWriter());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
示例#9
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   * @throws ServletException if a servlet-specific error occurs
   * @throws IOException if an I/O error occurs
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html;charset=UTF-8");
    PrintWriter out = response.getWriter();
    // String county= request.getParameter("county").toString();
    String countyid = request.getParameter("countyid");
    String id = request.getParameter("id");
    String value = request.getParameter("value");
    String columnName = request.getParameter("columnName");
    String columnId = request.getParameter("columnId");
    String columnPosition = request.getParameter("columnPosition");
    String rowId = request.getParameter("rowId");
    response.getWriter().print(value);
    HttpSession session;

    session = request.getSession(true);
    //  String unique=(String)session.getAttribute("countyid");
    dbConnect conn = new dbConnect();

    String query =
        "update behaviourscode set BehavioursCode='"
            + value
            + "'where BehavioursCodeID='"
            + id
            + "'";

    try {
      conn.state.executeUpdate(query);

      //                   response.sendRedirect("CountyServlet");
    } catch (SQLException ex) {
      Logger.getLogger(UpdateBehaviour.class.getName()).log(Level.SEVERE, null, ex);
      out.println(ex.toString());
    }
  }
示例#10
0
  // Implementation methods
  // -------------------------------------------------------------------------
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    try {
      WebClient client = WebClient.getWebClient(request);
      Session session = client.getSession();
      Queue queue = getQueue(request, session);
      if (queue == null) {
        throw new ServletException("No queue URI specified");
      }

      String msgId = request.getParameter("msgId");
      if (msgId == null) {
        MessageRenderer renderer = getMessageRenderer(request);
        configureRenderer(request, renderer);

        String selector = getSelector(request);
        QueueBrowser browser = session.createBrowser(queue, selector);
        renderer.renderMessages(request, response, browser);
      } else {
        XmlMessageRenderer renderer = new XmlMessageRenderer();
        QueueBrowser browser = session.createBrowser(queue, "JMSMessageID='" + msgId + "'");
        if (!browser.getEnumeration().hasMoreElements()) {
          response.sendError(HttpServletResponse.SC_NOT_FOUND);
          return;
        }
        Message message = (Message) browser.getEnumeration().nextElement();

        PrintWriter writer = response.getWriter();
        renderer.renderMessage(writer, request, response, browser, message);
        writer.flush();
      }
    } catch (JMSException e) {
      throw new ServletException(e);
    }
  }
  /**
   * 覆盖默认实现,用sendRedirect直接跳出框架,以免造成js框架重复加载js出错。
   *
   * @param token
   * @param subject
   * @param request
   * @param response
   * @return
   * @throws Exception
   * @see
   *     org.apache.shiro.web.filter.authc.FormAuthenticationFilter#onLoginSuccess(org.apache.shiro.authc.AuthenticationToken,
   *     org.apache.shiro.subject.Subject, javax.servlet.ServletRequest,
   *     javax.servlet.ServletResponse)
   */
  @Override
  protected boolean onLoginSuccess(
      AuthenticationToken token, Subject subject, ServletRequest request, ServletResponse response)
      throws Exception {
    // issueSuccessRedirect(request, response);
    // we handled the success redirect directly, prevent the chain from continuing:
    HttpServletRequest httpServletRequest = (HttpServletRequest) request;
    HttpServletResponse httpServletResponse = (HttpServletResponse) response;

    ShiroDbRealm.ShiroUser shiroUser = (ShiroDbRealm.ShiroUser) subject.getPrincipal();
    // 加入ipAddress
    shiroUser.setIpAddress(request.getRemoteAddr());

    // 这个是放入user还是shiroUser呢?
    httpServletRequest.getSession().setAttribute(SecurityConstants.LOGIN_USER, shiroUser.getUser());

    if (!"XMLHttpRequest".equalsIgnoreCase(httpServletRequest.getHeader("X-Requested-With"))
        || request.getParameter("ajax") == null) { // 不是ajax请求
      httpServletResponse.sendRedirect(httpServletRequest.getContextPath() + this.getSuccessUrl());
    } else {
      httpServletResponse.sendRedirect(
          httpServletRequest.getContextPath() + "/login/timeout/success");
    }

    return false;
  }
示例#12
0
  @RequiresPermissions("data:o_export")
  @RequestMapping(value = "/mysql/data/o_export.do")
  public String exportSubmit(
      String[] names, ModelMap model, HttpServletRequest request, HttpServletResponse response)
      throws UnsupportedEncodingException {
    if (validate(names, request)) {
      WebErrors errors = WebErrors.create(request);
      errors.addErrorCode(INVALID_PARAM);
      return errors.showErrorPage(model);
    }
    String backName = "back";
    if (names != null && names.length > 0 && names[0] != null) {
      backName =
          names[0].substring(
              names[0].indexOf(Constants.BACKUP_PATH) + Constants.BACKUP_PATH.length() + 1);
    }

    List<FileEntry> fileEntrys = new ArrayList<FileEntry>();
    response.setContentType("application/x-download;charset=UTF-8");
    response.addHeader("Content-disposition", "filename=" + backName + ".zip");
    for (String filename : names) {
      File file = new File(realPathResolver.get(filename));
      fileEntrys.add(new FileEntry("", "", file));
    }
    try {
      // 模板一般都在windows下编辑,所以默认编码为GBK
      Zipper.zip(response.getOutputStream(), fileEntrys, "GBK");
    } catch (IOException e) {
      log.error("export db error!", e);
    }
    return null;
  }
示例#13
0
 /** Sends an error to the user with the given {@code status} and body. */
 public static void sendError(HttpServletResponse response, String body, int status)
     throws IOException {
   Preconditions.checkArgument(status > 300);
   response.setStatus(status);
   response.setHeader(HttpHeaders.CONTENT_TYPE, "text/plain");
   response.getWriter().write(Escaper.escapeHtml(body));
 }
示例#14
0
 private void process(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String login = request.getParameter("login");
   String password = request.getParameter("password");
   if (login != null && password != null) {
     UserService service = null;
     try {
       service = new UserService();
       User user = service.findByLoginAndPassword(login, password);
       if (user != null) {
         HttpSession session = request.getSession();
         session.setAttribute("currentUser", user);
         response.sendRedirect(request.getContextPath());
       } else {
         response.sendRedirect(
             request.getContextPath()
                 + "/login.html?message="
                 + URLEncoder.encode("Имя пользователя или пароль неопознанны", "UTF-8"));
       }
     } catch (SQLException e) {
       throw new ServletException(e);
     } finally {
       if (service != null) {
         service.close();
       }
     }
   } else {
     getServletContext().getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, response);
   }
 }
示例#15
0
  /**
   * 获取异步请求结果
   *
   * @param req
   * @param res
   */
  public static void asyncResult(HttpServletRequest req, HttpServletResponse res) {
    IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt();
    SSysOperatorsListHolder holder = new SSysOperatorsListHolder();
    CBSErrorMsg errMsg = new CBSErrorMsg();
    iAsyncMgntInt.setAsyncCall(true);

    try {
      String mseq = req.getParameter("mseq");

      MessageSequence ms = new MessageSequence(mseq);

      iAsyncMgntInt.setMseq(ms);
      int result = iAsyncMgntInt.select_sysOperators_response(holder, errMsg);
      res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
      SSysOperatorsList list = holder.value;
      int size = list.size();
      res.getWriter().println("<pre>");
      for (int i = 0; i < size; i++) {
        SSysOperators opers = (SSysOperators) list.get(i);
        res.getWriter().println(i + ":" + opers.get_loginName());
      }
      res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
    } catch (Exception e) {
      // TODO Auto-generated catch block
      try {
        e.printStackTrace(res.getWriter());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
  static void sendJSONResponse(HttpServletResponse response, Map<String, String> responseMap) {
    if (!Boolean.parseBoolean(responseMap.get("success"))) {
      int serverCode = 500;
      if (responseMap.containsKey("serverCode")) {
        serverCode = Integer.parseInt(responseMap.get("serverCode"));
      }
      response.setStatus(serverCode);
    }

    String responseContent = new Gson().toJson(responseMap);
    response.setContentType("application/json");
    response.setCharacterEncoding("utf-8");
    response.setHeader("Content-Length", Integer.toString(responseContent.length()));

    Writer writer = null;
    try {
      writer = response.getWriter();
      writer.write(responseContent);
    } catch (IOException ex) {
      Logger.getLogger(RequestResponseHelper.class.getName()).log(Level.SEVERE, null, ex);
    } finally {
      if (writer != null) {
        try {
          writer.close();
        } catch (IOException ex) {
          Logger.getLogger(RequestResponseHelper.class.getName()).log(Level.SEVERE, null, ex);
        }
      }
    }
  }
示例#17
0
  /**
   * 超时测试
   *
   * @param req
   * @param res
   */
  public static void asyncTimeout(HttpServletRequest req, HttpServletResponse res) {
    IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt();
    iAsyncMgntInt.setAsyncCall(true); // 标志异步调用
    iAsyncMgntInt.setTimeout(10000);
    SSysOperatorsListHolder holder = new SSysOperatorsListHolder();
    CBSErrorMsg errMsg = new CBSErrorMsg();
    try {

      int result = iAsyncMgntInt.select_sysOperators_timeout(holder, errMsg); // 获取响应结果

      SSysOperatorsList list = holder.value;
      int size = list.size();
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
      res.getWriter().println("<pre>");
      for (int i = 0; i < size; i++) {
        SSysOperators opers = (SSysOperators) list.get(i);
        res.getWriter().println(i + ":" + opers.get_loginName());
      }
      res.getWriter().println("<a href=\"./index.html\">返回首页</a><br>");
    } catch (Exception e) {
      try {
        res.getWriter().println("<pre>");
        e.printStackTrace(res.getWriter());
      } catch (IOException e1) {
        e1.printStackTrace();
      }
    }
  }
示例#18
0
  public static void renderFile(
      HttpServletResponse resp,
      String filename,
      InputStream cont_stream,
      boolean showpic,
      boolean ignorespace)
      throws IOException {
    if (cont_stream == null) return;

    if (ignorespace) filename = filename.replace(" ", "");

    if (!showpic)
      resp.addHeader(
          "Content-Disposition",
          "attachment; filename=" + new String(filename.getBytes(), "iso8859-1"));

    resp.setContentType(Mime.getContentType(filename));
    ServletOutputStream os = resp.getOutputStream();
    byte[] buf = new byte[1024];
    int len = 0;
    while ((len = cont_stream.read(buf)) != -1) {
      os.write(buf, 0, len);
    }

    os.flush();
  }
 private void write(HttpServletResponse response, String resultado) throws IOException {
   response.setContentType("text/html");
   PrintWriter writer = response.getWriter();
   writer.print(resultado);
   writer.flush();
   writer.close();
 }
示例#20
0
  public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain)
      throws IOException, ServletException {

    HttpServletRequest request = (HttpServletRequest) req;
    HttpServletResponse response = (HttpServletResponse) res;

    String relativeUrl = request.getRequestURI(); /* 以根开头的URL */
    String path = request.getContextPath(); /* 获取客户端请求的上下文根 */

    /** 如果是登录请求,则进行登录认证。 如果是其它请求,则进行IP绑定匹配。 */
    if (relativeUrl.replaceAll(path, "").equals("/login")) { // 登录请求,登录认证
      if (request.getMethod().equals("POST")) { // 登录参数必须通过post方式传过来,security要求的
        int status = myAuthentication.getAuthenticationStatus(request); // 调用认证逻辑
        if (status == 0) { // 通过认证,则保存登录IP到session,并通过此过滤器
          request.getSession().setAttribute("bindIp", RequestIP.getRequestIp(request));
          chain.doFilter(request, response);
        } else { // 未通过认证,则拒绝登录,并返回登录页面提示相关信息
          response.sendRedirect(path + "/toIndex.action?error=" + status);
        }
      } else { // 如果不是POST方式,则返回登录页面,并提示信息
        response.sendRedirect(path + "/toIndex.action?error=9"); // 登录必须用POST方式
      }
    } else { // 其它请求(filters="none"的请求不会被处理,logout请求在此filter之前会被处理)
      // PC端进行IP认证
      String loginIp = (String) request.getSession().getAttribute("bindIp"); // 登录时记录的IP
      String currentIp = RequestIP.getRequestIp(request); // 当前请求的IP
      if (loginIp != null && !loginIp.equals(currentIp)) { // 如果此次请求的IP与登录IP不符,则禁止访问,并返回提示
        response.sendRedirect(path + "/toIndex.action?error=10");
      } else { // 如果IP匹配,则通过此过滤器
        chain.doFilter(request, response);
      }
    }
  }
示例#21
0
  private void addCookie(ExternalContext extContext, Flash flash) {
    // Do not update the cookie if redirect after post
    if (flash.isRedirect()) {
      return;
    }

    String thisRequestSequenceString = null;
    HttpServletResponse servletResponse = null;
    // PortletRequest portletRequest = null;
    Object thisRequestSequenceStringObj, response = extContext.getResponse();

    thisRequestSequenceStringObj =
        extContext.getRequestMap().get(Constants.FLASH_THIS_REQUEST_ATTRIBUTE_NAME);
    if (null == thisRequestSequenceStringObj) {
      return;
    }
    thisRequestSequenceString = thisRequestSequenceStringObj.toString();

    if (response instanceof HttpServletResponse) {
      servletResponse = (HttpServletResponse) response;
      Cookie cookie =
          new Cookie(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME, thisRequestSequenceString);
      cookie.setMaxAge(-1);
      servletResponse.addCookie(cookie);
    } else {
      /**
       * *** portletRequest = (PortletRequest) request; // You can't add a cookie in portlet. //
       * http://wiki.java.net/bin/view/Portlet/JSR168FAQ#How_can_I_set_retrieve_a_cookie
       * portletRequest.getPortletSession().setAttribute(Constants.FLASH_POSTBACK_REQUEST_ATTRIBUTE_NAME,
       * thisRequestSequenceString, PortletSession.PORTLET_SCOPE); *******
       */
    }
  }
示例#22
0
 /*    */ @RequestMapping({"/board/list.jsp"})
 /*    */ public String list(
     Integer pageNo,
     Integer count,
     HttpServletRequest request,
     HttpServletResponse response,
     ModelMap model)
       /*    */ {
   /* 69 */ Site site = ContextTools.getSite(request);
   /* 70 */ Page page =
       this.service.getPage(
           null,
           site.getId(),
           Boolean.valueOf(true),
           null,
           null,
           /* 71 */ pageNo.intValue(),
           count.intValue());
   /* 72 */ model.addAttribute("page", page);
   /* 73 */ ViewTools.frontData(request, model, site);
   /* 74 */ response.setHeader("Cache-Control", "no-cache");
   /* 75 */ response.setContentType("text/json;charset=UTF-8");
   /* 76 */ return ViewTools.getTplPath(
       null, site.getSolutionPath(), /* 77 */ "common/tags", "board_list");
   /*    */ }
示例#23
0
  /** @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response) */
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html;charset=utf-8");
    PrintWriter out = response.getWriter();
    if (request.getParameter("action") != null) {
      this.action = request.getParameter("action");
      if (action.equals("add")) // 添加商品进购物车
      {
        if (addToCart(request, response)) {
          request.getRequestDispatcher("/success.jsp").forward(request, response);
        } else {
          request.getRequestDispatcher("/failure.jsp").forward(request, response);
        }
      }

      if (action.equals("show")) // 显示购物车
      {
        request.getRequestDispatcher("/cart.jsp").forward(request, response);
      }

      if (action.equals("delete")) // 如果是执行删除购物车中的商品
      {
        if (deleteFromCart(request, response)) {
          request.getRequestDispatcher("/cart.jsp").forward(request, response);
        } else {
          request.getRequestDispatcher("/cart.jsp").forward(request, response);
        }
      }
    }
  }
示例#24
0
  public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
      throws ServletException {
    boolean result = super.preHandle(request, response, handler);

    ThemeResolver themeResolver = RequestContextUtils.getThemeResolver(request);

    String newTheme = themeResolver.resolveThemeName(request);

    if (!validThemes.contains(newTheme)) {
      // not found.
      logger.error("Invalid theme passed in: " + newTheme);
      try {
        response.sendRedirect("accessDenied.jsp");

        return false;
      } catch (IOException e) {
        throw new ServletException("Could not redirect to accessDenied page.", e);
      }
    } else if (request.getParameter(this.paramName) != null) {
      // found.  redirect to page without "param=.." extension.
      logger.warn("New theme set: " + newTheme + ".  Redirecting to login.htm");
      try {
        response.sendRedirect("login.htm");
      } catch (IOException e) {
        throw new ServletException("Could not redirect to login page.", e);
      }
    }

    return result;
  }
示例#25
0
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    Logger.getLogger(getClass()).debug("LOGIN device J2ME");

    final UserWorkerLocal userWorkerLocal = ServiceLocator.lookupLocal(UserWorkerLocal.JNDI_NAME);
    final SubjectWorkerLocal subjectWorkerLocal =
        ServiceLocator.lookupLocal(SubjectWorkerLocal.JNDI_NAME);

    DataInputStream dis = null;
    try {
      dis = new DataInputStream(request.getInputStream());
      final String login = dis.readUTF();
      final String password = dis.readUTF();

      final User user = userWorkerLocal.login(login, password);

      final String deviceId = subjectWorkerLocal.loginDevice(user);
      final byte[] resultBytes = deviceId.getBytes("utf-8");
      response.setContentLength(resultBytes.length);
      response.getOutputStream().write(resultBytes);
    } catch (LoginFailedException e) {
      response.sendError(HttpServletResponse.SC_FORBIDDEN);
    } finally {
      if (dis != null) {
        dis.close();
      }
    }
  }
 public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
     throws IOException, ServletException { // 登录界面login.jsp进入前判断是否已经登陆,是则直接跳转
   HttpServletRequest req = (HttpServletRequest) request;
   HttpServletResponse res = (HttpServletResponse) response;
   Cookie cookies[] = req.getCookies();
   Cookie login = null;
   Cookie user = null;
   Cookie admin = null;
   // 1)判断cookie为空。2)cookie存在,但没有"loginName"。
   // 3)cookie存在,但有"loginName",但loginName为null或0。
   if (cookies != null) {
     for (int i = 0; i < cookies.length; i++) {
       if (cookies[i].getName().equals("LoginName")) {
         login = cookies[i];
       } else if (cookies[i].getName().equals("superUser")) {
         user = cookies[i];
       } else if (cookies[i].getName().equals("adminRight")) {
         admin = cookies[i];
       }
     }
   }
   if (login != null && !login.getValue().equals("")) {
     if (admin != null && !admin.getValue().equals("")) {
       res.sendRedirect("/Login_Servlet/administrator/login/success.jsp");
     } else if (user != null && !user.getValue().equals("")) {
       res.sendRedirect("/Login_Servlet/user/login/success.jsp");
     }
   } else {
     chain.doFilter(request, response);
   }
 }
示例#27
0
 protected void service(HttpServletRequest req, HttpServletResponse res)
     throws ServletException, IOException {
   res.setHeader("Pragma", "no-cache");
   res.setHeader("Cache-Control", "no-cache");
   res.setDateHeader("Expires", 0);
   super.service(req, res);
 }
示例#28
0
 /**
  * 发起同步请求,获取后台信息,直接显示在页面上
  *
  * @param req
  * @param res
  */
 public static void sync(HttpServletRequest req, HttpServletResponse res) {
   System.setProperty("0", "aaaaaaaa");
   //		h.put(i+"","aaaaaaaaaaaaaaaaaaaaaaaa");
   //		i++;
   //		System.out.println("*************************system prop is " +
   // System.getProperties());
   IAsyncMgntInt iAsyncMgntInt = new IAsyncMgntInt();
   SSysOperatorsListHolder holder = new SSysOperatorsListHolder();
   CBSErrorMsg errMsg = new CBSErrorMsg();
   try {
     res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
     int result = iAsyncMgntInt.select_sysOperators(holder, errMsg);
     System.out.println("*****result is " + result);
     if (result != 0) {
       res.getWriter().println(errMsg.get_errorMsg() + ":" + errMsg.get_errorCode());
     }
     SSysOperatorsList list = holder.value;
     int size = list.size();
     res.getWriter().println("<pre>");
     for (int i = 0; i < size; i++) {
       SSysOperators opers = (SSysOperators) list.get(i);
       res.getWriter().println(i + ":" + opers.get_loginName());
     }
     res.getWriter().println("<a href=\"./index.html\">返回首页</a></script>");
   } catch (Exception e) {
     e.printStackTrace();
   }
 }
示例#29
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    // 接收时设置的编码
    request.setCharacterEncoding("utf-8");
    // 转发时设置的编码
    response.setCharacterEncoding("utf-8");
    // 以 超文本格式 方式转发
    response.setContentType("text/html");
    // 获取了一个输出流
    PrintWriter out = response.getWriter();

    // 修改库存数量Ajax
    String id = request.getParameter("id");
    String number = request.getParameter("number");
    NeProductsDao neProductsDao = new NeProductsDaoImpl();
    int count = neProductsDao.updateNumber(Integer.parseInt(id), Integer.parseInt(number));
    if (count > 0) {
      out.println("商品" + id + "库存数量修改成功");
    } else {
      out.println("商品" + id + "库存数量修改失败");
    }

    out.flush();
    out.close();
  }
示例#30
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    ResultSet rs = null;
    String sid = "000";
    try {

      String sql = "select top 1 Substation_ID from Substation order by Substation_ID desc";
      dataselect ds = new dataselect();
      rs = ds.select(sql);
      if (rs != null) {
        rs.next();
        sid = rs.getString(1);
      }
      rs.close();
      ds.close();
    } catch (Exception ex) {
      ex.printStackTrace();
    }
    // System.out.print(sid);
    int id = Integer.parseInt(sid) + 1;
    out.println(id);
    out.flush();
    out.close();
  }