2
\$\begingroup\$

This is a simple sort of array. The array (in fact I used ArrayList) is stored in default_list.txt file on server, all changes to it are made using servlets.

Add.java:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Add extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        addNumber(request);
        goToPage("/index.jsp", request, response);
    }

    private void goToPage(String address, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }

    public static void addNumber(HttpServletRequest request) {

        try {
            HttpSession session = request.getSession(true);
            String path = session.getServletContext().getRealPath("/")
                    + "default_list.txt";
            String path2 = session.getServletContext().getRealPath("/")
                    + "sorted_list.txt";
            int numbers = Integer.parseInt(request.getParameter("textarea1"));
            FileWriter writer = new FileWriter(path, true);
            writer.write(numbers + "\n");
            writer.flush();
            writer.close();

            List<String> buf = new ArrayList<String>();
            File sorted_list = new File(path2);
            sorted_list.delete();
            ArrayList<Integer> arr = new ArrayList<Integer>();
            FileReader filereader = new FileReader(path);
            BufferedReader br = new BufferedReader(filereader);
            String eachLine = br.readLine();
            while (eachLine != null) {
                arr.add(Integer.parseInt(eachLine));
                eachLine = br.readLine();
            }
            filereader.close();

            long timeout = System.currentTimeMillis();
            Collections.sort(arr);
            timeout = System.currentTimeMillis() - timeout;

            writer = new FileWriter(path2, true);
            for (int i = 0; i < arr.size(); ++i)
                buf.add(arr.get(i) + "\n");
            for (String record : buf) {
                writer.write(record);
            }
            if (arr.size() > 0) {
                writer.write("Sort method executed in " + timeout + " ms.\n");
            }
            writer.flush();
            writer.close();

        } catch (Exception e) {
        }
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

}

Delete.java:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Delete extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        addNumber(request);
        goToPage("/index.jsp", request, response);
    }

    private void goToPage(String address, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }

    public static void addNumber(HttpServletRequest request) {

        try {
            HttpSession session = request.getSession(true);
            List<String> buf = new ArrayList<String>();
            List<String> buf2 = new ArrayList<String>();
            String path = session.getServletContext().getRealPath("/")
                    + "default_list.txt";
            String path2 = session.getServletContext().getRealPath("/")
                    + "sorted_list.txt";

            ArrayList<Integer> arr = new ArrayList<Integer>();
            FileReader filereader = new FileReader(path);
            BufferedReader br = new BufferedReader(filereader);
            String eachLine = br.readLine();
            while (eachLine != null) {
                arr.add(Integer.parseInt(eachLine));
                eachLine = br.readLine();
            }
            filereader.close();

            if (arr.size() > 0) {
                arr.remove(arr.size() - 1);
                File path_buf = new File(path);
                path_buf.delete();

                FileWriter writer = new FileWriter(path, true);
                for (int i = 0; i < arr.size(); ++i)
                    buf.add(arr.get(i) + "\n");
                for (String record : buf) {
                    writer.write(record);
                }
                buf.clear();
                arr.clear();
                writer.flush();
                writer.close();
            }

            File sorted_list = new File(path2);
            sorted_list.delete();
            filereader = new FileReader(path);
            br = new BufferedReader(filereader);
            eachLine = br.readLine();
            while (eachLine != null) {
                arr.add(Integer.parseInt(eachLine));
                eachLine = br.readLine();
            }
            filereader.close();
            long timeout = System.currentTimeMillis();
            Collections.sort(arr);
            timeout = System.currentTimeMillis() - timeout;
            FileWriter writer = new FileWriter(path2, true);
            for (int i = 0; i < arr.size(); ++i)
                buf.add(arr.get(i) + "\n");
            for (String record : buf) {
                writer.write(record);
            }
            if (arr.size() > 0) {
                writer.write("Sort method executed in " + timeout + " ms.\n");
            }
            writer.flush();
            writer.close();

        }

        catch (Exception e) {
        }
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

}

Erase.java:

import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Erase extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        addNumber(request);
        goToPage("/index.jsp", request, response);
    }

    private void goToPage(String address, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }

    public static void addNumber(HttpServletRequest request) {

        try {
            HttpSession session = request.getSession(true);

            String path = session.getServletContext().getRealPath("/")
                    + "default_list.txt";
            File list = new File(path);
            list.delete();
            FileWriter writer = new FileWriter(path, true);
            writer.flush();
            writer.close();

            path = session.getServletContext().getRealPath("/")
                    + "sorted_list.txt";
            list = new File(path);
            list.delete();
            writer = new FileWriter(path, true);
            writer.flush();
            writer.close();
        } catch (Exception e) {
        }
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

}

Generate.java:

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Generate extends HttpServlet {

    protected void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {

        addNumber(request);
        goToPage("/index.jsp", request, response);
    }

    private void goToPage(String address, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext()
                .getRequestDispatcher(address);
        dispatcher.forward(request, response);
    }

    public static void addNumber(HttpServletRequest request) {

        try {
            HttpSession session = request.getSession(true);
            List<String> buf = new ArrayList<String>();
            String path = session.getServletContext().getRealPath("/")
                    + "default_list.txt";
            String path2 = session.getServletContext().getRealPath("/")
                    + "sorted_list.txt";
            try {
                short amount = Short.parseShort(request
                        .getParameter("textarea2"));
                Random randomGenerator = new Random();
                FileWriter writer = new FileWriter(path, true);
                for (int i = 0; i < amount; ++i)
                    buf.add(randomGenerator.nextInt(100) + "\n");
                for (String record : buf) {
                    writer.write(record);
                }
                writer.flush();
                writer.close();
                buf.clear();

                File sorted_list = new File(path2);
                sorted_list.delete();
                ArrayList<Integer> arr = new ArrayList<Integer>();
                FileReader filereader = new FileReader(path);
                BufferedReader br = new BufferedReader(filereader);
                String eachLine = br.readLine();
                while (eachLine != null) {
                    arr.add(Integer.parseInt(eachLine));
                    eachLine = br.readLine();
                }
                filereader.close();
                long timeout = System.currentTimeMillis();
                Collections.sort(arr);
                timeout = System.currentTimeMillis() - timeout;
                FileWriter writer2 = new FileWriter(path2, true);
                for (int i = 0; i < arr.size(); ++i)
                    buf.add(arr.get(i) + "\n");
                for (String record : buf) {
                    writer2.write(record);
                }
                if (arr.size() > 0) {
                    writer2.write("Sort method executed in " + timeout
                            + " ms.\n");
                }
                writer2.flush();
                writer2.close();

            } catch (Exception e) {
            }
            ;
        } catch (Exception e) {
        }
    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

}

index.jsp:

<%@ page import="java.util.*" %>
<%@ page import="java.io.*" %>
<HTML>
<HEAD>
<TITLE>Sample sort</TITLE>
</HEAD>
<BODY>
<H1>JSP/Servlet sorting sample.</H1>
<FORM ACTION="list.add" METHOD="POST">
  Input a number:
  <input type="text" name="textarea1">
  <INPUT TYPE="SUBMIT" VALUE="Add">
</form>
<FORM ACTION="list.gen" METHOD="POST">
  Enter amount of numbers to generate:
  <input type="text" name="textarea2">
  <input type="SUBMIT" value="Generate">
</FORM>
<table>
<tr>

<td><form action="list.del" method="POST">
  <input type="SUBMIT" value="Delete last">
</form></td>
<td><form action="list.erase" method="POST">
  <input type="SUBMIT" value="Clear">
</form></td>
  </tr>
</table>
<table width="500">
<tr>
<td width="250">
Your list:
<br>
<br>    
<%
String file = application.getRealPath("/") + "default_list.txt";
FileReader filereader = new FileReader(file);
BufferedReader br = new BufferedReader(filereader);
String eachLine = br.readLine();
while (eachLine != null) {
out.println(eachLine);
out.println("<br>");
eachLine = br.readLine();
}
filereader.close();       
%>
</td>
<td width="250">
Sorted list:
<br>
<br>
<%
String file2 = application.getRealPath("/") + "sorted_list.txt";
FileReader filereader2 = new FileReader(file2);
BufferedReader br2 = new BufferedReader(filereader2);
String eachLine2 = br2.readLine();
while (eachLine2 != null) {
out.println(eachLine2);
out.println("<br>");
eachLine2 = br2.readLine();
}
filereader2.close();       
%>
</td>
  </tr>
</table>
</BODY>
<HTML>

Alternatively the whole project is here.fcjrg5nms979in9

What I am asking for is:

  1. Did I do it overally properly? Some big mistakes here and there maybe?
  2. What would you advice me to change to make it better? (safer, faster, simpler)
\$\endgroup\$
2
\$\begingroup\$

Browsed quickly and here are a few pointers

1) Separation of Concerns (SoC). Let your view (jsp) handle the rendering, Controller (servlet) handle the flow of the application, and all your processing in another set of classes. This would be the basics of MVC. Here is the wikipedia definition for a simple layout.

Model - The model is a collection of Java classes that form a software application intended to store, and optionally separate, data. A single front end class that can communicate with any user interface (for example: a console, a graphical user interface, or a web application).

View - The view is represented by a Java Server Page, with data being transported to the page in the HttpServletRequest or HttpSession.

Controller - The Controller servlet communicates with the front end of the model and loads the HttpServletRequest or HttpSession with appropriate data, before forwarding the HttpServletRequest and Response to the JSP using a RequestDispatcher.

2) In your JSP don't use scriptlets. Consider learning jstl before you get in the habit of using scriptlets. Why are scriptlets bad? Read this detailed answer

3) All of your servlets have the methods goToPage(), doGet(), doPost(), and ProcessRequest(). This is a lot to re-write each time you create a new servlet. Consider creating an abstract class between your servlets and HttpServlet which defines these methods.

public abstract class BaseServlet extends HttpServlet{
    //You must define this 
    protected abstract void processRequest(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException;

    protected void goToPage(String address, HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        RequestDispatcher dispatcher = getServletContext().getRequestDispatcher(address);
        dispatcher.forward(request, response);

    }

    protected void doGet(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }

    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        processRequest(request, response);
    }
}

Now all you have to do is extend BaseServlet instead of HttpServlet and you have the methods available to you without the need to re-write. If you were to find a bug later, or want to rewrite this now you only have to look in one place instead of changing it in each servlet.

| improve this answer | |
\$\endgroup\$
  • \$\begingroup\$ Thanks, very very big thanks! I simply cant have any more questions now :) Thanks again! \$\endgroup\$ – Chelios Mar 8 '12 at 15:42
  • 1
    \$\begingroup\$ @Chelios: If the answer has helped or solved your problem. It is suggested to Mark as Answered. \$\endgroup\$ – Hardik Mishra Mar 9 '12 at 9:11
  • \$\begingroup\$ Uhm, sorry but how do I do it? \$\endgroup\$ – Chelios Mar 9 '12 at 12:13
  • \$\begingroup\$ meta.stackexchange.com/questions/5234/… \$\endgroup\$ – Sean Mar 9 '12 at 13:30

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy