How do you make a habit of studying?(Originally Asked on Quora)


The first thing to bring up the habit in whatever you do is by identifying the purpose behind doing that.
For example, if you want to make the habit of studying you must first identify why you want to study?
What’s your goal? Do you want to study just because your parents want you to?
Or to get a job? Or to answer all the curiosity about the world around you by reading or studying them?

Let’s discuss first what is studying and why it’s so important?
Studying is a practice of putting an effort to make yourself aware of everything that exists in this universe and by doing that we human being make our life easier.
For example, you need fire to keep yourself warm in a cold night so you must study the behavior of fire like how to create it, how to control it and what are the things where you can make use of it.
For approximately 200,000 years the human race has been evolving by studying such things. We were just a bunch of apps and now we have evolved into a civilized and modern society, this transformation was only possible because we studied the property, pattern, behavior of everything we could in this universe and made best possible use of it to evolve ourselves.

Well the universe and everything that exists in it are pretty must huge area to study and sure it would not be possible for an individuals to study all of it and that too in approximately 100 years of lifespan, that’s why we started storing our observations and finding into paper and then over years when we had huge amount of information we created different tools to store and extract this information.
One of the most widely used tools was the book. (Book is a written or printed information arranged and indexed using page numbers and categories by chapters)   
Thanks to the group of wise men who all created the syllabus, in fact, the entire education system where we can gain access to these information step by step from standard zero to infinity. The whole purpose of the education system was to formalize the information in an effective way so that it can be passed to our next generation and they could easily learn all those things which have already been discovered.
So now you know why you need to study and attend schools, it’s simply because schooling system has been designed to give you the information about the world in a manner which can be easily understood by you at your age (from age 5 to ….. till your lifetime).
You must also understand that you cannot study the whole thing that exists in this universe that’s why you need to identify your area of interest and narrow down the scope of studying to a particular field e.g. engineering, medical science, economics, history or any other.
You are not meant to study just because you have to pass the exam or score good marks. Exams and marks are just the way of evaluating yourself that how good you have studied the book or subject.
Always remember the real purpose of studying which is to know things, to satisfy your curiosity and at the end to discover something out of it.
Once you have the curiosity to know the interesting facts around the universe and you are also willing to bring discipline into it. The job is done! It will become your habit automatically.  


Which courses do people study on the IT faculty? (Asked in Quora)

There are various sets of courses one can learn to be effective IT Faculty. I will try to explain few by categorizing it into 2 basic types which are the most important part of IT engineering.
 
1.) Core of engineering (Not just IT): Yes its mathematics and full of complex calculations 
These are the subjects which helps you to gain core knowledge of engineering which means it can sharpen your analytical skills, problem solving skills and many other stuff.
E.g.: one has to first know how the addition of two numbers works before writing a program which can take 2 numbers from user as input and add them together to display the result.
After all IT was first developed to remove the burden of doing all complex calculation (Scientific calculation, Income tax, Banking, complex business rules) from our life by providing us a simple application which could do all the calculation for us. Later on it developed to do much more things than it could do initially like storing/Transferring and displaying useful informations, gaming , animation and much more.
Following are the subjects which belongs to this category:
Mathematical Logic: Propositional Logic; First Order Logic.
Probability: Conditional Probability; Mean, Median, Mode and Standard Deviation; Random Variables; Distributions; uniform, normal, exponential, Poisson, Binomial.
Set Theory & Algebra: Sets; Relations; Functions; Groups; Partial Orders; Lattice; Boolean Algebra.
Combinatorics: Permutations; Combinations; Counting; Summation; generating functions; recurrence relations; asymptotics.
Graph Theory: Connectivity; spanning trees; Cut vertices & edges; covering; matching; independent sets; Colouring; Planarity; Isomorphism.
Linear Algebra: Algebra of matrices, determinants, systems of linear equations, Eigen values and Eigen vectors.
Numerical Methods: LU decomposition for systems of linear equations; numerical solutions of non-linear algebraic equations by Secant, Bisection and Newton-Raphson Methods; Numerical integration by trapezoidal and Simpson’s rules.
Calculus: Limit, Continuity & differentiability, Mean value Theorems, Theorems of integral calculus, evaluation of definite & improper integrals, Partial derivatives, Total derivatives, maxima & minima.
 
Studying these subjects are very crucial for one wanting to be an IT expert as it teaches you how to solve a problem using mathematical thesis.
 
2.) Core of Computer Science/IT:
These are the real IT stuff which helps you to talk to machines (like computers, AC, TV, smart phones and many more) in their own language using the program you write and install into them. Binary is the most effective language in the history of commuter science which was chosen to be used as the foundation of computer science (“0” or “1”, “on” or “off”, “Dead or alive”, “something is there” or “Something is not there”), it was due to the fact it easy to understand, Non- complex and can be used to represent numbers, characters, instructions etc. So before you touch this section make sure you know the binary system well.
 
In this section of the studies you will learn to transform a real time algorithm/theory/Calculations/Solutions into a program/instructions installable into a machine.
Following are the subjects which belongs to this category:
Digital Logic: Logic functions, Minimization, Design and synthesis of combinational and sequential circuits; Number representation and computer arithmetic (fixed and floating point).
Computer Organization and Architecture: Machine instructions and addressing modes, ALU and data-path, CPU control design, Memory interface, I/O interface (Interrupt and DMA mode), Instruction pipelining, Cache and main memory, Secondary storage.
Programming and Data Structures: Programming in C; Functions, Recursion, Parameter passing, Scope, Binding; Abstract data types, Arrays, Stacks, Queues, Linked Lists, Trees, Binary search trees, Binary heaps.
Algorithms: Analysis, Asymptotic notation, Notions of space and time complexity, Worst and average case analysis; Design: Greedy approach, Dynamic programming, Divide-and-conquer; Tree and graph traversals, Connected components, Spanning trees, Shortest paths; Hashing, Sorting, Searching. Asymptotic analysis (best, worst, average cases) of time and space, upper and lower bounds, Basic concepts of complexity classes – P, NP, NP-hard, NP-complete.
Theory of Computation: Regular languages and finite automata, Context free languages and Push-down automata, Recursively enumerable sets and Turing machines, Undecidability.
Compiler Design: Lexical analysis, Parsing, Syntax directed translation, Runtime environments, Intermediate and target code generation, Basics of code optimization.
Operating System: Processes, Threads, Inter-process communication, Concurrency, Synchronization, Deadlock, CPU scheduling, Memory management and virtual memory, File systems, I/O systems, Protection and security.
Databases: ER-model, Relational model (relational algebra, tuple calculus), Database design (integrity constraints, normal forms), Query languages (SQL), File structures (sequential files, indexing, B and B+ trees), Transactions and concurrency control.
Information Systems and Software Engineering: information gathering, requirement and feasibility analysis, data flow diagrams, process specifications, input/output design, process life cycle, planning and managing the project, design, coding, testing, implementation, maintenance.
Computer Networks: ISO/OSI stack, LAN technologies (Ethernet, Token ring), Flow and error control techniques, Routing algorithms, Congestion control, TCP/UDP and sockets, IP(v4), Application layer protocols (icmp, dns, smtp, pop, ftp, http); Basic concepts of hubs, switches, gateways, and routers. Network security – basic concepts of public key and private key cryptography, digital signature, firewalls.
Web technologies: HTML, XML, basic concepts of client-server computing.

Access levels and Static Keyword in Java


Accessing Members of class:
Java enforces you to encapsulate each and every attribute and methods inside a template called class (can be Abstract class, interface etc) that means these attributes and methods are not visible to the outside world.  
How do we access these variables or methods if it is encapsulated?
We will answer this question latter in this discussion.
Access levels for class members:
Class level access (Full Access):

  •  Each and every members of a class are completely visible within the same class.
  •  In fact there is no way to hide any of the members from being used by the other members of same class.
Inheritance (Limited Access):

  •  If you want to use any of the variable or method which is a member of other class you may extend that class.
  • Each and every public, protected and default (same package) member of the super class can be called in sub class.
  • In fact all of these members become part of subclass.
Create an Object (has-a / uses-a relationship):

  •  Declare the object as class variable (has-a relationship).
  • Declare the object as local variable (uses-a relationship).
  •  Through this object one can access all the non private members of that class using dot operator.
  • Eg :
class A{
    static int variable1;
      static void m1(){}
        }

            Now to access these members in another class say class B:
              class B{
                void m2()
                  {
                          A.variable1;
                            A.m1();
                        }
                          }
                          Declare that member as static:
                          •  As soon as you declare a member as static it becomes global.
                          •   There is no need of creation and object or inherit the containing class.
                          • Just use the class name and dot operator.
                          What does static keyword do?
                          •   It makes the members (methods and variables) of a class independent from object creation and puts these things in global memory at runtime.
                          •  That means same copy of static variable and method are shared by all objects of that type at runtime .object does not receive a separate copy of static members at runtime.
                          •  Eg: Think in this way-
                          Question:  How does you program starts execution?
                          Answer:     Your answer is main method.
                          Question:  But how does the JVM gets access to the main method without creating object of the                           class which contains main().
                          v  Ok fine JVM knows the prototype of main method so it searches for the main() method prototype and starts execution .
                          v  But any how JVM has to gain access to the main method which is residing inside any of class in application isn’t it?
                          v  As we know everything in java resides in a class so JVM should not have access to a class member without creating object of that type then how does it starts execution.
                          Answer: Because main() is static and as we dont need to create the object of the class to access any of its statics members/methods JVM does not find any issue on executing the main() method.

                          Exception Handling


                          Exception
                          An exception is a problem that occurs during the execution of a program and disturbs the normal flow of execution.
                          It can occur due to following reasons:

                          • A user has entered invalid data.
                          • A file that needs to be opened cannot be found.
                          • A network connection has been lost in the middle of communications, or the JVM has run out of memory.

                          Types of Exceptions:

                          1. Checked exceptions:
                            • Typically a user error or a problem that cannot be foreseen by the programmer.
                            • For example, if a file is to be opened, but the file cannot be found, an exception occurs.
                            • These exceptions cannot simply be ignored at the time of compilation.
                            • Must be handled using try catch block and throws clause with method declaration.
                            • User Exception.
                          2. Runtime exceptions:
                            • The exceptions that probably could have been avoided by the programmer.
                            •  Runtime exceptions are ignored at the time of compilation.
                            • No need to declare with throws clause.
                            • Example division by zero and invalid array indexing.
                            • Programmer Exception.
                          3. Errors:

                            • The problems that arise beyond the control of the user or the programmer.
                            • Errors are typically ignored in code because one can rarely do anything about an error.
                            • For example, if a stack overflow occurs, an error will arise. They are also ignored at the time of compilation.
                            •  Hardware Exception.
                            • Runtime exception and Errors together called as unchecked exception as they need not to be checked at compile time.

                          Exception Hierarchy:


                          Unchecked RuntimeException Subclasses:

                          ·         ArithmeticException :                               Arithmetic error, such as divide-by-zero.
                          ·         ArrayIndexOutOfBoundsException:    Array index is out-of-bounds.
                          ·         ArrayStoreException:                               Assignment to an array element of an
                                                                                                                 incompatible type.
                          ·         ClassCastException:                                   Invalid cast.
                          ·         IllegalArgumentException:                      Illegal argument used to invoke a method.
                          ·         IndexOutOfBoundsException:               Some type of index is out-of-bounds.
                          ·         NegativeArraySizeException:                Array created with a negative size.

                          Java’s Checked Exceptions

                          ·         ClassNotFoundException: Class not found.
                          ·         CloneNotSupportedException: Attempt to clone an object that does not implement the Cloneable interface.
                          ·         IllegalAccessException:  Access to a class is denied.
                          ·         InstantiationException:  Attempt to create an object of an abstract class or interface.
                          ·         InterruptedException: One thread has been interrupted by another thread.
                          ·         NoSuchFieldException:  A requested field does not exist.
                          ·         NoSuchMethodException:  A requested method does not exist.
                          Handling Exception:
                          If an exception occurs that is not caught anywhere, the program will terminate and print a message to the console, giving the type of the exception and a stack trace.
                          To catch an exception, you set up a try/catch block. The simplest form of the try block is as follows:

                          try
                          {
                          code
                          more code
                          more code
                          }
                          catch (ExceptionType e)
                          {
                          handler for this type
                          }
                          *      If any of the code inside the try block throws an exception of the class specified in the catch clause, then
                          1.      The program skips the remainder of the code in the try block;
                          2.      The program executes the handler code inside the catch clause.
                          *      If none of the code inside the TRy block throws an exception, then the program skips the catch clause.
                          *      If any of the code in a method throws an exception of a type other than the one named in the catch clause, this method exits immediately. (Hopefully, one of its callers has already coded a catch clause for that type.)

                          Catching Multiple Exceptions
                          You can catch multiple exception types in a try block and handle each type differently. You use a separate catch clause for each type as in the following example:

                          try
                          {
                          code that might throw exceptions
                          }
                          catch (MalformedURLException e1)
                          {
                          handler code for malformed URLs
                          }
                          catch (UnknownHostException e2)
                          {
                          handler code for unknown hosts
                          }
                          catch (IOException e3)
                          {
                          handler code  for all other I/O problems
                          }


                          Re-throwing and Chaining Exceptions
                          You can re throw an exception in a catch clause. Typically, you do this because you want to change the exception type.
                          Eg:
                          try
                          {
                          code causes exception
                          }
                          catch (SQLException e)   // new exception object  created and re thrown in catch block.
                          {
                          throw new ServletException("database error: " + e.getMessage());
                          }

                          The finally Clause
                          *      When your code throws an exception, it stops processing the remaining code in your method and exits the method.
                          *      This is a problem if the method has acquired some local resource that only it knows about and if that resource must be cleaned up.
                          *      The code in the finally clause executes whether or not an exception was caught.

                          Eg:
                          try
                          {
                          // 1
                          code that might throw exceptions
                          // 2
                          }
                          catch (IOException e)
                          {
                          // 3
                          show error dialog
                          // 4
                          }
                          finally
                          {
                          // 5
                          code which will be executed regardless of exception occurs or not.
                          }
                          The throws clause
                          When you write your own methods, you don't have to advertise every possible throwable object that your method might actually throw. To understand when (and what) you have to advertise in the throws clause of the methods you write, keep in mind that an exception is thrown in any of the following four situations:
                          1.      You call a method that throws a checked exception, for example, the FileInputStream constructor.
                          2.      You detect an error and throw a checked exception with the throw statement (we cover the tHRow statement in the next section).
                          3.      You make a programming error, such as a[-1] = 0 that gives rise to an unchecked exception such as an ArrayIndexOutOfBoundsException.
                          4.      An internal error occurs in the virtual machine or runtime library.
                          If either of the first two scenarios occurs, you must tell the programmers who will use your method about the possibility of an exception. Why? Any method that throws an exception is a potential death trap. If no handler catches the exception, the current thread of execution terminates.
                          User Defined Exception Classes
                          Step 1: Create an exception class (extend exception class or child class of exception)
                          class MyException extends Exception
                          {
                                public Exception(String msg)
                             {
                                super(msg);
                             }
                          }
                          Step 2: Throw your very own exception type.
                          String readData(BufferedReader in) throws MyException
                          {
                             . . .

                             while (. . .)
                             {
                                if (ch == -1) // EOF encountered
                                {
                                   if (n < len)
                                      throw new MyException ();
                                }
                                . . .
                             }
                             return s;
                          }

                          Five minds for the future

                                
                          I happened to see in the book stall, "Five Minds for the Future" written by Howard Gardner. Let us remember, this book is being published, 25 centuries after Lord Buddha?s enlightenment. My curiosity and desire increased to go into the details of this book; particularly in the today?s world environment of social conflicts, political violence and impact of globalization and above all the youth of the world have a question where their lives? are heading. I am convinced with the multi-religious background of our nation, the future definitely needs these capacities to be built in the minds of the youth. I studied the five minds of the future, let me describe based on my understanding:  


                          1. Disciplinary mind:
                           Disciplinary minds require the mastery of major schools of thought that may include science, mathematics, history and religion. Apart from this the disciplinary mind has to be enriched with expertise in at least one professional field. Research confirms that it takes up to 10 years to master a discipline. This mind also knows how to work steadily overtime to improve skill and understand.  

                          2.Synthesizing mind:
                           What is needed is the ability to integrate ideas from different disciplines or spheres into an integrated system and communicate the synthesized thoughts. With the increasing volume of information in the present day world, capacity to synthesize assumes great importance.  

                          3. Creating mind:
                          It is essential to build capacity to uncover and create solutions to new problems, questions and phenomena. For examples on creativity, in general we look for leaders, rather than managers.  
                          It puts forth new ideas, poses, familiar questions and arrives at unprecedented answers. The creating mind seeks to remain at least one step ahead of even the most sophisticated computers and robots. I understand that most of the computers of the future and accessories will be micro sized, wearable and will have wireless communication with each other. Moderately priced PCs capable of performing about a billion calculations per second today will be able to perform about a trillion calculations per second within next 10 years. It is predicted that by 2019, the computational ability of an ordinary PC would exceed the capability of human brain. By 2029, the capability of a normal PC would be around 1000 times that of the human brain. My view is that definitely the creating mind of the human being will always be superior to the most powerful computers in the horizon.  
                          4.Respectful mind:
                           It is a uniquely developed mind, a mature mind that has awareness and appreciation for differences among human beings. The capacity built in the respectful mind, leads to understand other persons on their own terms with mutual trust. In the world where we are, all interlinked and need to maintain working relationship, intolerance is no longer a viable option. 

                          5. Ethical mind:
                          It is indeed a built-in-capacity for fulfilling once responsibility as a worker and as a citizen simultaneously, It will essentially lead to "work with integrity and succeed with integrity".
                          The mind conceptualizes how workers can serve purpose beyond self interest and how citizens can work unselfishly to improve the lot of all. The ethical mind then acts on the basis of these analyses. In the present scenario, the need for respecting mind and ethical mind is very important, because many of the societal problems today are arising out of lack of consideration for others and overwhelming selfishness of the individual. The education system has to cultivate these minds among the youth, so that they learn to respect others, are tolerant and perseverant for realizing their goals in life.  

                          With these five types of minds, a person will be well equipped to deal with what is expected as well as what cannot be anticipated. Without these minds, a person will be at the mercy of forces that he or she can?t understand. Our educational, political, managerial and spiritual system should nurture these five kinds of minds for cultivating positive human potentials. Disciplines, syntheses and creativity can be put to all kinds of ends if we do not cultivate the sense of respect and ethical orientation. Hence, the five kinds of minds should be made to work synergistically.  
                          When I visualize these five minds of the future, I have a message for all of you. Nurturing all the five minds is possible, if you build the following five capacities among the youth. What are those five capacities?

                          The five capacities are: research and inquiry, creativity and innovation, use of high technology, entrepreneurial and moral leadership are the five capacities required to be built through the education process. 

                          If we develop in all our students these five capacities, we will produce "Autonomous Learner" a self-directed, self controlled, lifelong learner who will have the capacity to both, respect authority and at the same time is capable of questioning authority, in an appropriate manner. These are the leaders who would work together as a "Self-organizing Network" and transform any nation into a prosperous nation. The most important part of the education is to imbibe the confidence among the student is the spirit of "we can do it".  

                          By, Dr. APJ Abdulkalam 
                          www.abdulkalam.com 

                           

                          Introduction to MVC and Struts Framework

                          Model 1 Architecture
                          1.    When user clicks on the hyperlink, the JSP is directly invoked.
                          2.    The servlet container parses the JSP and executes the resulting Java servlet.
                          3.    The JSP contains embedded code and tags to access the Model JavaBeans. T
                          4.    The Model JavaBeans contains attributes for holding the HTTP request parameters from the query string.
                          5.    In addition it contains logic to connect to the middle tier or directly to the database using JDBC to get the additional data needed to display the page.
                          6.     The JSP is then rendered as HTML using the data in the Model JavaBeans and other Helper classes and tags. 

                          Problems with Model 1 Architecture 
                          1.    Model 1 architecture is easy.
                          2.    There is some separation between content (Model JavaBeans) and presentation (JSP). This separation is good enough for smaller applications.
                          3.    Larger applications have a lot of presentation logic. In Model 1 architecture, the presentation logic usually leads to a significant amount of Java code embedded in the JSP in the form of scriptlets. This is ugly and maintenance nightmare even for experienced Java developers.
                          4.    In large applications, JSPs are developed and maintained by page authors. The intermingled scriptlets and markup results in unclear definition of roles and is very problematic. 

                          Model 2 Architecture - MVC
                          The Model 2 JSP architecture is actually MVC applied to web applications and hence the two terms can be used interchangeably in the web world.
                          1. The Controller Servlet handles the user’s request. (This means the hyperlink in the JSP should point to the controller servlet).
                          2. The Controller Servlet then instantiates appropriate JavaBeans based on the request parameters (and optionally also based on session attributes).
                          3. The JavaBeans talks to the middle tier or directly to the database to fetch the required data.
                          4. The Controller sets the resultant JavaBeans (either same or a new one) in one of the following contexts – request, session or application.
                          5. The controller then dispatches the request to the next view based on the request URL.
                          6. The View uses the resultant JavaBeans from Step 4 to display data.
                          Note that there is no presentation logic in the JSP. The sole function of the JSP in Model 2 architecture is to display the data from the JavaBeans set in the request, session or application scopes.

                          Advantages of Model 2 Architecture

                          1.    Since there is no presentation logic in JSP, there are no scriptlets. This means lesser nightmares.
                          2.    With MVC you can have as many controller servlets in your web application. In fact you can have one Controller Servlet per module. However there are several advantages of having a single controller servlet for the entire web application.
                          3.    In a typical web application, there are several tasks that you want to do for every incoming request. For instance, you have to check if the user requesting an operation is authorized to do so. You also want to log the user’s entry and exit from the web application for every request. You might like to centralize the logic for dispatching requests to other views.
                          4.    If you have several controller servlets, chances are that you have to duplicate the logic for all the above tasks in all those places.
                          5.     A single controller servlet for the web application lets you centralize all the tasks in a single place. Elegant code and easier to maintain.

                          What is MVC

                          1.    The Model View Controller design pattern is a technique used to separate Business logic/state (the Model) from User Interface (the View) and program progression/flow (the Control).
                          2.    This pattern is very useful when it comes to modern web development:
                          –The majority of modern, high usage websites are dynamically driven.
                          –People well skilled at presentation (HTML writers) seldom know how to develop back-end solutions and visa versa.
                          –Separating business rules from presentation is good no matter what environment you develop in be it web or desktop.


                          The View:

                          The view is how data is represented to the user. For instance the view in a web application may be an HTML page, an image or other media

                          The Model:

                          The model represents the data in the system. For instance, a model might represent the properties associated with a user’s profile

                          The Controller:

                          The controller is the glue between the model and the view. It is responsible for controlling the flow of the program as well as processing updates from the model to the view and visa versa.

                          Benefits of MVC


                          1.    Promotes Modularity
                          2.    Multiple views
                          3.    Abstraction
                          4.    Allows application to be defined in a flow-chart, use-case or activity diagram which is more easily transferred to implementation.
                          First look at Struts
                          1.    Struts is an open source MVC framework developed by the Apache Jakarta project group.
                          2.    Struts allows JSP/Servlet writers the ability to fashion their web applications using the MVC design pattern.
                          3.    Struts allows you to configure a lot of the default framework objects through xml configuration files.

                          The components of MVC in Struts:


                          –The View is usually defined as a JSP or HTML page.
                          –The Model is usually defined as a Java object (sometimes called a bean).
                          –The Controller is defined by a Java object which extends the org.apache.struts.action.Action class. The Action class is at the heart of the Struts framework.


                          Struts: The Model

                          1.    To define a model in Struts is simple. Just create a java class and provide some functions.
                          2.    Your model classes should be coded independent of the Struts framework to promote maximum code reuse by other applications (i.e. if you have to reference javax.servlet.* class in your model, you are doing something wrong)
                          3.    Struts provides some default Model components, the most important of which is ActionForm.
                          4.    If you create a Model class by extending the Struts ActionForm class, Struts will
                          –Ensure your form bean is created when needed
                          –Ensure form submittal directly updates your form object with the inputted values
                          –Your controller object will be passed the form bean
                          5.    Struts will only handle models in an automatic fashion if you extend org.apache.struts.action.ActionForm
                          6.    Most likely you will have already built model object such as Customer, Employee, etc…
                          7.    Because you don’t want to tie your existing model objects to the Struts framework by having to extend ActionForm, Struts provides a org.apache.struts.util.PropertyUtils class that has a static method called copyProperties
                          8.    When your controller receives a form, it can simply call PropertyUtils.copyProperties(myModel, form) to copy all form properties to your original model object

                          Model: ActionForm

                          import javax.servlet.http.HttpServletRequest;
                          import javax.servlet.http.HttpServletResponse;
                          import org.apache.struts.action.ActionForm;
                          import org.apache.struts.action.ActionMapping;
                          import org.apache.struts.upload.FormFile;

                          public class LogonForm extends ActionForm {
                                      protected String userName;
                                      protected String password;
                           
                                      public void setUserName(String userName) {
                                                  this.userName = userName;
                                      }
                                      public void setPassword(String password) {
                                                  this.password = password;
                                      }
                                      //There would also be getters for these properties
                          }


                          Ø  When this “LogonForm” is associated with a controller, it will be passed to the controller whenever it’s service is requested by the user.
                          Ø  JSP pages acting as the view for this LogonForm are automatically updated by Struts with the current values of the UserName and Password properties.
                          Ø  If the user changes the properties via the JSP page, the LogonForm will automatically be updated by Struts
                          Ø  But what if the user screws up and enters invalid data? ActionForms provide validation…
                          Ø  Before an ActionForm object is passed to a controller for processing, a “validate” method can be implemented on the form which allows the form to belay processing until the user fixes invalid input as we will see on the next slide...

                          Model: ActionForm

                          public ActionErrors validate(ActionMapping mapping,
                                                                          HttpServletRequest request) {
                                      if (“”.equals(this.userName)) {
                                                  ActionErrors aes = new ActionErrors();
                                                  aes.add(new ActionError(“error.username.invalid”));
                                                  return aes;
                                      }
                          }

                          Typically what will happen is Struts will see that errors are being returned and will forward the user to a jsp page that has been setup as the “failure” page. Usually, the errors result from bad input on a form, so the failure page will be set to the original form and any <html:errors> tags which are found are replaced with the contents of the ActionErrors returned from the validate method.



                          The Controller
                          Ø  The controller is the switch board of MVC.
                          Ø  It directs the user to the appropriate views by providing the view with the correct model
                          Ø  The task of directing users to appropriate views is called “mapping” in struts.
                          Ø  Luckily, the Struts framework provides a base object called org.apache.struts.action.ActionServlet.
                          Ø  The ActionServlet class uses a configuration file called struts-config.xml to read mapping data called action mappings
                          Ø  The ActionServlet class reads the incoming URI and tries to match the URI against a set of action mappings to see if it can find a controller class which would be willing to handle the request
                          Ø  This process is described in a diagram on the following page
                          Ø  http://myhost/authorize.do Server configured to pass *.do extensions to org.apache.struts.action.ActionServlet via a web.xml configuration file ActionServlet object inspects the URI and tries to match it
                          against an ActionMapping located in the struts-config.xml file. Instance of appropriate Action class is found and it’s perform() method is called Action object handles the request and returns control to a view based where the user is within the flow of the application

                          Controller:

                          public class LogonAction extends Action {
                                      public ActionForward perform(ActionMapping mapping,                                                                    ActionForm    form,
                                                                          HttpServletRequest request,
                                                                          HttpServletResponse response) {
                                                                                                                         
                                                  LogonForm myForm = (LogonForm) form;
                                                  if (myForm.getUserName().equals(“john”) &&
                                                              myForm.getPassword().equals(“doe”)) {
                                                             
                                                              //return a forward to our success page
                                                              return mapping.findForward(”success”);
                                                  } else {
                                                              ActionErrors errors = new ActionErrors();
                                                              errors.add("password",
                                                                          new ActionError("error.password.required"));
                                                              this.saveErrors(errors); //Action implements this method
                                                              //go back to the page that made the request
                                                              return (new                                                                           ActionForward(mapping.getInput()));
                                                  }
                                      }          
                                     
                          }

                          Controller: Forwards
                          Ø  You might be wondering what mapping.findForward(“success”) means?
                          –The mapping object passed to the Controller’s perform() method is of type ActionMapping.
                          –When you setup your struts-config.xml file you can define forward tags that are available via the ActionMapping.findForward() method.
                          –In the previous example, our ActionMapping object would have been loaded with values from the <action-mapping> section defined for the LogonAction




                          Controller: ActionMapping
                          <action-mappings>
                                      <action    path="/logon"
                                        type="org.apache.struts.example.LogonAction"
                                        name="logonForm"
                                        scope="request"
                                        input="/logon.jsp">
                                      </action>
                                      <forward   name="success” path="/msgBoard.jsp"/>
                          </action-mappings>

                          The View
                          Ø  The view in Struts is represented by JSP pages
                          Ø  JSP pages allows developers to write java code, and access server side java objects in a web page
                          Ø  Although this is good, we will distract ourselves from the reason we are using Struts and MVC.
                          –We want to let our web page authors create dynamic web pages without knowing how to program
                          Ø  JSP solves this by introducing the concept of Tag Libraries
                          –Taglibs allow web designers the convenience of using HTML like tags
                          –It lets developers program the logic behind the tags
                          –The attributes of the tags are used as basic parameters that the developers will interpret, which could change the output generated by the tag
                          * Struts contains a series of taglibs designed to allow developers and web page authors the ability to communication one another to facilitate dynamic web content



                          The View: Example


                          <%@ page language="java" %>
                          <%@ taglib uri="/WEB-INF/struts-bean.tld" prefix="bean" %>
                          <%@ taglib uri="/WEB-INF/struts-html.tld" prefix="html" %>
                          <html:html locale="true">
                          <head>
                          <title><bean:message key="logon.title"/></title>
                          <html:base/>
                          </head>
                          <body bgcolor="white">
                          <html:errors/>
                          <html:form action="/logon.do" focus="username">
                          <table border="0" width="100%">
                            <tr>
                              <th align="right">
                                <bean:message key="prompt.username"/>
                              </th>
                              <td align="left">
                                <html:text property="username" size="16" maxlength="16"/>
                              </td>
                            </tr>
                          <tr>
                              <th align="right">
                                <bean:message key="prompt.password"/>
                              </th>
                              <td align="left">
                                <html:password property="password"
                                      size="16" maxlength="16"/>
                              </td>
                            </tr>
                            <tr>
                              <td align="right">
                                <html:submit property="submit"
                                      value="Submit"/>
                              </td>
                              <td align="left">
                                <html:reset/>
                              </td>
                            </tr>
                          </table>
                          </html:form>
                          </body>
                          </html:html>


                          View: Internationalization
                          Ø  Commonly referred to as i18n (I <followed by 18 letters> n)
                          Ø  The ability to maintain a web app in several different languages
                          Ø  Based on the language setup on the client side, the web app will auto-magic-ally
                          Ø  This is achieve in Struts through Java Resource Bundles
                          Ø  ResourceBundles are classes that support, among other things, String data.
                          Ø  Instead of having to make a ResourceBundle class for each language supported by your web app, resource bundles can be described as text files
                          Ø  If you had a set of strings in the French language you might make a file named MyStrings_fr.properties


                          MyResources.properties file:

                          helloworld.title=Hello World!
                          menu.file=File
                          menu.file.open=Open
                          menu.file.close=Close
                          menu.file.exit=Exit
                          menu.edit=Edit
                          menu.edit.copy=Copy
                          menu.edit.paste=Paste

                          MyResources_fr.properties file:

                          helloworld.title=Allô monde!
                          menu.file=Dossier
                          menu.file.open=Ouvrir
                          menu.file.close=Fermer
                          menu.file.exit=Sortie
                          menu.edit=Rédiger
                          menu.edit.copy=Copier
                          menu.edit.paste=Pâte


                          How do you make a habit of studying?(Originally Asked on Quora)

                          The first thing to bring up the habit in whatever you do is by identifying the purpose behind doing that. For example, if you want to...