Blog

Collections

 

ArrayList list = new ArrayList();
        list.add("h");
        list.add("e");
        list.add("l");
        list.add("l");
        list.add("o");

        for (int i = 1; i < 10; i++) {
            list.add(i);
        }

        Iterator it = list.iterator();

        while (it.hasNext()) {
            out.println(it.next() + "<br/>");
        }

        HashSet hs = new HashSet();
        hs.add("A");
        hs.add("B");
        hs.add("C");
        hs.add("C");
        hs.add("C");

        HashMap hm = new HashMap();
        hm.put("a", "A");
        hm.put("b", "B");

        Iterator its = hs.iterator();

        while (its.hasNext()) {
            out.println(its.next() + "<br/>");
        }

        Iterator itr = hm.entrySet().iterator();

        while (itr.hasNext()) {
            Map.Entry pair = (Map.Entry) itr.next();
            out.println(pair.getKey() + " => " + pair.getValue() + "<br/>");
        }

        String[] strarr = new String[10];

        for (int i = 0; i < 10; i++) {
            strarr[i] = "abc" + i;
        }

        for (String valu : strarr) {
            out.println(valu);
        }

 
Ref:

  1. http://stackoverflow.com/questions/85190/how-does-the-java-for-each-loop-work
  2. http://stackoverflow.com/questions/4131655/what-is-the-difference-between-lists-arraylists-maps-hashmaps-collections-et
  3. https://www.quora.com/What-is-the-difference-between-a-Set-and-a-Map-in-Java
  4. http://stackoverflow.com/questions/1066589/iterate-through-a-hashmap
  5. http://stackoverflow.com/questions/1200621/how-to-declare-an-array-in-java
  6. http://stackoverflow.com/questions/1665834/how-can-i-initialize-a-string-array-with-length-0-in-java

Session Management in Java

List of Files

  1. header.jsp
  2. login.jsp
  3. home.jsp
  4. logout.jsp

header.jsp

<a href="login.jsp">Login</a>
<a href="home.jsp">Home</a>
<a href="logout.jsp">Logout</a>

 


login.jsp

 

<%
    HttpSession sess = request.getSession();

    if (sess.getAttribute("sess_username") != null) { // check is session variable exist in session pool or not
        response.sendRedirect("home.jsp"); // if session variable is already set then redirect it to home page else stay on login page
    }
%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%@include file="header.jsp" %>
        <h1>Login</h1>
        <form action="home.jsp" method="post">
            Username <input type="text" name="username"/><br/>
            Password <input type="password" name="password"/><br/>
            <input type="submit" value="Login"/>
        </form>
    </body>
</html>

 


home.jsp

 

<%
    HttpSession sess = request.getSession(); //get the session object from getSession() method of request object

    if (sess.getAttribute("sess_username") == null) { // check whether the session variable is exist in session pool or not
        sess.setAttribute("sess_username", request.getParameter("username")); // create session variable if it is not present in session pool
    }
%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%@include file="header.jsp" %>
        <h1>Home</h1>
        <h2>Hello <%=sess.getAttribute("sess_username")%> </h2>
    </body>
</html>

 


logout.jsp

 

<%
    HttpSession sess = request.getSession();
    sess.invalidate(); // this will terminate the session and destroy all variables stored in session pool
%>

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <title>JSP Page</title>
    </head>
    <body>
        <%@include file="header.jsp" %>
        <h1>Logout</h1>
    </body>
</html>

 


Display Session variables from pool

Console o/p:

 

Enumeration attributeNames = sess.getAttributeNames();

while (attributeNames.hasMoreElements()) {

    String name = (String) attributeNames.nextElement();

    String value = (String) sess.getAttribute(name);

    out.println(name + "=" + value);

}

 

JSTL(Java Server Pages Standard Tag Library) o/p:

<c:forEach var="session" items="${sessionScope}">

    ${session.key} = ${session.value}

</c:forEach>

 

 

form field validation

The problem is that your REGX pattern will only match the input “0-9”.

To meet your requirement (0-9999999), you should rewrite your regx pattern:

ng-pattern="/^[0-9]{1,7}$/"

HTML:

<div ng-app ng-controller="formCtrl">
    <form name="myForm" ng-submit="onSubmit()"> 
        <input type="number" ng-model="price" name="price_field" ng-pattern="/^[0-9]{1,7}$/" required> 
        <span ng-show="myForm.price_field.$error.pattern">Not a valid number!</span> 
        <span ng-show="myForm.price_field.$error.required">This field is required!</span> 
        <input type="submit" value="submit"/> 
    </form> 
</div> 

JS:

function formCtrl($scope){ 
    $scope.onSubmit = function(){ 
        alert("form submitted"); 
    } 
}

 

 

 


Spring Hibernate Jars

MySQL Connection Jars

http://www.java2s.com/Code/Jar/c/Downloadcommysqljdbc515jar.htm

http://www.java2s.com/Code/Jar/m/Downloadmysqlconnectorjava5123binjar.htm

Bcrypt Password Jars

http://www.java2s.com/Code/Jar/s/Downloadspringsecuritycrypto310RELEASEjar.htm

Why String is Immutable in Java

Lets break it into some parts

String s1 = “hello”;
This Statement creates string containing hello and occupy space in memory i.e. in Constant String Pool and and assigned it to reference object s1

String s2 = s1;
This statement assigns the same string hello to new reference s2

         _______
        |       |
s1 ---->| hello |<----- s2
        |_______|

Both references are pointing to the same string so output the same value as follows.

out.println(s1); // o/p: hello
out.println(s2); // o/p: hello
Though String is immutable, assignment can be possible so the s1 will now refer to new value stack.

s1 = “stack”;

         _________
        |         |
s1 ---->| stack   |
        |_________|

But what about s2 object which is pointing to hello it will be as it is.

         __________
        |          |
s2 ---->| hello    |
        |__________|

out.println(s1); // o/p: stack
out.println(s2); // o/p: hello
Since String is immutable Java Virtual Machine won’t allow us to modify string s1 by its method. It will create all new String object in pool as follows.

s1.concat(” overflow”);

                 ___________________
                |                   |
s1.concat ----> | stack overflow    |
                |___________________|

out.println(s1); // o/p: stack
out.println(s2); // o/p: hello
out.println(s1.concat); // o/p: stack overflow
Note if String would be mutable then the output would have been

out.println(s1); // o/p: stack overflow
Now you might be surprised why String has such methods like concat() to modify. Following snippet will clear your confusion.

s1 = s1.concat(” overflow”);
Here we are assigning modified value of string back to s1 reference.

         ___________________
        |                   |
s1 ---->| stack overflow    |
        |___________________|

out.println(s1); // o/p: stack overflow
out.println(s2); // o/p: hello
That’s why Java decided String to be a final class Otherwise anyone can modify and change the value of string. Hope this will help little bit.

Spring Web MVC Hello World

 

Git Clone Link: https://gitlab.com/shaileshsonare/spring_helloworld.git

Step 1. Create new Project

Step 2. Name the Project and select location

 

Step 3. Select Server and Settings

 

Step 4. Select Framework to include in Project’s library and include JSTL (Java Server Pages Tag Library)

 

Step 5. Project Created Successfully

Step 6. Check Welcome file. This file will display on browser if we enter only Project name in url.

e.g. http://localhost:8080/ProjectName/

Step 7. This section will decide which url pattern will be consider as Spring Requests and which url is not a part of Spring Framework.

Here all *.htm (URL ending with .htm from browser) will be consider as Spring request.

 

Step 8. You can run normal jsp pages also from browser which will not be part of Spring framework.

 

Step 9. Create new jsp file as

Right Click on WebPages >> New >> Jsp File

 

Step 10. Run on Browser it will run as old traditional jsp project file.

 

Hibernate CRUD with MySQL Database – Java

 

To Update Record Using Hibernate Session:

Configuration cfg = new Configuration().configure("hibernate.cfg.xml"); 

StandardServiceRegistryBuilder ssrb = new StandardServiceRegistryBuilder().applySettings(cfg.getProperties()); 

SessionFactory factory = cfg.buildSessionFactory(ssrb.build()); Session session = factory.openSession(); 

Transaction t = session.beginTransaction(); 

Users u = (Users) session.load(Users.class, 6); // load record having id 6 into u object

u.setLastName("Nitnavre"); // set column value which needs to update

System.out.println(session.save(u)); // fire update query using save function of hibernate

t.commit(); // commit the update changes to save state in database

System.out.println("Record updated successfully...");

 

Ref Link:

  1. https://www.journaldev.com/3481/hibernate-session-merge-vs-update-save-saveorupdate-persist-example