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);
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    pedidosDAO dao = new pedidosDAO();

    String clavePedido = request.getParameter("clavePedido");

    pedidoBean pedido = new pedidoBean();

    pedido = dao.getPedido(clavePedido);

    String claveCliente = pedido.getClaveCliente();
    String nombreCliente = pedido.getNombreEmpresa();
    String FechaS = pedido.getFecha();
    String detallesPedido = pedido.getDetallesPedido();
    String fechaInicial = pedido.getFechaInicial();
    String fechaFinal = pedido.getFechaFinal();
    String noPedido = pedido.getNoPedido();
    String tipoCambio = pedido.getTipoCambio();
    String tiposIva = pedido.getTipoIva();
    String tipoPedido = pedido.getTipoPedido();

    List listaClientes = new ArrayList();

    listaClientes = dao.getClientes();

    String mensaje = "";

    if (pedido.getClavePedido() == null) {
      mensaje = "¡Numero de pedido No encontrado!";
      RequestDispatcher rdExito =
          request.getRequestDispatcher("/jsp/Pedido/cargaModificarPedido.jsp");

      request.setAttribute("mensaje", mensaje);

      rdExito.forward(request, response);
    } else {

      RequestDispatcher rdExito = request.getRequestDispatcher("/jsp/Pedido/modificarPedido.jsp");

      request.setAttribute("FechaS", FechaS);
      request.setAttribute("mensaje", mensaje);
      request.setAttribute("clavePedido", clavePedido);
      request.setAttribute("claveCliente", claveCliente);
      request.setAttribute("nombreCliente", nombreCliente);
      request.setAttribute("detallesPedido", detallesPedido);
      request.setAttribute("fechaFinal", fechaFinal);
      request.setAttribute("noPedido", noPedido);
      request.setAttribute("tipoCambio", tipoCambio);
      request.setAttribute("tiposIva", tiposIva);
      request.setAttribute("tipoPedido", tipoPedido);
      request.setAttribute("listaClientes", listaClientes);
      request.setAttribute("fechaInicial", fechaInicial);

      rdExito.forward(request, response);
    }
  }
Esempio n. 3
0
  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());
    // }

  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    /*	-- pentru codul scris in java
    	response.setContentType("text/thml");
    	PrintWriter out =  response.getWriter();
    	out.println("Beer Selection Advice");
    */
    String c = request.getParameter("color");
    /* se adauga clasa BeerExpert */
    BeerExpert be = new BeerExpert();
    List result = be.getBrands(c);

    /*
     out.println("Got beer color " + c);
    // afisare rezultate din metoda getBrends
     Iterator it = result.iterator();
     while(it.hasNext()){
     	out.println("try: "+ it.next());
     }
    */
    /* cod folosit de aplicatia JSP */
    request.setAttribute("styles", result);
    RequestDispatcher view = request.getRequestDispatcher("result.jsp");
    view.forward(request, response);
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    String amount = request.getParameter("amount");
    String amount2 = request.getParameter("amount2");
    String amount3 = request.getParameter("amount3");
    Integer posotita = Integer.parseInt(amount);
    Integer posotita2 = Integer.parseInt(amount2);
    Integer posotita3 = Integer.parseInt(amount3);

    HttpSession session = request.getSession();

    if (session.isNew()) {
      request.setAttribute("sessionVal", "this is a new session");
    } else {
      request.setAttribute("sessionVal", "Welcome Back!");
    }

    double total = ((posotita * 18.50) + (posotita2 * 6.95) + (posotita3 * 1.29));
    session.setAttribute("totalVal", total);

    request.setAttribute("currency", total);
    request.setAttribute("from", amount);
    request.setAttribute("from2", amount2);
    request.setAttribute("from3", amount3);

    RequestDispatcher view = request.getRequestDispatcher("index.jsp");
    view.forward(request, response);
  }
Esempio n. 6
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String fechaHora = request.getParameter("FechaHora");
    String place = request.getParameter("Place");
    String idlocalteam = request.getParameter("Idlocalteam");
    String idvisitteam = request.getParameter("Idvisitteam");
    String ronda = request.getParameter("Ronda");
    String id = request.getParameter("id");

    PartidosBean partidosBean = new PartidosBean();
    partidosBean.setIdpartido(id);
    partidosBean.setDatetime(fechaHora);
    partidosBean.setPlace(place);

    EquiposBean localteam = new EquiposBean();
    localteam.setIdequipo(idlocalteam);

    EquiposBean visitteam = new EquiposBean();
    visitteam.setIdequipo(idvisitteam);

    partidosBean.setIdlocalteam(localteam);
    partidosBean.setIdvisitteam(visitteam);
    partidosBean.setRonda(ronda);

    String opcion = request.getParameter("opcion");

    /*if(opcion.equalsIgnoreCase("Agregar")){
        boolean status=AddPartido(partidosBean);
        if(status)
            request.setAttribute("Status",true);
        else
            request.setAttribute("Status",false);
    }*/

    /*if(opcion.equalsIgnoreCase("Eliminar")){
        boolean status=DeletePartido(partidosBean);
        if(status)
            request.setAttribute("Status",true);
        else
            request.setAttribute("Status",false);
    }*/

    if (opcion.equalsIgnoreCase("Editar")) {
      boolean status = EditPartido(partidosBean);
      if (status) request.setAttribute("Status", true);
      else request.setAttribute("Status", false);
    }

    // Mostramos los Equipos de los 8 Grupos
    EquiposDAO equiposDAO = new EquiposDAO();
    List<EquiposBean> equipos = equiposDAO.getTodosEquipos();
    request.setAttribute("Equipos", equipos);

    // Consultamos los Partidos Existentes
    PartidosDAO partidosDAO = new PartidosDAO();
    List<PartidosBean> partidos = partidosDAO.getTodosPartidos();
    request.setAttribute("Partidos", partidos);

    request.getRequestDispatcher("/WEB-INF/Partidos.jsp").forward(request, response);
  }
	// 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);
	}
Esempio n. 8
0
  public void doPost(HttpServletRequest req, HttpServletResponse res)
      throws IOException, ServletException {

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

    /* Get Session */
    HttpSession s = req.getSession(true);
    /* Make sure user is logged in */
    if (s.getAttribute("login") == null || (String) s.getAttribute("login") != "go") {
      req.getRequestDispatcher("login.jsp").forward(req, res);
    }

    try {
      String dbuser = this.getServletContext().getInitParameter("dbuser");
      String dbpassword = this.getServletContext().getInitParameter("dbpassword");

      Class.forName("com.mysql.jdbc.Driver");
      Connection conn =
          DriverManager.getConnection("jdbc:mysql://localhost/project", dbuser, dbpassword);

      Statement stmt = conn.createStatement();
      stmt.execute(
          "INSERT INTO songs VALUES(null, '"
              + req.getParameter("song_name")
              + "', '"
              + req.getParameter("artist")
              + "', '"
              + req.getParameter("album")
              + "', '"
              + req.getParameter("genre")
              + "', 0)");

      stmt.close();
      conn.close();

      // delete memcache since new song is now added
      MemcachedClient c = new MemcachedClient(new InetSocketAddress("127.0.0.1", 11211));
      c.delete("master");

      req.getRequestDispatcher("add_song_success.jsp").forward(req, res);

    } catch (Exception e) {
      out.println(e.getMessage());
    }
  }
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String deleteProductValue = "false";

    try {

      // Get the form data
      int productID = Integer.parseInt(request.getParameter("productID"));
      PrintWriter out = response.getWriter();
      DB db = mongo.getDB("FashionFactoryProd");
      DBCollection myProducts = db.getCollection("productInfo");
      DBCollection myTrending = db.getCollection("myTrending");
      BasicDBObject searchQuery = new BasicDBObject();
      searchQuery.put("productID", productID);
      DBCursor cursor = myProducts.find(searchQuery);

      if (cursor.count() == 0) {
        deleteProductValue = "false";
        request.setAttribute("deleteProductValue", deleteProductValue);
        RequestDispatcher rd = request.getRequestDispatcher("deleteProduct.jsp");
        rd.forward(request, response);
      } else {
        int product = 0;
        while (cursor.hasNext()) {

          BasicDBObject obj = (BasicDBObject) cursor.next();
          product = obj.getInt("productID");
          if (product == productID) {
            myProducts.remove(obj);
            myTrending.remove(searchQuery);
            deleteProductValue = "true";

            request.setAttribute("deleteProductValue", deleteProductValue);

            RequestDispatcher rd = request.getRequestDispatcher("deleteProduct.jsp");
            rd.forward(request, response);
          }
        }
      }
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
Esempio n. 10
0
  public void doGet(HttpServletRequest req, HttpServletResponse res)
      throws ServletException, IOException {

    // read the last post id here .......................
    String url = req.getRequestURI();
    String urlprt[] = url.split("/");
    int urlcount = urlprt.length - 1;

    JSONParser parserPost = new JSONParser();
    JSONObject post = null;
    String id = urlprt[urlcount];

    // read the post  here .............................

    try {

      if (id != null) {
        Object objPost =
            parserPost.parse(new FileReader("..\\webapps\\Blog\\post\\" + id + ".json"));

        post = (JSONObject) objPost;
        String postauthor = post.get("author").toString();
        String posttitle = post.get("title").toString();
        String postcontent = post.get("content").toString();

        JSONArray arr = (JSONArray) post.get("comments");
        List<String> list = new ArrayList<String>();
        Iterator<String> iterator = arr.iterator();

        while (iterator.hasNext()) {
          list.add(iterator.next());
        }

        int listsz = list.size();
        String[] comments = new String[listsz];
        for (int i = 0; i < listsz; i++) {
          comments[i] = list.get(i);
        }

        req.setAttribute("title", posttitle);
        req.setAttribute("content", postcontent);
        req.setAttribute("author", postauthor);
        req.setAttribute("comments", comments);
        req.setAttribute("id", id);

        req.getRequestDispatcher("/view.jsp").forward(req, res);
      }

    } catch (Exception e) {
      res.setContentType("text/html");
      PrintWriter out = res.getWriter();
      out.println("get POST ......................");
      out.println(e);
      out.println("......................");
    }
  }
Esempio n. 11
0
 // @ requires request != null;
 // @ requires response != null;
 // @ requires s != null;
 public void redirect(HttpServletRequest request, HttpServletResponse response, String s) {
   RequestDispatcher dispatcher = request.getRequestDispatcher(s);
   try {
     dispatcher.forward(request, response);
   } catch (IOException ioe) {
     System.out.println(ioe);
   } catch (ServletException se) {
     System.out.println(se);
   }
 }
Esempio n. 12
0
  public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

    String fowarding = "/guestbook";
    RequestDispatcher rd = req.getRequestDispatcher(fowarding);

    try {
      rd.forward(req, resp);
    } catch (ServletException e) {
      e.printStackTrace();
    }
  }
  /** Show appropriate order page. */
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    ServletContext sc = getServletContext();
    Connection conn = (Connection) sc.getAttribute("dbConnection");
    HttpSession session = request.getSession();
    synchronized (session) {
      LoginSession ls = (LoginSession) session.getAttribute("loginSession");
      if (ls == null) {
        return;
      }
      Basket basket = ls.getUser().getBasket();
      // If there is no basket, do nothing
      if (basket == null) {
        return;
      }
      if (request.getParameter("dialog").equals("yes")) {
        String msg = null;
        Order order = null;
        try {
          order = new Order();
          msg = order.form(basket, conn);
        } catch (SQLException exc) {
          request.setAttribute("sqlExc", exc);
          request.getRequestDispatcher("/error").forward(request, response);
          return;
        }
        // If there is a message (that means can't form an order)
        if (msg != null) {
          request.setAttribute("errMsg", msg);
        }
      }
      if (request.getParameter("dialog").equals("show")) {
        request.setAttribute("itemList", basket.getItemList());
      }
      request.setAttribute("url", request.getRequestURI());
      request.getRequestDispatcher("/WEB-INF/OrderVerified.jsp").forward(request, response);
    }
  }
Esempio n. 14
0
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   Integer etat = (Integer) request.getSession().getAttribute("etat");
   if (etat == null) {
     RequestDispatcher dispatcher = request.getRequestDispatcher("/login.jsp");
     dispatcher.forward(request, response);
   } else {
     try {
       String titre = request.getParameter("titre");
       String dateSortie = request.getParameter("dateSortie");
       String nom = request.getParameter("nom");
       String role = request.getParameter("role");
       // conversion du parametre dateSortie en SQLDate
       Date date;
       try {
         date = new Date(FormatDate.convertirDate(dateSortie).getTime());
       } catch (ParseException e) {
         throw new Tp6Exception(
             "Format de la date " + dateSortie + " incorrect. AAAA-MM-JJ attendue.");
       }
       // executer la transaction
       GestionTp6 tp6Update = (GestionTp6) request.getSession().getAttribute("tp6Update");
       synchronized (tp6Update) {
         tp6Update.gestionFilm.ajoutActeurFilm(titre, date, nom, role);
       }
       RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/menu.jsp");
       dispatcher.forward(request, response);
     } catch (Tp6Exception e) {
       List<String> listeMessageErreur = new LinkedList<String>();
       listeMessageErreur.add(e.toString());
       request.setAttribute("listeMessageErreur", listeMessageErreur);
       RequestDispatcher dispatcher = request.getRequestDispatcher("/WEB-INF/menu.jsp");
       dispatcher.forward(request, response);
     } catch (Exception e) {
       e.printStackTrace();
       response.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, e.toString());
     }
   }
 }
Esempio n. 15
0
 @Override
 public void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   String length = request.getParameter("primeLength");
   ServletContext context = getServletContext();
   synchronized (this) {
     if ((context.getAttribute("primeBean") == null) || (!isMissing(length))) {
       PrimeBean primeBean = new PrimeBean(length);
       context.setAttribute("primeBean", primeBean);
     }
     String address = "/WEB-INF/results/show-prime.jsp";
     RequestDispatcher dispatcher = request.getRequestDispatcher(address);
     dispatcher.forward(request, response);
   }
 }
Esempio n. 16
0
  protected void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    String[] uri = request.getRequestURI().split("/");
    if (uri.length < 4) {
      response.getWriter().print(XavaResources.getString(request, "module_name_missing"));
      return;
    }
    String url = "/naviox/index.jsp?application=" + uri[1] + "&module=" + uri[3];
    RequestDispatcher dispatcher = request.getRequestDispatcher(url);

    Style.setPotalInstance(
        NaviOXStyle
            .getInstance()); // We manage style in NaviOX as in the portal case, to override the
                             // style defined in xava.properties and by device
    dispatcher.forward(request, response);
  }
Esempio n. 17
0
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {

    String c = request.getParameter("type");
    String d = request.getParameter("q");

    Expert ce = new Expert();

    List result = ce.getTypes(c, d);

    getServletContext().setAttribute("SAVED_DATA", result);
    request.setAttribute("styles", result);

    RequestDispatcher view = request.getRequestDispatcher("result.jsp");
    view.forward(request, response);
  }
Esempio n. 18
0
  @Override
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws IOException, ServletException {
    // HttpSession sesh = request.getSession();
    // int id = 0;
    // id = (Integer) sesh.getAttribute("id");
    // if (id != 0) {
    RequestDispatcher dis = request.getRequestDispatcher("search.jsp");
    dis.forward(request, response);
    // }
    // else {
    // RequestDispatcher dis = request.getRequestDispatcher("login.jsp");
    // dis.forward(request, response);
    // }

  }
  @Override
  public void doPost(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    String nombreChofer = request.getParameter("nombreChofer");
    String telefonoChofer = request.getParameter("telefonoChofer");
    float salarioChofer = Float.parseFloat(request.getParameter("salarioChofer"));
    String choferID = request.getParameter("usernameChofer");

    Chofer c = new Chofer(nombreChofer, telefonoChofer, salarioChofer);
    new ListaChoferes().updateChofer(choferID, c);

    request.setAttribute("mensaje", "Chofer modificado de manera exitosa");
    String color = "10E214";
    request.setAttribute("coloreado", color);
    request.setAttribute("ListaDeChoferes", new ListaChoferes().obtenerChoferes());
    request.getRequestDispatcher("VerChoferes.jsp").forward(request, response);
  }
Esempio n. 20
0
 public void doPost(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   request.setCharacterEncoding("gb2312");
   String delete = request.getParameter("delete");
   Login loginBean = null;
   HttpSession session = request.getSession(true);
   try {
     loginBean = (Login) session.getAttribute("loginBean");
     boolean b = loginBean.getLogname() == null || loginBean.getLogname().length() == 0;
     if (b) response.sendRedirect("login.jsp"); // 重定向到登录页面
     LinkedList<String> car = loginBean.getCar();
     car.remove(delete);
   } catch (Exception exp) {
     response.sendRedirect("login.jsp"); // 重定向到登录页面
   }
   RequestDispatcher dispatcher = request.getRequestDispatcher("lookShoppingCar.jsp");
   dispatcher.forward(request, response); // 转发
 }
Esempio n. 21
0
 public void service(HttpServletRequest request, HttpServletResponse response)
     throws IOException, ServletException {
   try {
     Driver driver = new com.mysql.jdbc.Driver();
     DriverManager.registerDriver(driver);
     Connection connection =
         DriverManager.getConnection("jdbc:mysql://127.0.0.1/school", "root", "password");
     PreparedStatement preparedStatement =
         connection.prepareStatement("update student set name=?, per=? where roll=?");
     preparedStatement.setString(1, request.getParameter("name"));
     preparedStatement.setFloat(2, Float.parseFloat(request.getParameter("per")));
     preparedStatement.setInt(3, Integer.parseInt(request.getParameter("roll")));
     preparedStatement.execute();
     preparedStatement.close();
     connection.close();
   } catch (SQLException e) {
     e.printStackTrace();
   }
   RequestDispatcher requestDispatcher = request.getRequestDispatcher("/Display");
   requestDispatcher.forward(request, response);
 }
Esempio n. 22
0
  public void service(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {

    //	ServletContext context = getServletContext(); // per ricavare il MIME del file
    String url = null;
    try {
      GestisciFile gf = new GestisciFile(request);
      gf.getFile1();

      url = "upload.jsp";

      //         inserisco i dati nella request per poi inviarli alla pagina jsp
      //        request.setAttribute("contentType",context.getMimeType(f.getName()));
      //        request.setAttribute("path",f.getName());

      RequestDispatcher rd = request.getRequestDispatcher(url);
      rd.forward(request, response);
    } catch (Exception e) {
      e.printStackTrace();
    }
  }
 public void doGet(HttpServletRequest request, HttpServletResponse response) {
   try {
     String comment = request.getParameter("comment");
     int answerId = Integer.parseInt(request.getParameter("answer_id"));
     Connection connection = GlobalResources.getConnection();
     Statement s;
     s = connection.createStatement();
     PreparedStatement preparedStatement;
     PreparedStatement preparedStatement1;
     preparedStatement =
         connection.prepareStatement("insert into comment(comment,answer_id) values(?,?)");
     preparedStatement.setString(1, comment);
     preparedStatement.setInt(2, answerId);
     preparedStatement.executeUpdate();
     preparedStatement.close();
     connection.close();
     RequestDispatcher requestDispatcher;
     requestDispatcher = request.getRequestDispatcher("/studenthome.jsp");
     requestDispatcher.forward(request, response);
   } catch (Exception e) {
   }
 }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    assert emf != null; // Make sure injection went through correctly.
    EntityManager em = null;
    try {
      em = emf.createEntityManager();

      // query for all the persons in database
      List persons = em.createQuery("select p from Person p").getResultList();
      request.setAttribute("personList", persons);

      // Forward to the jsp page for rendering
      request.getRequestDispatcher("ListPerson.jsp").forward(request, response);
    } catch (Exception ex) {
      throw new ServletException(ex);
    } finally {
      // close the em to release any resources held up by the persistebce provider
      if (em != null) {
        em.close();
      }
    }
  }
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException {
    assert emf != null; // Make sure injection went through correctly.
    EntityManager em = null;
    try {

      // Get the data from user's form
      String id = (String) request.getParameter("id");
      String firstName = (String) request.getParameter("firstName");
      String lastName = (String) request.getParameter("lastName");

      // Create a person instance out of it
      Person person = new Person(id, firstName, lastName);

      // begin a transaction
      utx.begin();
      // create an em.
      // Since the em is created inside a transaction, it is associsated with
      // the transaction
      em = emf.createEntityManager();
      // persist the person entity
      em.persist(person);
      // commit transaction which will trigger the em to
      // commit newly created entity into database
      utx.commit();

      // Forward to ListPerson servlet to list persons along with the newly
      // created person above
      request.getRequestDispatcher("ListPerson").forward(request, response);
    } catch (Exception ex) {
      throw new ServletException(ex);
    } finally {
      // close the em to release any resources held up by the persistebce provider
      if (em != null) {
        em.close();
      }
    }
  }
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    HttpSession session = request.getSession(false);
    if (session == null) {
      response.sendRedirect("login.html");
      return;
    }

    String userName = (String) session.getAttribute("userName");
    if (isMissing(userName)) {
      response.sendRedirect("login.html");
      return;
    }
    String title = request.getParameter("title");
    String link = request.getParameter("link");
    String description = request.getParameter("description");
    session.setAttribute("title", title);
    session.setAttribute("link", link);
    session.setAttribute("description", description);
    String address = "WEB-INF/view/SaveBookmarkPage.jsp";
    String urlEncoding = response.encodeURL(address);
    RequestDispatcher dispatcher = request.getRequestDispatcher(urlEncoding);
    dispatcher.forward(request, response);
  }
 protected void processRequest(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   // retrieving values from input fields of matrixinput.jsp
   String sMatrix1 = request.getParameter("firstMatrix");
   String sMatrix2 = request.getParameter("secondMatrix");
   // Creating MatrixMultipler object
   MatrixMultiplier mm = new MatrixMultiplier();
   // Passing Strings to convertToObject() method of MatrixMultiplier
   // convertToObject() is used to convert strings into MatrixBean
   MatrixBean fMatrix = mm.convertToObject(sMatrix1);
   MatrixBean sMatrix = mm.convertToObject(sMatrix2);
   // passing MatrixBean’s objects to multiply() method of
   // MatrixMultiplier and receiving the product matrix in the form
   // of MatrixBean
   MatrixBean rMatrix = mm.multiply(fMatrix, sMatrix);
   // saving results in database
   mm.saveResult(rMatrix);
   // storing the product of matrices into request, so that it can be
   // retrieved on matrixresult.jsp
   request.setAttribute("product", rMatrix);
   // forwarding request to matrixresult.jsp
   RequestDispatcher rd = request.getRequestDispatcher("matrixresult.jsp");
   rd.forward(request, response);
 } // end processRequest()
  public void doGet(HttpServletRequest request, HttpServletResponse response)
      throws ServletException, IOException {
    response.setContentType("text/html");
    PrintWriter out = response.getWriter();
    out.println("<br><h4>we are getting data</h4>");
    String code = request.getParameter("code");
    out.println("<br>code: " + code);
    out.println("<br>");
    try {
      OAuthClientRequest requestOAuth =
          OAuthClientRequest.tokenLocation("https://graph.facebook.com/oauth/access_token")
              .setGrantType(GrantType.AUTHORIZATION_CODE)
              .setClientId(apiKey)
              .setClientSecret(secretKey)
              .setRedirectURI(redirectUri)
              .setCode(code)
              .buildBodyMessage();

      OAuthClient oAuthClient = new OAuthClient(new URLConnectionClient());

      GitHubTokenResponse oAuthResponse =
          oAuthClient.accessToken(requestOAuth, GitHubTokenResponse.class);
      accessToken = oAuthResponse.getAccessToken();
      expiresIn = oAuthResponse.getExpiresIn();
    } catch (OAuthSystemException ae) {
      ae.printStackTrace();
    } catch (OAuthProblemException pe) {
      pe.printStackTrace();
    }

    // out.println("<br>Access Token: " + accessToken);
    // out.println("<br>Expires In: " + expiresIn);

    try {
      FacebookClient facebookClient = new DefaultFacebookClient(accessToken);
      myFriends = facebookClient.fetchConnection("me/friends", User.class);
      myFeeds = facebookClient.fetchConnection("me/home", Post.class);

      for (User myFriend : myFriends.getData()) {
        f.add(myFriend.getName());
        out.println("<br>id: " + myFriend.getId() + " Name: " + myFriend.getName());
      }
      //	out.println("<br>");
      out.println("<br>f count: " + f.size());
    } catch (FacebookException e) {
      e.printStackTrace();
    }

    facebookDataBean fdb = new facebookDataBean();
    fdb.setName("zishan ali khan");
    HttpSession session = request.getSession();
    if (session != null) {
      session.setAttribute("myfdb", fdb);
      session.setAttribute("yourFriends", f);
      session.setAttribute("feeds", myFeeds);
      RequestDispatcher view = request.getRequestDispatcher("result.jsp");
      view.forward(request, response);
      f.clear();
      // out.println("<br>I am in");
    } else {
      // out.println("<br>Session Over");
    }
  }
Esempio n. 29
0
 protected void doGet(HttpServletRequest request, HttpServletResponse response)
     throws ServletException, IOException {
   request.getRequestDispatcher("/home.jsp").include(request, response);
 }
Esempio n. 30
0
  /**
   * Processes requests for both HTTP <code>GET</code> and <code>POST</code> methods.
   *
   * @param request servlet request
   * @param response servlet response
   */
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
      throws ServletException {
    assert emf != null; // Make sure injection went through correctly.
    EntityManager em = null;
    try {

      // begin a transaction
      utx.begin();
      // create an em.
      // Since the em is created inside a transaction, it is associsated with
      // the transaction

      em = emf.createEntityManager();

      // Get the data from user's form
      String titre = (String) request.getParameter("titre");
      Boolean peutEtreReemprunter = Boolean.valueOf(request.getParameter("peutEtreReemprunter"));
      String typeString = (String) request.getParameter("type");

      ProduitType type = null;
      for (ProduitType t : ProduitType.values()) {
        if (t.toString().equals(typeString)) {
          type = t;
        }
      }

      Date datePublication = new Date();

      String auteur1Txt = (String) request.getParameter("auteur1");
      String auteur2Txt = (String) request.getParameter("auteur2");
      String auteur3Txt = (String) request.getParameter("auteur3");

      Auteur auteur1 = null;
      try {
        auteur1 =
            (Auteur)
                em.createNamedQuery("findAuteur", Auteur.class)
                    .setParameter("nom", auteur1Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      Auteur auteur2 = null;
      try {
        auteur2 =
            (Auteur)
                em.createNamedQuery("findAuteur", Auteur.class)
                    .setParameter("nom", auteur2Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      Auteur auteur3 = null;
      try {
        auteur3 =
            (Auteur)
                em.createNamedQuery("findAuteur", Auteur.class)
                    .setParameter("nom", auteur3Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      List<Auteur> auteurs = new ArrayList<Auteur>();
      if (auteur1 != null) auteurs.add(auteur1);
      if (auteur2 != null) auteurs.add(auteur2);
      if (auteur3 != null) auteurs.add(auteur3);

      String genre1Txt = (String) request.getParameter("genre1");
      String genre2Txt = (String) request.getParameter("genre2");
      String genre3Txt = (String) request.getParameter("genre3");

      Genre genre1 = null;
      try {
        genre1 =
            (Genre)
                em.createNamedQuery("findGenre", Genre.class)
                    .setParameter("nom", genre1Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      Genre genre2 = null;
      try {
        genre2 =
            (Genre)
                em.createNamedQuery("findGenre", Genre.class)
                    .setParameter("nom", genre2Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      Genre genre3 = null;
      try {
        genre3 =
            (Genre)
                em.createNamedQuery("findGenre", Genre.class)
                    .setParameter("nom", genre3Txt)
                    .getSingleResult();
      } catch (NoResultException e) {

      }
      List<Genre> genres = new ArrayList<Genre>();
      if (genre1 != null) genres.add(genre1);
      if (genre2 != null) genres.add(genre2);
      if (genre3 != null) genres.add(genre3);

      // Create a person instance out of it
      Produit produit =
          new Produit(titre, peutEtreReemprunter, datePublication, auteurs, genres, type);

      // persist the person entity
      em.persist(produit);

      // commit transaction which will trigger the em to
      // commit newly created entity into database
      utx.commit();

      // Forward to ListPerson servlet to list persons along with the newly
      // created person above
      request.getRequestDispatcher("ListProduit").forward(request, response);
    } catch (Exception ex) {
      throw new ServletException(ex);
    } finally {
      // close the em to release any resources held up by the persistebce provider
      if (em != null) {
        em.close();
      }
    }
  }