コード例 #1
1
  /**
   * Creates a Discussion Post
   *
   * <p>- Requires a cookie for the session user - Requires a comment and threadId request parameter
   * for the POST
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void createPostAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<>();

    if (req.getMethod() == HttpMethod.Post) {
      DiscussionManager dm = new DiscussionManager();

      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");

      // Create the discussion post
      DiscussionPost post = new DiscussionPost();
      post.setUserId(userSession.getUserId());
      post.setMessage(req.getParameter("comment"));
      post.setThreadId(Integer.parseInt(req.getParameter("threadId")));

      dm.createPost(post);

      redirectToLocal(req, res, "/group/discussion/?threadId=" + req.getParameter("threadId"));
    } else {
      httpNotFound(req, res);
    }
  }
コード例 #2
1
  public static void showSession(HttpServletRequest req, PrintStream out) {

    // res.setContentType("text/html");

    // Get the current session object, create one if necessary
    HttpSession session = req.getSession();

    out.println("Session id: " + session.getId());
    out.println(" session.isNew(): " + session.isNew());
    out.println(" session.getMaxInactiveInterval(): " + session.getMaxInactiveInterval() + " secs");
    out.println(
        " session.getCreationTime(): "
            + session.getCreationTime()
            + " ("
            + new Date(session.getCreationTime())
            + ")");
    out.println(
        " session.getLastAccessedTime(): "
            + session.getLastAccessedTime()
            + " ("
            + new Date(session.getLastAccessedTime())
            + ")");
    out.println(" req.isRequestedSessionIdFromCookie: " + req.isRequestedSessionIdFromCookie());
    out.println(" req.isRequestedSessionIdFromURL: " + req.isRequestedSessionIdFromURL());
    out.println(" req.isRequestedSessionIdValid: " + req.isRequestedSessionIdValid());

    out.println("Saved session Attributes:");
    Enumeration atts = session.getAttributeNames();
    while (atts.hasMoreElements()) {
      String name = (String) atts.nextElement();
      out.println(" " + name + ": " + session.getAttribute(name) + "<BR>");
    }
  }
コード例 #3
1
  /**
   * Deletes a meeting from the database
   *
   * <p>- Requires a cookie for the session user - Requires a meetingId request parameter for the
   * HTTP GET
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void deletemeetingAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    if (req.getMethod() == HttpMethod.Get) {

      // Get the meeting
      int meetingId = Integer.parseInt(req.getParameter("meetingId"));
      MeetingManager meetingMan = new MeetingManager();
      Meeting meeting = meetingMan.get(meetingId);
      meetingMan.deleteMeeting(meetingId);

      // Update the User Session to remove meeting
      HttpSession session = req.getSession();
      Session userSession = (Session) session.getAttribute("userSession");
      List<Meeting> adminMeetings = userSession.getUser().getMeetings();

      for (int i = 0; i < adminMeetings.size(); i++) {
        Meeting m = adminMeetings.get(i);
        if (m.getId() == meeting.getId()) {
          adminMeetings.remove(i);
          break;
        }
      }

      redirectToLocal(req, res, "/home/dashboard");
      return;

    } else if (req.getMethod() == HttpMethod.Post) {
      httpNotFound(req, res);
    }
  }
コード例 #4
1
  private void processReturn(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {
    Account principal = this.verifyResponse(req);

    // System.out.println(principal);

    String returnURL = req.getParameter("exist_return");

    if (principal == null) {
      // this.getServletContext().getRequestDispatcher("/openid/login.xql").forward(req, resp);
      resp.sendRedirect(returnURL);
    } else {
      HttpSession session = req.getSession(true);

      // ((XQueryURLRewrite.RequestWrapper)req).setUserPrincipal(principal);

      Subject subject = new Subject();

      // TODO: hardcoded to jetty - rewrite
      // *******************************************************
      DefaultIdentityService _identityService = new DefaultIdentityService();
      UserIdentity user = _identityService.newUserIdentity(subject, principal, new String[0]);

      Authentication cached = new HttpSessionAuthentication(session, user);
      session.setAttribute(HttpSessionAuthentication.__J_AUTHENTICATED, cached);
      // *******************************************************

      resp.sendRedirect(returnURL);
    }
  }
コード例 #5
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   response.setContentType("text/html");
   PrintWriter out = response.getWriter();
   String title = "Showing Request Headers";
   StringBuilder sb = new StringBuilder();
   sb.append("<html>\n<head>\n");
   sb.append("<title>" + title + "</title>\n");
   sb.append("</head>\n");
   sb.append("<body bgcolor='#FDF5E6'>\n");
   sb.append("<h1 align='center'>" + title + "</h1>\n");
   sb.append("<b> Request Method: </b>" + request.getMethod() + "<br>\n");
   sb.append("<b> Request URI: </b>" + request.getRequestURI() + "<br>\n");
   sb.append("<b> Request Protocol: </b>" + request.getProtocol() + "<br>\n");
   sb.append("<table border=1 align='center'>\n");
   sb.append("<tr bgcolor='#FFAD00'>\n");
   sb.append("<th> Header Name </th><th> Header Value </th></tr>\n");
   Enumeration headerNames = request.getHeaderNames();
   while (headerNames.hasMoreElements()) {
     String headerName = (String) headerNames.nextElement();
     sb.append("<tr><td>" + headerName + "</td>");
     sb.append("<td>" + request.getHeader(headerName) + "</td></tr>\n");
   }
   sb.append("</table>\n");
   sb.append("</body></html>");
   out.println(sb.toString());
   out.close();
 }
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    try {
      userObj = new User();
      tmsManager = new TMSManager();

      RequestDispatcher rd1 = request.getRequestDispatcher("./header");
      rd1.include(request, response);

      out.println("<html><head><title>UpdateUser</title></head>");
      out.println("<body onload=onSubmit() bgcolor =\"#ffcc00\">");
      out.println("<form  method =\"POST\"  action =\"./updateUser\" ><br><br><br>");
      out.println("<table border = 1 width = \"40%\" align = \"center\" bgcolor = \"#bbccff\">");
      out.println("<caption><b>UpdateUser</b></caption>");
      out.println("<tr><td style = font face: verdana>Enter User ID</td>");
      out.println("<td><input type = \"text\" name = \"user_id\" ></td></tr>");
      out.println(
          "<tr><td colspan = 2 align = \"center\"><input type = \"submit\"  name = \"Submit\" value = \"Submit\">");
      out.println("<input type = \"Reset\"  name = \"Reset\" value = \"Clear\"></td></tr>");
      out.println("</table>");
      out.println("</body></html>");

      // String user_id = request.getParameter("user_id");
      //    userObj = tmsManager.getUser(user_id);
    } catch (Exception e) {
      System.out.println(e.getMessage());
    }

    RequestDispatcher rd2 = request.getRequestDispatcher("./footer");
    rd2.include(request, response);
  }
コード例 #7
0
  /**
   * 判断是否需要必须录入合同金额
   *
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  private String calNeedInputMoney(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String xml = null;
    String company_id = JUtil.convertNull(request.getParameter("company_id"));
    String exter_contract_type = JUtil.convertNull(request.getParameter("exter_contract_type"));
    String need_con_money = "0";
    xml = "<?xml version='1.0' encoding='gbk'?>\n";
    org.jdom.Element eleRoot = new org.jdom.Element("root");
    org.jdom.Element eleNeed = new org.jdom.Element("need_con_money");

    try {
      List<ExterContractType> lsType = ExterContractType.getContractTypeByCompany(company_id);
      for (ExterContractType type : lsType) {
        if (type.getCon_type_id().equals(exter_contract_type)) {
          if (type.getNeed_con_money() == 1) {
            need_con_money = "1";
          }
          break;
        }
      }
      eleNeed.setAttribute("need_con_money", need_con_money);
      eleRoot.addContent(eleNeed);
      org.jdom.output.XMLOutputter xmlout = new org.jdom.output.XMLOutputter();
      xml += xmlout.outputString(eleRoot);
      JLog.getLogger().debug("xml=\n" + xml);
      return xml.trim();
    } catch (Exception e) {
      JLog.getLogger().error("", e);
    }
    return "";
  }
コード例 #8
0
ファイル: MobileApi.java プロジェクト: chrooter/bkitpoma
  @Override
  protected void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // POST method only used for tracked login operation
    HttpSession session = request.getSession();
    response.setContentType("text/plain");
    PrintWriter out = response.getWriter();

    // Get the username and password from request
    String username = request.getParameter("id");
    String password = request.getParameter("pwd");

    Long id = 0L;
    try {
      id = Long.parseLong(username);
    } catch (Exception ex) {
    }

    if (username != null && password != null) {
      // Login into tracked system
      CTracked ctracked = db.loginTrackedFromMobile(id, password).getResult();

      if (ctracked != null) {
        // Login successful
        out.print("OK," + ctracked.getUsername());
        session.setAttribute("device_id", ctracked.getUsername());
        log.info(ctracked + " : logined!");
      }
    }
  }
コード例 #9
0
ファイル: bill_delete_ok.java プロジェクト: RainerJava/erp-6
  public synchronized void service(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    HttpSession dbSession = request.getSession();
    JspFactory _jspxFactory = JspFactory.getDefaultFactory();
    PageContext pageContext =
        _jspxFactory.getPageContext(this, request, response, "", true, 8192, true);
    ServletContext dbApplication = dbSession.getServletContext();

    ServletContext application;
    HttpSession session = request.getSession();
    nseer_db_backup1 finance_db = new nseer_db_backup1(dbApplication);

    try {

      if (finance_db.conn((String) dbSession.getAttribute("unit_db_name"))) {
        String finance_cheque_id = request.getParameter("finance_cheque_id");
        String sql = "delete from finance_bill where id='" + finance_cheque_id + "'";
        finance_db.executeUpdate(sql);
        finance_db.commit();
        finance_db.close();

      } else {
        response.sendRedirect("error_conn.htm");
      }
    } catch (Exception ex) {
      ex.printStackTrace();
    }
  }
コード例 #10
0
  public void doPost(HttpServletRequest req, HttpServletResponse resp)
      throws ServletException, IOException {

    resp.setContentType("text/html");
    PrintWriter out = resp.getWriter();

    String support = "support"; // valid username

    HttpSession session = null;
    session = req.getSession(false); // Get user's session object (no new one)
    if (session == null) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String userName = (String) session.getAttribute("user"); // get username

    if (!userName.equals(support)) {

      invalidUser(out); // Intruder - reject
      return;
    }

    String action = "";
    if (req.getParameter("todo") != null) action = req.getParameter("todo");

    if (action.equals("update")) {

      doUpdate(out);
      return;
    }

    out.println("<p>Nothing to do.</p>todo=" + action);
  }
コード例 #11
0
 private void setHttpRequestStockPlace(HttpServletRequest request, OutMgr outMgr) {
   outMgr.setCurrentInventoryPlace(request.getParameter("place"));
   outMgr.setLocationPlace(
       (LocationPlace)
           Utility.getObject(
               outMgr.getStockPlaceMeta().getStockPlaceList(), request.getParameter("place")));
 }
コード例 #12
0
  /**
   * Displays a Discussion Thread page
   *
   * <p>- Requires a cookie for the session user - Requires a threadId request parameter for the
   * HTTP GET
   *
   * @param req The HTTP Request
   * @param res The HTTP Response
   */
  public void discussionAction(HttpServletRequest req, HttpServletResponse res) {
    // Ensure there is a cookie for the session user
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<>();

    if (req.getMethod() == HttpMethod.Get) {

      // Get the thread
      GroupManager gm = new GroupManager();
      int threadId = Integer.parseInt(req.getParameter("threadId"));
      DiscussionManager discussionManager = new DiscussionManager();
      DiscussionThread thread = discussionManager.getThread(threadId);
      thread.setGroup(gm.get(thread.getGroupId()));
      thread.setPosts(discussionManager.getPosts(threadId));

      // get documents for the thread
      DocumentManager docMan = new DocumentManager();
      viewData.put("documents", docMan.getDocumentsForThread(threadId));

      viewData.put("thread", thread);
      viewData.put("title", "Discussion: " + thread.getThreadName());
      view(req, res, "/views/group/DiscussionThread.jsp", viewData);
    } else {
      httpNotFound(req, res);
    }
  }
コード例 #13
0
ファイル: readPostParameters.java プロジェクト: kmizu/spnuts
 protected Object exec(Object[] args, Context context) {
   int nargs = args.length;
   if (nargs != 1 && nargs != 2) {
     undefined(args, context);
     return null;
   }
   HttpServletRequest request = (HttpServletRequest) args[0];
   String enc;
   if (nargs == 1) {
     enc = ServletEncoding.getDefaultInputEncoding(context);
   } else {
     enc = (String) args[1];
   }
   String contentType = request.getContentType();
   if (contentType != null && contentType.startsWith("multipart/form-data")) {
     throw new RuntimeException("not yet implemented");
   } else {
     try {
       ByteArrayOutputStream bout = new ByteArrayOutputStream();
       byte[] buf = new byte[512];
       int n;
       InputStream in = request.getInputStream();
       while ((n = in.read(buf, 0, buf.length)) != -1) {
         bout.write(buf, 0, n);
       }
       in.close();
       String qs = new String(bout.toByteArray());
       Map map = URLEncoding.parseQueryString(qs, enc);
       return new ServletParameter(map);
     } catch (IOException e) {
       throw new PnutsException(e, context);
     }
   }
 }
コード例 #14
0
ファイル: BaseXServlet.java プロジェクト: james-jw/basex
  @Override
  public final void service(final HttpServletRequest req, final HttpServletResponse res)
      throws IOException {

    final HTTPContext http = new HTTPContext(req, res, this);
    final boolean restxq = this instanceof RestXqServlet;
    try {
      http.authorize();
      run(http);
      http.log(SC_OK, "");
    } catch (final HTTPException ex) {
      http.status(ex.getStatus(), Util.message(ex), restxq);
    } catch (final LoginException ex) {
      http.status(SC_UNAUTHORIZED, Util.message(ex), restxq);
    } catch (final IOException | QueryException ex) {
      http.status(SC_BAD_REQUEST, Util.message(ex), restxq);
    } catch (final ProcException ex) {
      http.status(SC_BAD_REQUEST, Text.INTERRUPTED, restxq);
    } catch (final Exception ex) {
      final String msg = Util.bug(ex);
      Util.errln(msg);
      http.status(SC_INTERNAL_SERVER_ERROR, Util.info(UNEXPECTED, msg), restxq);
    } finally {
      if (Prop.debug) {
        Util.outln("_ REQUEST _________________________________" + Prop.NL + req);
        final Enumeration<String> en = req.getHeaderNames();
        while (en.hasMoreElements()) {
          final String key = en.nextElement();
          Util.outln(Text.LI + key + Text.COLS + req.getHeader(key));
        }
        Util.out("_ RESPONSE ________________________________" + Prop.NL + res);
      }
    }
  }
コード例 #15
0
 public DownloadRequest(ServletContext context, HttpServletRequest request) {
   _context = context;
   _httpRequest = request;
   _path = request.getRequestURI();
   _encoding = request.getHeader(ACCEPT_ENCODING);
   String context_path = request.getContextPath();
   if (context_path != null) _path = _path.substring(context_path.length());
   if (_path == null) _path = request.getServletPath(); // This works for *.<ext> invocations
   if (_path == null) _path = "/"; // No path given
   _path = _path.trim();
   if (_context != null && !_path.endsWith("/")) {
     String realPath = _context.getRealPath(_path);
     // fix for 4474021 - getRealPath might returns NULL
     if (realPath != null) {
       File f = new File(realPath);
       if (f != null && f.exists() && f.isDirectory()) {
         _path += "/";
       }
     }
   }
   // Append default file for a directory
   if (_path.endsWith("/")) _path += "launch.jnlp";
   _version = getParameter(request, ARG_VERSION_ID);
   _currentVersionId = getParameter(request, ARG_CURRENT_VERSION_ID);
   _os = getParameterList(request, ARG_OS);
   _arch = getParameterList(request, ARG_ARCH);
   _locale = getParameterList(request, ARG_LOCALE);
   _knownPlatforms = getParameterList(request, ARG_KNOWN_PLATFORMS);
   String platformVersion = getParameter(request, ARG_PLATFORM_VERSION_ID);
   _isPlatformRequest = (platformVersion != null);
   if (_isPlatformRequest) _version = platformVersion;
   _query = request.getQueryString();
   _testJRE = getParameter(request, TEST_JRE);
 }
コード例 #16
0
ファイル: ShowSession.java プロジェクト: marleau/cs122b_p2
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Session Tracking Example";
    HttpSession session = request.getSession(true);
    String heading;

    Integer accessCount = (Integer) session.getAttribute("accessCount");

    if (accessCount == null) {
      accessCount = new Integer(0);
      heading = "Welcome, Newcomer";
    } else {
      heading = "Welcome Back";
      accessCount = new Integer(accessCount.intValue() + 1);
    }

    session.setAttribute("accessCount", accessCount);
    out.println(
        "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=\"CENTER\">"
            + heading
            + "</H1>\n"
            + "<H2>Information on Your Session:</H2>\n"
            + "<TABLE BORDER=1 ALIGN=\"CENTER\">\n"
            + "<TR BGCOLOR=\"#FFAD00\">\n"
            + "  <TH>Info Type<TH>Value\n"
            + "<TR>\n"
            + "  <TD>ID\n"
            + "  <TD>"
            + session.getId()
            + "\n"
            + "<TR>\n"
            + "  <TD>Creation Time\n"
            + "  <TD>"
            + new Date(session.getCreationTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Time of Last Access\n"
            + "  <TD>"
            + new Date(session.getLastAccessedTime())
            + "\n"
            + "<TR>\n"
            + "  <TD>Number of Previous Accesses\n"
            + "  <TD>"
            + accessCount
            + "\n"
            + "</TR>"
            + "</TABLE>\n");

    // the following two statements show how to retrieve parameters in
    // the request.  The URL format is something like:
    // http://localhost:8080/project2/servlet/ShowSession?myname=Chen%20Li
    String myname = request.getParameter("myname");
    if (myname != null) out.println("Hey " + myname + "<br><br>");

    out.println("</BODY></HTML>");
  }
コード例 #17
0
  /**
   * Constructor.
   *
   * @param rq request
   * @param rs response
   * @throws IOException I/O exception
   */
  public HTTPContext(final HttpServletRequest rq, final HttpServletResponse rs) throws IOException {

    req = rq;
    res = rs;
    final String m = rq.getMethod();
    method = HTTPMethod.get(m);

    final StringBuilder uri = new StringBuilder(req.getRequestURL());
    final String qs = req.getQueryString();
    if (qs != null) uri.append('?').append(qs);
    log(false, m, uri);

    // set UTF8 as default encoding (can be overwritten)
    res.setCharacterEncoding(UTF8);

    segments = toSegments(req.getPathInfo());
    path = join(0);

    user = System.getProperty(DBUSER);
    pass = System.getProperty(DBPASS);

    // set session-specific credentials
    final String auth = req.getHeader(AUTHORIZATION);
    if (auth != null) {
      final String[] values = auth.split(" ");
      if (values[0].equals(BASIC)) {
        final String[] cred = Base64.decode(values[1]).split(":", 2);
        if (cred.length != 2) throw new LoginException(NOPASSWD);
        user = cred[0];
        pass = cred[1];
      } else {
        throw new LoginException(WHICHAUTH, values[0]);
      }
    }
  }
コード例 #18
0
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   EstacionBombeoModule module = (EstacionBombeoModule) context.getBean("estacionBombeoModule");
   try {
     String presionSalida = request.getParameter("presionSalida");
     int presionSalidaObj = Integer.parseInt(presionSalida);
     String presionEntrada = request.getParameter("presionEntrada");
     int presionEntradaObj = Integer.parseInt(presionEntrada);
     String cantidadBombas = request.getParameter("cantidadBombas");
     int cantidadBombasObj = Integer.parseInt(cantidadBombas);
     String capacidadMaxima = request.getParameter("capacidadMaxima");
     int capacidadMaximaObj = Integer.parseInt(cantidadBombas);
     String idAcueducto = request.getParameter("idAcueducto");
     int idAcueductoObj = Integer.parseInt(idAcueducto);
     String encargado = request.getParameter("encargado");
     String tipo = request.getParameter("tipo");
     String telefono = request.getParameter("telefono");
     String nombreEstacion = request.getParameter("nombreEstacion");
     module.insertar(
         presionSalidaObj,
         tipo,
         capacidadMaximaObj,
         cantidadBombasObj,
         encargado,
         telefono,
         presionEntradaObj,
         idAcueductoObj,
         nombreEstacion);
     response.sendRedirect("listaEstacionBombeos");
   } catch (Exception e) {
     request.setAttribute("mensaje", e.getMessage());
     forward(e.getMessage(), request, response);
   }
 }
コード例 #19
0
	// post方式发送email
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("UTF-8");
		File file = doAttachment(request);
		EmailAttachment attachment = new EmailAttachment();
		attachment.setPath(file.getPath());
		attachment.setDisposition(EmailAttachment.ATTACHMENT);
		attachment.setName(file.getName());
		MultiPartEmail email = new MultiPartEmail();
		email.setCharset("UTF-8");
		email.setHostName("smtp.sina.com");
		email.setAuthentication("T-GWAP", "dangdang");
		try {
			email.addTo(parameters.get("to"));
			email.setFrom(parameters.get("from"));
			email.setSubject(parameters.get("subject"));
			email.setMsg(parameters.get("body"));
			email.attach(attachment);
			email.send();
			request.setAttribute("sendmail.message", "邮件发送成功!");
		} catch (EmailException e) {
			Logger logger = Logger.getLogger(SendAttachmentMailServlet.class);
			logger.error("邮件发送不成功", e);
			request.setAttribute("sendmail.message", "邮件发送不成功!");
		}
		request.getRequestDispatcher("/sendResult.jsp").forward(request,
				response);
	}
コード例 #20
0
ファイル: CaseDel.java プロジェクト: kouzant/e-Lawyer
  /**
   * Parse the case id from the url and then delete it. Finally redirects the response and the
   * request to admCase.jsp
   *
   * @see DatabaseMethods#caseDelete(int)
   * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
   */
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    // TODO Auto-generated method stub

    request.setCharacterEncoding("UTF-8");
    response.setCharacterEncoding("UTF-8");
    DatabaseMethods dbPoint = new DatabaseMethods();
    HttpSession userSession = request.getSession();

    if (Integer.parseInt(userSession.getAttribute("isadmin").toString()) == 1) {
      int caseId = Integer.parseInt(request.getParameter("caseId"));

      int success = dbPoint.caseDelete(caseId);

      if (success != 0) {
        userSession.setAttribute("caseDelete", "1");
      } else {
        userSession.setAttribute("caseDelete", "0");
      }
    }
    RequestDispatcher rd = getServletContext().getRequestDispatcher("/admCase.jsp");
    if (rd != null) {
      rd.forward(request, response);
    }
  }
コード例 #21
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    try {

      response.setContentType("text/html");
      PrintWriter out = response.getWriter();

      /*String n=request.getParameter("username");
      out.print("Welcome "+n);*/

      String name = request.getParameter("name");
      String dob = request.getParameter("dob");
      String address = request.getParameter("address");
      String email = request.getParameter("email");
      HttpSession session = request.getSession(true);
      String userid = (String) session.getAttribute("theName");
      int AccNo = 0;
      String AccMsg = "";

      DbCommunication db_comm = new DbCommunication();
      AccNo = db_comm.accountCreation(name, dob, address, email, userid);
      // db_comm.accountCreation(name,email);
      AccMsg = "Account created successfully. Account number is:" + AccNo;
      // out.println(AccMsg);

      String redirectURL = "accountCreationPage.jsp";
      response.sendRedirect(redirectURL);
      session.setAttribute("AccCreationalMsgStatus", "set");
      session.setAttribute("AccCreationalMsg", AccMsg);

    } catch (Exception e) {
      System.out.println(e);
    }
  }
コード例 #22
0
  /**
   * 根据公司ID,获得对外合同申请的合同类别 取公司对应的合同类型 如公司为空,则取所有
   *
   * @param request
   * @param response
   * @return
   * @throws Exception
   */
  private String calExterContractApplyType(HttpServletRequest request, HttpServletResponse response)
      throws Exception {
    String xml = null;
    String company_id = JUtil.convertNull(request.getParameter("company_id"));
    String defalut_type = JUtil.convertNull(request.getParameter("defalut_type"));
    xml = "<?xml version='1.0' encoding='gbk'?>\n";
    org.jdom.Element eleRoot = new org.jdom.Element("root");
    org.jdom.Element defalutType = new org.jdom.Element("defalut_type");
    defalutType.setAttribute("defalut_type", defalut_type);
    eleRoot.addContent(defalutType);
    org.jdom.Element eleRows = new org.jdom.Element("contract_types");
    eleRoot.addContent(eleRows);
    org.jdom.Element eleRow = null;

    try {
      List<ExterContractType> lsType = ExterContractType.getContractTypeByCompany(company_id);
      for (ExterContractType type : lsType) {
        eleRow = new org.jdom.Element("contract_type");
        eleRow.setAttribute("con_type_id", type.getCon_type_id());
        eleRow.setAttribute("con_type_name", type.getCon_type_name());
        eleRows.addContent(eleRow);
      }
      org.jdom.output.XMLOutputter xmlout = new org.jdom.output.XMLOutputter();
      xml += xmlout.outputString(eleRoot);
      JLog.getLogger().debug("xml=\n" + xml);
      return xml.trim();
    } catch (Exception e) {
      JLog.getLogger().error("", e);
    }
    return "";
  }
コード例 #23
0
 private String getOriginOrReferer(HttpServletRequest pReq) {
   String origin = pReq.getHeader("Origin");
   if (origin == null) {
     origin = pReq.getHeader("Referer");
   }
   return origin != null ? origin.replaceAll("[\\n\\r]*", "") : null;
 }
コード例 #24
0
  public void summaryAction(HttpServletRequest req, HttpServletResponse res) {
    if (AccountController.redirectIfNoCookie(req, res)) return;

    Map<String, Object> viewData = new HashMap<String, Object>();
    DocumentManager docMan = new DocumentManager();

    try {

      if (req.getParameter("documentId") != null) {
        // Get the document ID
        int docId = Integer.parseInt(req.getParameter("documentId"));
        // Get the document using document id
        Document document = docMan.get(docId);
        // Set title to name of the document
        viewData.put("title", document.getDocumentName());
        // Create List of access records
        List<AccessRecord> accessRecords = new LinkedList<AccessRecord>();
        // Add access records for document to the list
        accessRecords = docMan.getAccessRecords(docId);

        viewData.put("accessRecords", accessRecords);
      } else {
        // Go back to thread page.
      }

    } catch (Exception e) {
      Logger.getLogger("").log(Level.SEVERE, "An error occurred when getting profile user", e);
    }

    view(req, res, "/views/group/Document.jsp", viewData);
  }
コード例 #25
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    res.setContentType("text/html");
    PrintWriter out = res.getWriter();
    Enumeration values = req.getParameterNames();
    String name = "";
    String value = "";
    String id = "";
    while (values.hasMoreElements()) {
      name = ((String) values.nextElement()).trim();
      value = req.getParameter(name).trim();
      if (name.equals("id")) id = value;
    }
    if (url.equals("")) {
      url = getServletContext().getInitParameter("url");
      cas_url = getServletContext().getInitParameter("cas_url");
    }
    HttpSession session = null;
    session = req.getSession(false);
    if (session != null) {
      session.invalidate();
    }
    res.sendRedirect(cas_url);
    return;
  }
コード例 #26
0
ファイル: GpsImport.java プロジェクト: craser/kukido
  public ActionForward execute(
      ActionMapping mapping, ActionForm form, HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    try {
      GpsImportForm gpsForm = (GpsImportForm) form;
      User user = (User) req.getSession().getAttribute("user");
      int entryId = gpsForm.getEntryId();
      String fileName = gpsForm.getFileName();
      String title = gpsForm.getTitle();
      String activityId = gpsForm.getActivityId();
      String xml = gpsForm.getXml();
      log.debug(xml);

      List<GpsTrack> tracks = new TcxParser().parse(xml.getBytes());
      GpsTrack track = tracks.get(0); // Horrible hack.
      createAttachment(user, entryId, fileName, title, activityId, track);
      createGeotag(fileName, track);

      req.setAttribute("status", "success");
      req.setAttribute("message", "");
      log.debug("Returning status: success.");
      return mapping.findForward("results");
    } catch (Exception e) {
      log.fatal("Error processing incoming Garmin XML", e);
      req.setAttribute("status", "failure");
      req.setAttribute("message", e.toString());
      return mapping.findForward("results");
    }
  }
コード例 #27
0
ファイル: login.java プロジェクト: nitt006/project_final
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    PrintWriter writer = response.getWriter();
    HttpSession session = request.getSession();

    String username = request.getParameter("username");
    String password = request.getParameter("password");
    String type = request.getParameter("type");
    System.out.println(username + password + type);

    session.setAttribute("user", username);

    try {
      writer.println("<html>");
      writer.println("<body bgcolor=green>");
      writer.println("<center>");
      ps.setString(1, username);
      ps.setString(2, password);
      ps.setString(3, type);
      ResultSet rs = ps.executeQuery();

      if (rs.next()) {
        writer.println("<h1>LOGIN SUCCESSFUL</h1><br><br>");
        writer.println("<a href=account.html>click here to see your account</a>");
      } else {
        writer.println("<h1>LOGIN FAILED</h1><br><br>");
        writer.println("<a href=login.html>click here to login again</a>");
      }
      writer.println("</center>");
      writer.println("</body>");
      writer.println("</html>");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
コード例 #28
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    String title = "Reading All Request Parameters";
    out.println(
        ServletUtilities.headWithTitle(title)
            + "<BODY BGCOLOR=\"#FDF5E6\">\n"
            + "<H1 ALIGN=CENTER>"
            + title
            + "</H1>\n"
            + "<TABLE BORDER=1 ALIGN=CENTER>\n"
            + "<TR BGCOLOR=\"#FFAD00\">\n"
            + "<TH>Parameter Name<TH>Parameter Value(s)");
    Enumeration paramNames = request.getParameterNames();
    while (paramNames.hasMoreElements()) {
      String paramName = (String) paramNames.nextElement();
      out.println("<TR><TD>" + paramName + "\n<TD>");
      String[] paramValues = request.getParameterValues(paramName);
      if (paramValues.length == 1) {
        String paramValue = paramValues[0];
        if (paramValue.length() == 0) out.print("<I>No Value</I>");
        else out.print(paramValue);
      } else {
        out.println("<UL>");
        for (int i = 0; i < paramValues.length; i++) {
          out.println("<LI>" + paramValues[i]);
        }
        out.println("</UL>");
      }
    }
    out.println("</TABLE>\n</BODY></HTML>");
  }
コード例 #29
0
ファイル: BeerSelect.java プロジェクト: ithakar/servlet
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {
    // res.setContentType("text/html");
    // PrintWriter pw = res.getWriter();
    // pw.println("Beer selection advice<br/>");
    BeerExpert be = new BeerExpert();
    String c = req.getParameter("color");
    List result = be.getBrands(c);

    req.setAttribute("styles", result);

    String email = getServletConfig().getInitParameter("adminEmail");
    RequestDispatcher view = req.getRequestDispatcher("result.jsp");
    // try{
    view.forward(req, res);
    // } catch (Exception e) {
    // 	System.out.println("some thing wrong in view.forward");
    // 	e.printStackTrace();
    // }

    // Iterator it = result.iterator();
    // while(it.hasNext()){
    // 	pw.println("<br/> tyr: " + it.next());
    // }

  }
コード例 #30
0
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();

    if (request.getParameter("setcookie") != null) {
      Cookie cookie = new Cookie("Learningjava", "Cookies!");
      cookie.setMaxAge(3600);
      response.addCookie(cookie);
      out.println("<html><body><h1>Cookie Set...</h1>");
    } else {
      out.println("<html><body>");
      Cookie[] cookies = request.getCookies();
      if (cookies.length == 0) {
        out.println("<h1>No cookies found...</h1>");
      } else {
        for (int i = 0; i < cookies.length; i++)
          out.print(
              "<h1>Name: "
                  + cookies[i].getName()
                  + "<br>"
                  + "Value: "
                  + cookies[i].getValue()
                  + "</h1>");
      }
      out.println(
          "<p><a href=\""
              + request.getRequestURI()
              + "?setcookie=true\">"
              + "Reset the Learning Java cookie.</a>");
    }
    out.println("</body></html>");
  }