Friday, March 22, 2019

Creating a Web Application


Generally, a web application starts with a login portal or registration portal, otherwise we could use simple html pages for rest things out there. Our first web application will be starting with a login portal, interacting with database through a servlet with validation and login error handling .
Requirements :

  • An IDE (most preferably Eclipse J2EE)  
  • Server (Apache Tomcat) // link to download is given in previous blog post.
  • Database (most preferably MySql 5.5)
Follow the steps below and code to create a login page :

1. Open Eclipse Enterprise edition. File -> New -> Dynamic Web Project.


2. Enter project name and choose a new runtime which is the server itself.

3. Select server name and specify it’s directory in the system.


4. click next, and put build/classes as the output folder (by default it’s same written here) and then next, check the web.xml for deployment description purpose.


5. Click on Finish to end setup.
6. Right click on project name (test here), Build Path -> Configure Build Path in order to configure project for servlet-api if not provided (to avoid compilation error in most cases).  A dialog box will open, click on Add External JAR, go to apache tomcat->lib directory and select servlet-api.jar, apply the change.


7. Click on project name, create a .jsp file named login.jsp as follows : WebContent->New->JSP File.


8. All we need now to write code for login.jsp, a servlet and web xml, along with a login table in database.
login.jsp:
<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
       pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>login page</title>
</head>
<body>
       <form action="Login" method="post">
             username: <input type="text" name="email" required><br>
             password: <input type="password" name="pass" required><br>
             <input type="submit" value="Login"> <input type="reset"
                    value="reset">
             <center style="color: red">
<%
if (null != request.getAttribute("errorMessage")) {
String s = (String) request.getAttribute("errorMessage");
if (s != null) {
out.println(s);
}
}
%>
</center><br>
       </form>
</body>
</html>
Action in form is “Login” which will be our servlet named Login.java.

9. Create a login table in database (let uid(user,pass) be the table.
Mysql:
·       User : root and pwd:4591
·       Database name: login
·       Code:
create table uid ( user varchar(20), pass varchar(20), primary key(user));
insert into uid() values(“a”, “a”);

10. To create Servlet, goto project name->new->servlet. A dialog box will open, enter package name (like com), it’s optional and class name as Login, to generate Login.class file (same as filename Login.java). Click on next and notice the Url mapping : /Login which will be used in web.xml for mapping purpose. Click next and finish to open Login.java file.
Login.java :
package com;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.List;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import javax.servlet.http.HttpSessionActivationListener;

//import com.sun.xml.internal.bind.v2.schemagen.xmlschema.List;

public class Login extends HttpServlet {

       public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
             RequestDispatcher dispatcher = request.getRequestDispatcher("/Login.jsp");
             dispatcher.forward(request, response);
       }

       public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
              try {
                    String user = request.getParameter("email");
                    String pass = request.getParameter("pass");
                    int c = 0;
                    // jdbc call
                    Class.forName("com.mysql.jdbc.Driver");
                    Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/login?useSSL=false", "root", "4591");
                    System.out.println("Connected to mysql");
                    Statement st = con.createStatement();
                    ResultSet rs = st.executeQuery("select * from uid");
                                        while (rs.next()) {
                                 if (user.equals(rs.getString("user")) && pass.equals(rs.getString("pass"))) {
                                        response.sendRedirect("https://icodemac55.blogspot.com");
                                        c++;
                                 }
                    }
                    if (c == 0) {
                           request.setAttribute("errorMessage", "Invalid username or password");
                           RequestDispatcher dispatcher = request.getRequestDispatcher("/Login.jsp");
                           dispatcher.forward(request, response);
                           response.sendRedirect("Login.jsp");
                    }
             } catch (Exception e) {
                    e.printStackTrace();
             }

       }
}

11.  Last step is to write code for web.xml file which lie inside WebContent-> WEB-INF -> lib.
web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>log</display-name>
  <servlet>
    <servlet-name>Logintesteeeee</servlet-name>
    <servlet-class>com.Login</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>Logintesteeeee</servlet-name>
    <url-pattern>/Login</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>login.jsp</welcome-file>
  </welcome-file-list>
</web-app>

12. Run the project on server project-name(test)-> Run as -> Run on Server.

(if error occurred on http://localhost:8080/test, then run login.jsp as: http://localhost:8080/test/login.jsp).
If login credentials are correct, you’ll redirected to the required page, else an error will be thrown on same page.
Note: For user friendly view, choose in Eclipse EE ide (Window- Show View- Navigator).

Wednesday, March 6, 2019

Starting with Servlet


Talking about the Servlets, it all starts with Dynamic Web.
In traditional programming, applets were used to access a database and get dynamic data,but they were too slow and inefficient. So we use dynamic web which in terms introduces Common Gateway Interface (CGI) programs  and client-side scripting to deal with that problem.
  • CGI programs reside on the server and they accept requests, use the server-side resources, and generate an HTML page as a response. They can be written in a variety of language, such as Java,C++,Perl and Visual Basic. Examples of CGI programs are JSPs, Servlets, ASPs etc.
  • Client-side scripting uses scripting language at client side for small business applications,such as form validation.
Here we'll elaborate Dynamic Web applications using servlets on J2EE platform. J2EE specifications were written by Sun Microsystems. It is made up of 13 technologies : 
1.    Java Server Pages (JSPs)
2.    Servlets
3.    Java messaging Service (JMS)
4.    Java Database Connectivity (JDBC)
5.    Java Naming and Directory Interface (JNDI)
6.    Java Transaction Service (JTS)
7.    Java Transaction API (JTA)
8.    JavaMail
9.    JavaBeans Activation Framework (JAF)
10. Remote Method Invocation (RMI)
11. Enterprise JavaBeans (EJB)
12. Extensible Markup Language (XML)
13. Java Integrated Definition Language (Java IDL)
Recently J2EE Connector Architecture is added by Sun to the J2EE.
Further J2EE uses XML for deployment descriptors. A complaint application server supports all the technologies defined in the J2EE. This helps developers because they can write applications to the specification and then choose what application server to deploy on.
We'll choose front end of the Dynamic Web Application (client-side) to be written in JSP which includes HTML,CSS and JavaScript. But to run JSP, there needs to be an environment.
We'll use Apache's Tomcat as our JSP server. Apache Tomcat is a free Web server that can handle requests for HTML, JSPs, and Servlets. Another runtime environment you could use is BEA WebLogic Server.
Download Apache Tomcat 8.5 from here : https://tomcat.apache.org/download-80.cgi and configure it. Change tomcat users id and password in xml file (conf/tomcat-users.xml) for admin and manager-gui users as like this: 
        <tomcat-users>
        <role rolename="manager-gui"/>
        <user username="admin" password="" roles="manager-gui"/>
        <role rolename="admin-gui"/>
        <user username="tomcat" password="s3cret" roles="admin-gui"/>
        </tomcat-users>
After configuring apache tomcat, we'll add it as runtime environment in our IDE for writing JSPs which may be Eclipse J2EE , Netbeans or other IDE providing J2EE technologies.
Servlets for Dynamic Web Application:
Servlet is a CGI program. In most common terms, a servlet is a Java class that implements the Servlet Interface (refer to Interfaces in Java) and accepts requests and generate responses. The requests come from Java classes, Web clients, or other Servlets.
One doubt anyone can acquire is that How JSPs become Servlets ?
Answer to this query is quite simple, it's all about mapping things out there.
·        In your servlet container, the JSP servlet is mapped to any URL that ends in .jsp (usually)
·        When one of those .jsp  URLs is requested, the request goes to the JSP servlet. Then, this servlet checks if the JSP is already compiled.
·        If the JSP is not compiled yet, the JSP servlet translates the JSP to some Java source code implementing the Servlet interface. Then it compiles this Java source code to a .class file. This .class file usually is located somewhere in the servlet container's work directory for the application.
·        Once the JSP servlet has compiled the servlet class from the JSP source code, it just forwards the request to this servlet class.
The thing is, unless you specifically precompile your JSP, all this happens at runtime, and hidden in the servlet container's work directory, so it is "invisible". Also have in mind that this is what happens "conceptually", several optimizations are possible in this workflow.
In the next section we'll talk about how to create a complete Web Application.


Event Handling in Spring

Spring's event handling is single-threaded so if an event is published,  until and unless all the receivers get the message, the process...