[ Andrej013 @ 19.02.2013. 08:16 ] @
Napravio sam jednostavni dinamicki web projekat za registraciju i logovanje na sajt, gde za registraciju sa jsp stranice servletu prosledjujem username, password, adresu, godinu rodjenja i slicno.
Servlet se tada kaci na localhoast server i preko ObjectOutputStreama salje request objekat sa parametrima(npr parametri su String komanda i objekat Osoba sa gore navedenim poljima). server thread, na osnovu komande, proverava da li treba da registruje korisnika ili da se loguje. proverava da li username i password vec postoji u bazi podataka i vraca servletu informaciju da li je registracija/logovanje uspesno i ako nije, zasto nije.

sve to fino funkcionise, ali bih sada hteo da dodam mogucnost da logovani korisnik uploaduje sliku kada se loguje. na netu sam nasao neki tutorijal sa kodom gde je sve objasnjeno kako da se uploaduje slika preko servleta i to funkcionise, ali me zanima, kako to da odradim preko servera sa multithreadingom? sta da posaljem na objectOutputStream? cini mi se da je upload fajlova dosta zeznutiji od obicnog logovanja, pisanja i citanja iz baze podataka.
da li gresim? gde da pocnem?

Servlet za registraciju:
Code:


       String hostname = "localhost";
        InetAddress addr = InetAddress.getByName(hostname);
        int TCP_PORT = 9000;  
        Socket socket = new Socket(addr, TCP_PORT);// ip & port of server. in this moment the request is detected on server and socket is made for thread
        
        //make in and out streams for communication with the server
        ObjectOutputStream out=new ObjectOutputStream(socket.getOutputStream());
        ObjectInputStream in=new ObjectInputStream(socket.getInputStream());
        
        REQ req=new REQ();
        req.getParameters().put("command","register");
        req.getParameters().put("person",person);
        
        //write to Server
        out.writeObject(req);
        out.flush();
        Answer answer=new Answer();
        try{
            answer=(Answer)in.readObject();
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        }
        System.out.println("message from server: "+answer.getMessage());


Server Thread,
Code:
private Socket sock;
    // stream za slanje poruka
    private ObjectOutputStream out;
    // stream za prijem poruka
    private ObjectInputStream in;

    private SessionFactory sessionFactory;
    private Session session;
    
    public ServerThread(Socket sock){
        this.sock=sock;
        try {
            in = new ObjectInputStream(sock.getInputStream());    
            out = new ObjectOutputStream(sock.getOutputStream());
            sessionFactory=new Configuration().configure().buildSessionFactory();
            session = sessionFactory.openSession();
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }
    
    public void run() {
        System.out.println("run");
        try {
            //request reading
            REQ req=(REQ)in.readObject();
            System.out.println("OBJECT read");
            String command=(String)req.getParameters().get("command");
            
            if(command.equals("register")){
                Person P = null;
                P =(Person)req.getParameters().get("person");
                //write the data in the DB
                session.beginTransaction();
                session.save(P);
                session.getTransaction().commit();
                session.close();    
                
                Answer answer=new Answer();
                answer.setMessage("everything went fine with "+P.getUsername());
                answer.setFlag(1);
                answer.setPerson(P);
                //send the answer to the client
                out.writeObject(answer);
                out.flush();
                out.reset();
            }
            
            if(command.equals("login")){
                System.out.println("in login part of the thread");
                Person person=new Person();
                String username=(String)req.getParameters().get("username");
                String password=(String)req.getParameters().get("password");
                session.beginTransaction();
                person=(Person)session.get(Person.class, username);
                session.close();
                
                if(person.getPassword().equals(password)){
                    person.setLoggedIn(true);
                    Answer answer=new Answer();
                    answer.setMessage("everything went fine with "+person.getUsername());
                    answer.setFlag(1);
                    answer.setPerson(person);
                    System.out.println(answer.getMessage());
                    //send the answer to the client
                    out.writeObject(answer);
                    out.flush();
                    out.reset();
                }else{
                    person.setLoggedIn(false);
                    Answer answer=new Answer();
                    answer.setMessage("wrong password from user: "+person.getUsername());
                    answer.setFlag(0);
                    answer.setPerson(person);
                    System.out.println(answer.getMessage());
                    //send the answer to the client
                    out.writeObject(answer);
                    out.flush();
                    out.reset();
                }
                
            }
            //end of client-server communication
            in.close();
            out.close();
            sock.close();
        }


p.s. ne znam da li da okacim ceo kod-ima ga bas dosta pa nisam hteo da zatrpavam
pp.s. nisam siguran da sam na dobrom mestu kreirao sesiju za hibernate(u konstruktoru ServerThread-a)? kako je u pitanju 'skup' objekat, hteo sam da ga kreiram samo jednom pa posle da se koristi taj isti, ali niti sam siguran da sam to uspeo niti sam siguran da je to dobro resenje.
govorim o ovom delu koda:
Code:

        sessionFactory=new Configuration().configure().buildSessionFactory();
    session = sessionFactory.openSession();

[ Andrej013 @ 19.02.2013. 08:23 ] @
ovo bi bio servlet koji obavlja upload:
Code:

@WebServlet("/TestServlet")
public class TestServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    private static final String UPLOAD_DIRECTORY = "upload";
    private static final int THRESHOLD_SIZE = 1024 * 1024 * 3;    // 3MB
    private static final int MAX_FILE_SIZE = 1024 * 1024 * 40;    // 40MB
    private static final int REQUEST_SIZE = 1024 * 1024 * 50;    // 50MB
    
    /*
     *That checks if the request contains upload data (recognized by enctype="multipart/form-data" 
     *of the upload form). If not, we exit the method, otherwise we continue.
     */
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // TODO Auto-generated method stub
        if (!ServletFileUpload.isMultipartContent(request)) {
            return;
        }
        
        /*
         * The DiskFileItemFactory class manages file content either in memory or on disk. 
         * We call setSizeThreshold() method to specify the threshold above which files 
         * will be stored on disk, under the directory specified by the method setRepository(). 
         * In the above code, we specify the temporary directory available for Java programs. 
         * Files are stored temporarily in that directory and they will be deleted. 
         * So we need to copy the files from the temporary directory to a desired location.

         * The ServletFileUpload is the main class that handles file upload by parsing the request 
         * and returning a list of file items. It is also used to configure the maximum size of 
         * a single file upload and maximum size of the request, by the methods setFileSizeMax()
         * and setSizeMax() respectively.
         */
        DiskFileItemFactory factory = new DiskFileItemFactory();
        factory.setSizeThreshold(THRESHOLD_SIZE);
        factory.setRepository(new File(System.getProperty("java.io.tmpdir")));
        ServletFileUpload upload = new ServletFileUpload(factory);
        upload.setFileSizeMax(MAX_FILE_SIZE);
        upload.setSizeMax(REQUEST_SIZE);
        
        
        
        /*
         * Because upload files are stored temporarily under a temporary directory, 
         * we need to save them under another directory permanently. The following code 
         * creates a directory specified by the constant UPLOAD_DIRECTORY under web 
         * application’s root directory, if it does not exist:
         */
        //making a directory with unique name: username+email address
        HttpSession httpSession=request.getSession();
        Person person=(Person)httpSession.getAttribute("loggedUser");
        System.out.println(person.getEmail());
        
        String uploadPath = getServletContext().getRealPath("")
                + File.separator + UPLOAD_DIRECTORY;
        uploadPath="C:\\Users\\Andrej\\Desktop\\Java Recourses\\WorkspaceLearn" +
                "\\Ask\\data\\"+person.getUsername()+person.getEmail();
        File uploadDir = new File(uploadPath);
        if (!uploadDir.exists()) {
            uploadDir.mkdir();
        }
        
        
        //And this is the most important code: parse the request to save upload data to a 
        //permanent file on disk:
        String fullPath="";
        try {
            // parses the request's content to extract file data
            List formItems = upload.parseRequest(request);
            Iterator iter = formItems.iterator();
             
            // iterates over form's fields
            while (iter.hasNext()) {
                FileItem item = (FileItem) iter.next();
                // processes only fields that are not form fields
                if (!item.isFormField()) {
                    String fileName = new File(item.getName()).getName();
                    String filePath = uploadPath + File.separator + fileName;
                    File storeFile = new File(filePath);
                    fullPath=filePath;
                    // saves the file on disk
                    item.write(storeFile);
                }
            }
            /*
             * The parseRequest() method of ServletFileUpload class returns a list of form items 
             * which will be iterated to identify the item (represented by a FileItem object) 
             * which contains file upload data. The method isFormField()of FileItem class checks 
             * if an item is a form field or not. A non-form field item contains upload data, 
             * thus the check:
             * if (!item.isFormField()) {}
             */
            request.setAttribute("message", "Upload has been done successfully!");
        } catch (Exception ex) {
            request.setAttribute("message", "There was an error: " + ex.getMessage());
        }
        /*HttpSession session=request.getSession();
        session.setAttribute("image", fullPath);
        System.out.println(fullPath);*/
        request.setAttribute("image", fullPath);
        getServletContext().getRequestDispatcher("/uploadSuccessfull.jsp").forward(request, response);
    }

}


inace, sve radim u eclipse-u uz tomcat 7