7da70advance Java Lab Manual
7da70advance Java Lab Manual
7da70advance Java Lab Manual
1
ASETL CSE/VI SEM AJP LAB
LIST OF EXPERIMENTS
2
ASETL CSE/VI SEM AJP LAB
CONTENTS
LIST OF EXPERIMENTS ......................................................................................................... 2
3
ASETL CSE/VI SEM AJP LAB
Procedure:-
1. use SampleDB;
Or if you are using MySQL Command Line Client program, save the above script into a file,
let’s say, SQLScript.sql and execute the following command:
source Path\To\The\Script\File\SQLScript.sql
Here’s an example screenshot taken while executing the above script in MySQL Command
Line Client program:
4
ASETL CSE/VI SEM AJP LAB
o DriverManager: this class is used to register driver for a specific database type (e.g.
MySQL in this tutorial) and to establish a database connection with the server via
its getConnection() method.
o Connection: this interface represents an established database connection (session)
from which we can create statements to execute queries and retrieve results, get
metadata about the database, close connection, etc.
o Statement and PreparedStatement: these interfaces are used to execute static SQL
query and parameterized SQL query, respectively. Statement is the super interface of
the PreparedStatement interface. Their commonly used methods are:
A prepared statement is one that contains placeholders (in form question marks ?) for
dynamic values will be set at runtime. For example:
SELECT * from Users WHERE user_id=?
Here the value of user_id is parameterized by a question mark and will be set by one
of the setXXX() methods from the PreparedStatement interface, e.g. setInt(int index,
int value).
o ResultSet: contains table data returned by a SELECT query. Use this object to iterate
over rows in the result set using next() method, and get value of a column in the current
row using getXXX() methods (e.g. getString(), getInt(), getFloat() and so on). The
column value can be retrieved either by index number (1-based) or by column name.
o SQLException: this checked exception is declared to be thrown by all the above
methods, so we have to catch this exception explicitly when calling the above classes’
methods.
5
ASETL CSE/VI SEM AJP LAB
4. try {
5. Connection conn = DriverManager.getConnection(dbURL, username, password);
6. if (conn != null) {
7. System.out.println("Connected");
8. }
9. } catch (SQLException ex) {
10. ex.printStackTrace();
11. }
Once the connection was established, we have a Connection object which can be used to create
statements in order to execute SQL queries. In the above code, we have to close the connection
explicitly after finish working with the database:
conn.close();
However, since Java 7, we can take advantage of the try-with-resources statement which will
close the connection automatically, as shown in the following code snippet:
1. try (Connection conn = DriverManager.getConnection(dbURL, username, password))
{
2. // code to execute SQL queries goes here...
3. } catch (SQLException ex) {
4. ex.printStackTrace();
5. }
6
ASETL CSE/VI SEM AJP LAB
And so on. Which method to be used is depending on the type of the corresponding column in
the database table?
Finally we call the PreparedStatement’s executeUpdate() method to execute the INSERT
statement. This method returns an update count indicating how many rows in the table were
affected by the query, so checking this return value is necessary to ensure the query was
executed successfully. In this case, executeUpdate() method should return 1 to indicate one
record was inserted.
7
ASETL CSE/VI SEM AJP LAB
based, the first column will be at index 1, the second at index 2, and so on. If you are not sure
or don’t know exactly the index of column, so passing a column name would be useful:
String fullname = result.getString("fullname");
For other data types, the ResultSet provide appropriate getter methods:
o getString()
o getInt()
o getFloat()
o getDate()
o getTimestamp()
o …
The following code snippet will update the record of “Bill Gates” as we inserted previously:
8
ASETL CSE/VI SEM AJP LAB
Procedure:-
Creating login form, we have used the DAO (Data Access Object), Factory method and DTO
(Data Transfer Object) design patterns. There are many files:
index.jsp it provides three links for login, logout and profile
login.jsp for getting the values from the user
loginprocess.jsp, a jsp file that processes the request and calls the methods.
LoginBean.java, a bean class that have properties and setter and getter methods.
Provider.java, an interface that contains many constants like DRIVER_CLASS,
CONNECTION_URL, USERNAME and PASSWORD
ConnectionProvider.java, a class that is responsible to return the object of
Connection. It uses the Singleton and factory method design pattern.
LoginDao.java, a DAO class that verifies the emailId and password from the
database.
logout.jsp it invalidates the session.
profile.jsp it provides simple message if user is logged in, otherwise forwards the
request to the login.jsp page.
In this example, we are using the Oracle10g database to match the emailId and password with
the database. The table name is user432 which have many fields like name, email, pass etc.
You may use this query to create the table:
index.jsp
1. <a href="login.jsp">login</a>|
2. <a href="logout.jsp">logout</a>|
3. <a href="profile.jsp">profile</a>
9
ASETL CSE/VI SEM AJP LAB
login.jsp
This file creates a login form for two input fields name and password. It is the simple login
form, you can change it for better look and feel. We are focusing on the concept only.
loginprocess.jsp
This jsp file contains all the incoming values to an object of bean class which is passed as an
argument in the validate method of the LoginDao class. If emailid and password is correct, it
displays a message you are successfully logged in! and maintains the session so that we may
recognize the user.
1. <%@page import="bean.LoginDao"%>
2. <jsp:useBean id="obj" class="bean.LoginBean"/>
3.
4. <jsp:setProperty property="*" name="obj"/>
5.
6. <%
7. boolean status=LoginDao.validate(obj);
8. if(status){
9. out.println("You r successfully logged in");
10
ASETL CSE/VI SEM AJP LAB
10. session.setAttribute("session","TRUE");
11. }
12. else
13. {
14. out.print("Sorry, email or password error");
15. %>
16. <jsp:include page="index.jsp"></jsp:include>
17. <%
18. }
19. %>
LoginBean.java
It is the bean class that have 2 properties email and pass with its setter and getter methods.
1. package bean;
2.
3. public class LoginBean {
4. private String email,pass;
5.
6. public String getEmail() {
7. return email;
8. }
9.
10. public void setEmail(String email) {
11. this.email = email;
12. }
13.
14. public String getPass() {
15. return pass;
16. }
17.
18. public void setPass(String pass) {
19. this.pass = pass;
20. }
21.
22.
23. }
Provider.java
11
ASETL CSE/VI SEM AJP LAB
This interface contains four constants that may differ from database to database.
1. package bean;
2.
3. public interface Provider {
4. String DRIVER="oracle.jdbc.driver.OracleDriver";
5. String CONNECTION_URL="jdbc:oracle:thin:@localhost:1521:xe";
6. String USERNAME="system";
7. String PASSWORD="oracle";
8.
9. }
ConnectionProvider.java
This class provides a factory method that returns the object of Connection. Here, driver class
is loaded only once and connection object gets memory only once because it is static.
1. package bean;
2. import java.sql.*;
3. import static bean.Provider.*;
4.
5. public class ConnectionProvider {
6. private static Connection con=null;
7. static{
8. try{
9. Class.forName(DRIVER);
10. con=DriverManager.getConnection(CONNECTION_URL,USERNAME,PASSWORD
);
11. }catch(Exception e){}
12. }
13.
14. public static Connection getCon(){
15. return con;
16. }
17.
18. }
LoginDao.java
12
ASETL CSE/VI SEM AJP LAB
1. package bean;
2. import java.sql.*;
3. public class LoginDao {
4.
5. public static boolean validate(LoginBean bean){
6. boolean status=false;
7. try{
8. Connection con=ConnectionProvider.getCon();
9.
10. PreparedStatement ps=con.prepareStatement(
11. "select * from user432 where email=? and pass=?");
12.
13. ps.setString(1,bean.getEmail());
14. ps.setString(2, bean.getPass());
15.
16. ResultSet rs=ps.executeQuery();
17. status=rs.next();
18.
19. }catch(Exception e){}
20.
21. return status;
22.
23. }
24. }
13
ASETL CSE/VI SEM AJP LAB
Procedure:-
Cookies in Servlet
A cookie is a small piece of information that is persisted between the multiple client requests.
A cookie has a name, a single value, and optional attributes such as a comment, path and
domain qualifiers, a maximum age, and a version number.
By default, each request is considered as a new request. In cookies technique, we add cookie
with response from the servlet. So cookie is stored in the cache of the browser. After that if
request is sent by the user, cookie is added with request by default. Thus, we recognize the user
Types of Cookie
1. Non-persistent cookie
2. Persistent cookie
Non-persistent cookie
It is valid for single session only. It is removed each time when user closes the browser.
Persistent cookie
It is valid for multiple session . It is not removed each time when user closes the browser. It
is removed only if user logout or signout.
Advantage of Cookies
14
ASETL CSE/VI SEM AJP LAB
Disadvantage of Cookies
Cookie class
There are given some commonly used methods of the Cookie class.
Method Description
public void setMaxAge(int Sets the maximum age of the cookie in seconds.
expiry)
public String getName() Returns the name of the cookie. The name cannot be
changed after creation.
public String getValue() Returns the value of the cookie.
public void setName(String changes the name of the cookie.
name)
public void setValue(String changes the value of the cookie.
value)
For adding cookie or getting the value from the cookie, we need some methods provided
by other interfaces. They are:
15
ASETL CSE/VI SEM AJP LAB
Let's see the simple code to delete cookie. It is mainly used to logout or signout the user.
1. Cookie ck[]=request.getCookies();
2. for(int i=0;i<ck.length;i++){
3. out.print("<br>"+ck[i].getName()+" "+ck[i].getValue());//printing name and value of c
ookie
4. }
16
ASETL CSE/VI SEM AJP LAB
In this example, we are storing the name of the user in the cookie object and accessing it in
another servlet. As we know well that session corresponds to the particular user. So if you
access it from too many browsers with different values, you will get the different value.
index.html
FirstServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5.
6. public class FirstServlet extends HttpServlet {
7.
8. public void doPost(HttpServletRequest request, HttpServletResponse response){
9. try{
10.
11. response.setContentType("text/html");
12. PrintWriter out = response.getWriter();
13.
14. String n=request.getParameter("userName");
15. out.print("Welcome "+n);
16.
17. Cookie ck=new Cookie("uname",n);//creating cookie object
18. response.addCookie(ck);//adding cookie in the response
19.
20. //creating submit button
21. out.print("<form action='servlet2'>");
22. out.print("<input type='submit' value='go'>");
23. out.print("</form>");
24.
25. out.close();
26.
27. }catch(Exception e){System.out.println(e);}
28. }
29. }
17
ASETL CSE/VI SEM AJP LAB
SecondServlet.java
1. import java.io.*;
2. import javax.servlet.*;
3. import javax.servlet.http.*;
4.
5. public class SecondServlet extends HttpServlet {
6.
7. public void doPost(HttpServletRequest request, HttpServletResponse response){
8. try{
9.
10. response.setContentType("text/html");
11. PrintWriter out = response.getWriter();
12.
13. Cookie ck[]=request.getCookies();
14. out.print("Hello "+ck[0].getValue());
15.
16. out.close();
17.
18. }catch(Exception e){System.out.println(e);}
19. }
20.
21.
22. }
web.xml
1. <web-app>
2.
3. <servlet>
4. <servlet-name>s1</servlet-name>
5. <servlet-class>FirstServlet</servlet-class>
6. </servlet>
7.
8. <servlet-mapping>
9. <servlet-name>s1</servlet-name>
10. <url-pattern>/servlet1</url-pattern>
11. </servlet-mapping>
12.
13. <servlet>
18
ASETL CSE/VI SEM AJP LAB
14. <servlet-name>s2</servlet-name>
15. <servlet-class>SecondServlet</servlet-class>
16. </servlet>
17.
18. <servlet-mapping>
19. <servlet-name>s2</servlet-name>
20. <url-pattern>/servlet2</url-pattern>
21. </servlet-mapping>
22.
23. </web-app>
19
ASETL CSE/VI SEM AJP LAB
Procedure:-
When a browser requests for a web page, it sends lot of information to the web server which
can not be read directly because this information travel as a part of header of HTTP request.
You can check HTTP Protocol for more information on this.
Following is the important header information which comes from browser side and you would
use very frequently in web programming:
Header Description
Accept This header specifies the MIME types that the browser or other clients
can handle. Values of image/png or image/jpeg are the two most
common possibilities.
Accept- This header specifies the character sets the browser can use to display the
Charset information. For example ISO-8859-1.
Accept- This header specifies the types of encodings that the browser knows how
Encoding to handle. Values of gzip or compress are the two most common
possibilities.
Accept- This header specifies the client's preferred languages in case the servlet
Language can produce results in more than one language. For example en, en-us, ru,
etc.
Authorization This header is used by clients to identify themselves when accessing
password-protected Web pages.
Connection This header indicates whether the client can handle persistent HTTP
connections. Persistent connections permit the client or other browser to
retrieve multiple files with a single request. A value of Keep-Alive means
that persistent connections should be used
Content- This header is applicable only to POST requests and gives the size of the
Length POST data in bytes.
Cookie This header returns cookies to servers that previously sent them to the
browser.
Host This header specifies the host and port as given in the original URL.
If-Modified- This header indicates that the client wants the page only if it has been
Since changed after the specified date. The server sends a code, 304 which
means Not Modified header if no newer result is available.
If- This header is the reverse of If-Modified-Since; it specifies that the
Unmodified- operation should succeed only if the document is older than the specified
Since date.
Referer This header indicates the URL of the referring Web page. For example, if
you are at Web page 1 and click on a link to Web page 2, the URL of
Web page 1 is included in the Referer header when the browser requests
Web page 2.
20
ASETL CSE/VI SEM AJP LAB
User-Agent This header identifies the browser or other client making the request and
can be used to return different content to different types of browsers.
The request object provides methods to get HTTP header information including form data,
cookies, HTTP methods etc.
There are following important methods which can be used to read HTTP header in your JSP
program. These method are available with HttpServletRequest object which represents client
request to webserver.
21
ASETL CSE/VI SEM AJP LAB
10 String getAuthType()
Returns the name of the authentication scheme used to protect the servlet, for
example, "BASIC" or "SSL," or null if the JSP was not protected
11 String getCharacterEncoding()
Returns the name of the character encoding used in the body of this request.
12 String getContentType()
Returns the MIME type of the body of the request, or null if the type is not known.
13 String getContextPath()
Returns the portion of the request URI that indicates the context of the request.
14 String getHeader(String name)
Returns the value of the specified request header as a String.
15 String getMethod()
Returns the name of the HTTP method with which this request was made, for
example, GET, POST, or PUT.
16 String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does not
exist.
17 String getPathInfo()
Returns any extra path information associated with the URL the client sent when it
made this request.
18 String getProtocol()
Returns the name and version of the protocol the request.
19 String getQueryString()
Returns the query string that is contained in the request URL after the path.
20 String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent the request.
21 String getRemoteHost()
Returns the fully qualified name of the client that sent the request.
22 String getRemoteUser()
Returns the login of the user making this request, if the user has been authenticated,
or null if the user has not been authenticated.
23 String getRequestURI()
Returns the part of this request's URL from the protocol name up to the query string
in the first line of the HTTP request.
24 String getRequestedSessionId()
Returns the session ID specified by the client.
25 String getServletPath()
Returns the part of this request's URL that calls the JSP.
22
ASETL CSE/VI SEM AJP LAB
Once we have an Enumeration, we can loop down the Enumeration in the standard manner,
using hasMoreElements() method to determine when to stop and using nextElement() method
to get each parameter name.
23
ASETL CSE/VI SEM AJP LAB
Now put the above code in main.jsp and try to access it. This would produce result something
as follows:
24
ASETL CSE/VI SEM AJP LAB
Procedure:-
JSP actions use constructs in XML syntax to control the behavior of the servlet engine. You
can dynamically insert a file, reuse JavaBeans components, forward the user to another page,
or generate HTML for the Java plugin.
There is only one syntax for the Action element, as it conforms to the XML standard:
Action elements are basically predefined functions and there are following JSP actions
available:
Syntax Purpose
jsp:include Includes a file at the time the page is requested
jsp:useBean Finds or instantiates a JavaBean
jsp:setProperty Sets the property of a JavaBean
jsp:getProperty Inserts the property of a JavaBean into the output
jsp:forward Forwards the requester to a new page
jsp:plugin Generates browser-specific code that makes an OBJECT or EMBED tag
for the Java plugin
jsp:element Defines XML elements dynamically.
jsp:attribute Defines dynamically defined XML element's attribute.
jsp:body Defines dynamically defined XML element's body.
jsp:text Use to write template text in JSP pages and documents.
Common Attributes:
There are two attributes that are common to all Action elements: the id attribute and
the scope attribute.
Id attribute: The id attribute uniquely identifies the Action element, and allows the
action to be referenced inside the JSP page. If the Action creates an instance of an
object the id value can be used to reference it through the implicit object PageContext
Scope attribute: This attribute identifies the lifecycle of the Action element. The id
attribute and the scope attribute are directly related, as the scope attribute determines
the lifespan of the object associated with the id. The scope attribute has four possible
values: (a) page, (b)request, (c)session, and (d) application.
25
ASETL CSE/VI SEM AJP LAB
This action lets you insert files into the page being generated. The syntax looks like this:
Unlike the include directive, which inserts the file at the time the JSP page is translated into
a servlet, this action inserts the file at the time the page is requested.
Attribute Description
page The relative URL of the page to be included.
flush The boolean attribute determines whether the included resource has its buffer
flushed before it is included.
Example:
Let us define following two files (a)date.jsp and (b) main.jsp as follows:
1. <p>
2. Today's date: <%= (new java.util.Date()).toLocaleString()%>
3. </p>
1. <html>
2. <head>
3. <title>The include Action Example</title>
4. </head>
5. <body>
6. <center>
7. <h2>The include action Example</h2>
8. <jsp:include page="date.jsp" flush="true" />
9. </center>
10. </body>
11. </html>
Now let us keep all these files in root directory and try to access main.jsp. This would display
result something like this:
26
ASETL CSE/VI SEM AJP LAB
The useBean action is quite versatile. It first searches for an existing object utilizing the id
and scope variables. If an object is not found, it then tries to create the specified object.
Once a bean class is loaded, you can use jsp:setProperty and jsp:getProperty actions to
modify and retrieve bean properties.
Attribute Description
class Designates the full package name of the bean.
type Specifies the type of the variable that will refer to the object.
beanName Gives the name of the bean as specified by the instantiate () method of the
java.beans.Beans class.
Let us discuss about jsp:setProperty and jsp:getProperty actions before giving a valid
example related to these actions.
The setProperty action sets the properties of a Bean. The Bean must have been previously
defined before this action. There are two basic ways to use the setProperty action:
You can use jsp:setProperty after, but outside of, a jsp:useBean element, as below:
In this case, the jsp:setProperty is executed regardless of whether a new bean was instantiated
or an existing bean was found.
A second context in which jsp:setProperty can appear is inside the body of a jsp:useBean
element, as below:
27
ASETL CSE/VI SEM AJP LAB
Here, the jsp:setProperty is executed only if a new object was instantiated, not if an existing
one was found.
Attribute Description
name Designates the bean whose property will be set. The Bean must have been
previously defined.
property Indicates the property you want to set. A value of "*" means that all request
parameters whose names match bean property names will be passed to the
appropriate setter methods.
value The value that is to be assigned to the given property. The the parameter's
value is null, or the parameter does not exist, the setProperty action is ignored.
param The param attribute is the name of the request parameter whose value the
property is to receive. You can't use both value and param, but it is permissible
to use neither.
The getProperty action is used to retrieve the value of a given property and converts it to a
string, and finally inserts it into the output.
The getProperty action has only two attributes, both of which are required ans simple syntax
is as follows:
Attribute Description
name The name of the Bean that has a property to be retrieved. The Bean must have
been previously defined.
property The property attribute is the name of the Bean property to be retrieved.
Example:
1. /* File: TestBean.java */
2. package action;
28
ASETL CSE/VI SEM AJP LAB
Compile above code to generated TestBean.class file and make sure that you copied
TestBean.class in C:\apache-tomcat-7.0.2\webapps\WEB-INF\classes\action folder and
CLASSPATH variable should also be set to this folder:
Now use the following code in main.jsp file which loads the bean and sets/gets a simple String
parameter:
1. <html>
2. <head>
3. <title>Using JavaBeans in JSP</title>
4. </head>
5. <body>
6. <center>
7. <h2>Using JavaBeans in JSP</h2>
8. <jsp:useBean id="test" class="action.TestBean" />
9. <jsp:setProperty name="test"
property="message"
value="Hello JSP..." />
10. <p>Got message....</p>
11. <jsp:getProperty name="test" property="message" />
12. </center>
13. </body>
14. </html>
29
ASETL CSE/VI SEM AJP LAB
Got message....
Hello JSP...
The forward action terminates the action of the current page and forwards the request to
another resource such as a static page, another JSP page, or a Java Servlet.
Attribute Description
page Should consist of a relative URL of another resource such as a static page,
another JSP page, or a Java Servlet.
Example:
Let us reuse following two files (a) date.jsp and (b) main.jsp as follows:
1. <p>
2. Today's date: <%= (new java.util.Date()).toLocaleString()%>
3. </p>
1. <html>
2. <head>
3. <title>The include Action Example</title>
4. </head>
5. <body>
6. <center>
7. <h2>The include action Example</h2>
8. <jsp:forward page="date.jsp" />
9. </center>
30
ASETL CSE/VI SEM AJP LAB
10. </body>
11. </html>
Now let us keep all these files in root directory and try to access main.jsp. This would display
result something like as below. Here it discarded content from main page and displayed
content from forwarded page only.
The plugin action is used to insert Java components into a JSP page. It determines the type of
browser and inserts the <object> or <embed> tags as needed.
If the needed plugin is not present, it downloads the plugin and then executes the Java
component. The Java component can be either an Applet or a JavaBean.
The plugin action has several attributes that correspond to common HTML tags used to format
Java components. The <param> element can also be used to send parameters to the Applet or
Bean.
You can try this action using some applet if you are interested. A new element, the <fallback>
element, can be used to specify an error string to be sent to the user in case the component
fails.
31
ASETL CSE/VI SEM AJP LAB
The <jsp:element>, lt;jsp:attribute> and <jsp:body> actions are used to define XML elements
dynamically. The word dynamically is important, because it means that the XML elements
can be generated at request time rather than statically at compile time.
1. <html xmlns="http://www.w3c.org/1999/xhtml"
2. xmlns:jsp="http://java.sun.com/JSP/Page">
3. <head><title>Generate XML Element</title></head>
4. <body>
5. <xmlElement xmlElementAttr="Value for the attribute">
6. Body for XML element
7. </xmlElement>
8. </body>
9. </html>
The <jsp:text> Action
The <jsp:text> action can be used to write template text in JSP pages and documents.
Following is the simple syntax for this action:
32
ASETL CSE/VI SEM AJP LAB
1. <jsp:text>Template data</jsp:text>
The body of the template cannot contain other elements; it can only contain text and EL
expressions ( Note: EL expressions are explained in subsequent chapter). Note that in XML
files, you cannot use expressions such as ${whatever > 0}, because the greater than signs are
illegal. Instead, use the gt form, such as ${whatever gt 0} or an alternative is to embed the
value in a CDATA section.
1. <jsp:text><![CDATA[<br>]]></jsp:text>
If you need to include a DOCTYPE declaration, for instance for XHTML, you must also use
the <jsp:text> element as follows:
1. <jsp:text><![CDATA[<!DOCTYPE html
2. PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
3. "DTD/xhtml1-strict.dtd">]]>
4. </jsp:text>
5. <head><title>jsp:text action</title></head>
6. <body>
7. <books><book><jsp:text>
8. Welcome to JSP Programming
9. </jsp:text></book></books>
10. </body>
11. </html>
33
ASETL CSE/VI SEM AJP LAB
Procedure:-
Stateless Session Bean
Stateless Session bean is a business object that represents business logic only. It doesn't have
state (data).
In other words, conversational state between multiple method calls is not maintained by the
container in case of stateless session bean.
The stateless bean objects are pooled by the EJB container to service the request on demand.
It can be accessed by one client at a time. In case of concurrent access, EJB container routes
each request to different instance.
1. @Stateless
2. @PostConstruct
3. @PreDestroy
There is only two states of stateless session bean: does not exist and ready. It is explained by
the figure given below.
34
ASETL CSE/VI SEM AJP LAB
EJB Container creates and maintains a pool of session bean first. It injects the dependency if
then calls the @PostConstruct method if any. Now actual business logic method is invoked by
the client. Then, container calls @PreDestory method if any. Now bean is ready for garbage
collection.
To develop stateless bean application, we are going to use Eclipse IDE and glassfish 3 server.
To create EJB application, you need to create bean component and bean client.
To create the stateless bean component, you need to create a remote interface and a bean class.
File: AdderImplRemote.java
1. package com.javatpoint;
2. import javax.ejb.Remote;
3.
4. @Remote
5. public interface AdderImplRemote {
6. int add(int a,int b);
7. }
File: AdderImpl.java
1. package com.javatpoint;
2. import javax.ejb.Stateless;
3.
4. @Stateless(mappedName="st1")
5. public class AdderImpl implements AdderImplRemote {
6. public int add(int a,int b){
7. return a+b;
8. }
9. }
The stateless bean client may be local, remote or webservice client. Here, we are going to create
remote client. It is console based application. Here, we are not using dependency injection. The
dependency injection can be used with web based client only.
File: AdderImpl.java
1. package com.javatpoint;
35
ASETL CSE/VI SEM AJP LAB
2. import javax.naming.Context;
3. import javax.naming.InitialContext;
4.
5. public class Test {
6. public static void main(String[] args)throws Exception {
7. Context context=new InitialContext();
8. AdderImplRemote remote=(AdderImplRemote)context.lookup("st1");
9. System.out.println(remote.add(32,32));
10. }
11. }
36
ASETL CSE/VI SEM AJP LAB
Procedure:-
Enterprise JavaBeans: Working with Entity and Session Beans
Today, more and more developers want to write distributed transactional applications for the
enterprise, and leverage the speed, security, and reliability of server-side technology. One
approach is to use a multitiered model where a thin-client application invokes business logic
that executes on the server.
Normally, thin-client multitiered applications are hard to write because they involve many lines
of intricate code to handle transaction and state management, multithreading, resource pooling,
and other complex low-level details. The Enterprise JavaBeans (EJB) architecture makes these
applications easy to write because it separates the low-level details from the business logic.
You concentrate on creating the best business solution and leave the rest to the underlying
architecture.
To show you how it works, this article walks through a very simple web-based application
where the thin-client is a servlet. The servlet invokes enterprise Beans for database reads and
writes and to perform a simple calculation.
There are two types of enterprise Beans: session Beans and entity Beans. An enterprise Bean
that implements a business task is a session Bean, and an enterprise Bean that implements a
business entity is an entity Bean.
A session Bean represents a transient conversation with a client, and might execute
database reads and writes. A session Bean might invoke the JDBC calls itself or it might
use an entity Bean to make the call, in which case the session Bean is a client to the
entity Bean. A session Bean's fields contain the state of the conversation and are
transient. If the server or client crashes, the session Bean is gone. This model is typically
used with database programming languages such as PL/SQL.
An entity Bean represents data in a database and the methods to act on that data. In a
relational database context for a table of employee information, there is one Bean for
each row in the table. Entity Beans are transactional and long-lived. As long as the data
remains in the database, the entity Bean exists. This model can be easily used for
relational databases and is not restricted to object databases.
37
ASETL CSE/VI SEM AJP LAB
An enterprise Bean's remote interface describes the Bean's methods, or what the Bean
does. A client program or another enterprise Bean calls the methods defined in the
remote interface to invoke the business logic implemented by the Bean.
An enterprise Bean's home interface describes how a client program or another
enterprise Bean creates, finds, and removes that enterprise Bean from its container.
The container, shown in light blue (cyan), provides the interface between the enterprise
Bean and the low-level platform-specific functionality that supports the enterprise
Bean.
You do not need to know how an enterprise Bean is implemented to use it; all you need to
know are its methods. You might or might not write your own enterprise Beans to use in an
application. It is possible and often desirable to use enterprise Beans written by a provider that
you assemble into an application.
Deployment tools and an EJB Home Server are essential to running the application code. The
deployment tools generate enterprise Bean containers, which are classes that provide an
interface to the low-level implementations in a given EJB Server. The server provider can
include containers and deployment tools for their server and will typically publish their low-
level interfaces so other vendors can develop containers and deployment tools for their server.
38
ASETL CSE/VI SEM AJP LAB
The simple example uses the EJB Server created by EJBHome. Visit this site for a free
reference implementation that includes the EJB Server and deployment tools for generating
containers. The site also provides tutorials to walk you through example programs that come
with the download.
Source Code
The source code files for the example are listed below. The example program requires a
database table named bonus with the following fields:
Other naming conventions are used within the source code and discussed below where they
appear. While source file-naming conventions are standard across EJB Server
implementations, naming conventions used within the source are specific to the EJB Server or
deployment tool you use.
Client Program
BonusServlet.java.
Running the Application
Entity Bean
39
ASETL CSE/VI SEM AJP LAB
Session Bean
Calc.java, the remote interface with this method:
o calcBonus
CalcHome.java, the home interface with this method:
o create
CalcBean.java, an enterprise Bean with these public fields and methods:
o int bonus
o int calcBonus
o ejbCreate
Container Classes
When the entity and session Beans are deployed, a number of container source and class files
are generated with the following prefixes. A container is a set of classes generated by the
deployment tool that manages an enterprise Bean's persistence, transactional properties, and
security.
EJBHomeBonus*.java
EJBHomeBonus*.class
EJBHomeCalc*.java
EJBHomeCalc*.class
Client Program
The thin-client BonusServlet.java declares variables and parameter values of specific types to
locate the database table, create the home interface, and invoke the entity and session Bean
methods.
Note: To keep the code simple, data values that the servlet would normally receive from user
input to a browser form is hard coded.
These are the import and declarations statements. The entity Bean remote interface type
is Bonus and maps to the database table name, which is also Bonus.
The socsec and bonus variables map to the fields in the database table. Variable names that
map to the database table or fields in the database are case insensitive.
1. import javax.servlet.*;
2. import javax.servlet.http.*;
3. import java.io.*;
4. import java.util.Properties;
5. import javax.naming.*;
6. //location of Bean classes
7. import com.ejbhome.examples.*;
40
ASETL CSE/VI SEM AJP LAB
The EJB Home Server uses the beans.properties configuration file to map enterprise Beans to
the home interfaces for their respective container classes. Here is how the mapping looks. The
container classes are not created until the Beans are deployed, but you can put the entry into
this file before you deploy because the naming convention is consistent. The
values calcs and bonuses are used in the next code segment for the enterprise Bean lookup. The
values in this file and the strings used in the code have to match exactly so the EJB Home
Server can look up the enterprise Bean home interface.
1. calcs=com.ejbhome.examples.EJBHomeCalcHome
2. bonuses=com.ejbhome.examples.EJBHomeBonusHome
3. Here is the servlet init method implementation. The JNDI API is used to look up the
Beans and containers.
4. public void init(ServletConfig config)
5. throws ServletException{
6. try{
7. Properties env = new Properties();
8. env.put("java.naming.factory.initial",
9. "com.ejbhome.naming.
10. //spi.rmi.RMIInitCtxFactory");
11. Context ctx = new InitialContext(env);
12. //Look up home interfaces and containers
13. //for entity and session beans.
14. //Strings map to settings in
15. the beans.properties file.
16. homebonus =
17. (BonusHome)ctx.lookup("bonuses");
18. homecalc =
19. (CalcHome)ctx.lookup("calcs");
1. try{
2. socsec = 555220000;
41
ASETL CSE/VI SEM AJP LAB
3. bonus = 200;
1. try{
2. //Instantiate a primary key object
3. BonusPK PK = new BonusPK(555220000);
4. //Locate a record with the primary key
5. rec1 = hmebonus.findByPrimaryKey(PK);
6. //Use the entity Bean home interface
7. //to retrieve current bonus value
8. retbonus = rec1.getBonus();
This next code segment creates the session Bean's home interface, and uses the home interface
to call the session Bean's calcBonus method. The hard-coded values passed to
the calcBonus method would normally be received by user input to a form in the browser. For
simplicity, the code to display the final bonus in the browser is not included in the segment,
but here is the entire source file for the BonusServlet.java servlet.
1. //Calculate bonus
2. int base = 100;
3. int perf=5, company=2;
4. theCalculation = homecalc.create();
5. int calc = theCalculation.calcBonus(
a. base, perf, company);
6. System.out.println(calc);
7. rec1.addBonus(calc);
8. retbonus = rec1.getBonus();
9. } catch (Exception FinderException) {
10. FinderException.printStackTrace();
11. }
42
ASETL CSE/VI SEM AJP LAB
Record 1
SocSec:555220000
Bonus Total: 200
Record 2
1. package com.ejbhome.examples;
2. import javax.ejb.*;
3. import java.rmi.*;
4. public interface BonusHome extends EJBHome {
5. Bonus create(int bonus, int socsec)
6. throws CreateException, RemoteException;
7. Bonus findByPrimaryKey(BonusPK socsec)
8. throws FinderException, RemoteException;
9. }
When the home interface is instantiated, the EJB Home Server also creates the remote interface
and enterprise Bean instances. Here is the remote interface. It extends EJBObject and declares
43
ASETL CSE/VI SEM AJP LAB
the BonusBean methods. It also follows the rules of the RMI API in that the arguments and
return types for each method must be serializable and the methods should
throw java.rmi.RemoteException as one of its exception.
package com.ejbhome.examples;
1. import javax.ejb.*;
2. import java.rmi.*;
The EJBHome server requires a container-managed entity Bean to have a primary key class
with a public primary key field (or fields, if using composite primary keys). You can have the
container manage an enterprise Bean or write the code to manage the Bean yourself. In this
example, both Beans are container-managed, and you should always let the container manage
an entity Bean.
Here is the primary key class. The primary key in the Bonus table is socsec, and so socsec is a
public field in this class that is assigned a value when the class is constructed.
1. package com.ejbhome.examples;
8. public BonusPK() {}
9. }
Now for a look at the entity bean source code. It implements EntityBean and the developer-
defined and interface methods. It should follow the rules of the RMI API in that the arguments
and return types for each method must be serializable and the methods should
throw java.rmi.RemoteException as one of its exception.
1. package com.ejbhome.examples;
2. import java.rmi.RemoteException;
3. import javax.ejb.*;
44
ASETL CSE/VI SEM AJP LAB
45
ASETL CSE/VI SEM AJP LAB
The home interface does not have a FindByPrimaryKey method because no database access is
involved. A session Bean could perform database access, and would then need
a FindByPrimaryKey method, but the simple example does not need it.
1. package com.ejbhome.examples;
2. import javax.ejb.*;
3. import java.rmi.*;
4. public interface CalcHome extends EJBHome {
5. Calc create() throws CreateException, RemoteException;
6. }
7. The remote interface declares the session Bean's one method.
8. package com.ejbhome.examples;
9. import javax.ejb.*;
10. import java.rmi.*;
11. public interface Calc extends EJBObject {
12. int calcBonus(int base, int perf, int company) throws RemoteException;
13. }
14. The session Bean implements SessionBean and the developer-defined and interface
methods.
15. package com.ejbhome.examples;
16. import java.rmi.RemoteException;
17. import javax.ejb.*;
18. public class CalcBean implements SessionBean
19. throws Remote Exception {
20. public int bonus;
21. protected SessionContext ctx;
22. public int calcBonus(int base,
23. int perf, int company) {
24. int calc = (base*perf*company);
25. this.bonus += calc;
26. return this.bonus;
27. }
28. public void ejbCreate() throws CreateException,
29. RemoteException {}
46
ASETL CSE/VI SEM AJP LAB
39. RemoteException { }
40. public void ejbPassivate() throws
41. RemoteException { }
42. public void ejbLoad() throws
43. RemoteException { }
44. public void ejbStore() throws
45. RemoteException { }
46. }
Container Classes
The Deployer tool generates these container classes for BonusBean and CalcBean.
BonusBean CalcBean
EJBHomeBonusBean.class EJBHomeCalcBean.class
EJBHomeBonusBean.java EJBHomeCalcBean.java
EJBHomeBonusHome.class EJBHomeCalcHome.class
EJBHomeBonusHome.java EJBHomeCalcHome.java
EJBHomeBonusHome_Skel.class EJBHomeCalcHome_Skel.class
EJBHomeBonusHome_Skel.java EJBHomeCalcHome_Skel.java
EJBHomeBonusHome_Stub.class EJBHomeCalcHome_Stub.class
EJBHomeBonusHome_Stub.java EJBHomeCalcHome_Stub.java
EJBHomeBonusMetaData.class EJBHomeCalcMetaData.class
EJBHomeBonusMetaData.java EJBHomeCalcMetaData.java
EJBHomeRemoteBonus.class EJBHomeRemoteCalc.class
EJBHomeRemoteBonus.java EJBHomeRemoteCalc.java
EJBHomeRemoteBonus_Skel.class EJBHomeRemoteCalc_Skel.class
EJBHomeRemoteBonus_Skel.java EJBHomeRemoteCalc_Skel.java
EJBHomeRemoteBonus_Stub.class EJBHomeRemoteCalc_Stub.class
EJBHomeRemoteBonus_Stub.java EJBHomeRemoteCalc_Stub.java
47
ASETL CSE/VI SEM AJP LAB
Procedure:-
we are creating the struts 2 without IDE. We can simply create the struts 2 application by
following these simple steps:
1. Create the directory structure
2. Create input page (index.jsp)
3. Provide the entry of Controller in (web.xml) file
4. Create the action class (Product.java)
5. Map the request with the action in (struts.xml) file and define the view components
6. Create view components (welcome.jsp)
7. load the jar files
8. start server and deploy the project
1) Create the directory structure
The directory structure of struts 2 is same as servlet/JSP. Here, struts.xml file must be located
in the classes folder.
48
ASETL CSE/VI SEM AJP LAB
49
ASETL CSE/VI SEM AJP LAB
17. }
18. public float getPrice() {
19. return price;
20. }
21. public void setPrice(float price) {
22. this.price = price;
23. }
24.
25. public String execute(){
26. return "success";
27. }
28. }
5) Map the request in (struts.xml) file and define the view components
It is the important file from where struts framework gets information about the action and
decides which result to be invoked. Here, we have used many elements such as struts, package,
action and result.
struts element is the root elements of this file. It represents an application.
package element is the sub element of struts. It represents a module of the application. It
generally extends the struts-default package where many interceptors and result types are
defined.
action element is the sub element of package. It represents an action to be invoked for the
incoming request. It has name, class and method attributes. If you don't specify name attribute
by default execute() method will be invoked for the specified action class.
result element is the sub element of action. It represents an view (result) that will be invoked.
Struts framework checks the string returned by the action class, if it returns success, result page
for the action is invoked whose name is success or has no name. It has name and type attributes.
Both are optional. If you don't specify the result name, by default success is assumed as the
result name. If you don't specify the type attribute, by default dispatcher is considered as the
default result type. We will learn about result types later.
struts.xml
1. <?xml version="1.0" encoding="UTF-8" ?>
2. <!DOCTYPE struts PUBLIC "-//Apache Software Foundation//DTD Struts
3. Configuration 2.1//EN" "http://struts.apache.org/dtds/struts-2.1.dtd">
4. <struts>
5. <package name="default" extends="struts-default">
6.
7. <action name="product" class="com.javatpoint.Product">
8. <result name="success">welcome.jsp</result>
9. </action>
10.
11. </package>
12. </struts>
50
ASETL CSE/VI SEM AJP LAB
51
ASETL CSE/VI SEM AJP LAB
Procedure:-
We will cover the basic CRUD (Create, Read, Update and Delete) Operation. So that you will
be able to handle MySQL Database after going through this experiment.
Creating the MySQL Database
Employee Table
As you can see I have a table named employee with 4 columns (id, name, designation,
salary). Id is set auto increment and primary key so we do not need to insert id.
Now we will create our php scripts.
1 <?php
2 /*
3 author: Belal Khan
4 website: https://www.simplifiedcoding.net
5
6 My Database is androiddb
7 you need to change the database name rest the things are default if you are using wamp
8 or xampp server
9 You may need to change the host user name or password if you have changed the
10 defaults in your server
11 */
12
52
ASETL CSE/VI SEM AJP LAB
13 //Defining Constants
14 define('HOST','localhost');
15 define('USER','root');
16 define('PASS','');
17 define('DB','androiddb');
18 //Connecting to Database
$con = mysqli_connect(HOST,USER,PASS,DB) or die('Unable to Connect');
addEmp.php
<?php
1
if($_SERVER['REQUEST_METHOD']=='POST'){
2
3
//Getting values
4
$name = $_POST['name'];
5
$desg = $_POST['desg'];
6
$sal = $_POST['salary'];
7
8
//Creating an sql query
9
$sql = "INSERT INTO employee (name,designation,salary) VALUES
10
('$name','$desg','$sal')";
11
12
//Importing our db connection script
13
require_once('dbConnect.php');
14
15
//Executing query to database
16
if(mysqli_query($con,$sql)){
17
echo 'Employee Added Successfully';
18
}else{
19
echo 'Could Not Add Employee';
20
}
21
22
//Closing the database
23
mysqli_close($con);
24
}
Now after adding an employee we will fetch the name and id of all the employees. So
that user can select a particular employee to see all the details of that employee.
For this create a new file named getAllEmp.php and write the following code.
getAllEmp.php
1 <?php
2 //Importing Database Script
3 require_once('dbConnect.php');
4
5 //Creating sql query
6 $sql = "SELECT * FROM employee";
53
ASETL CSE/VI SEM AJP LAB
7
8 //getting result
9 $r = mysqli_query($con,$sql);
10
11 //creating a blank array
12 $result = array();
13
14 //looping through all the records fetched
15 while($row = mysqli_fetch_array($r)){
16
17 //Pushing name and id in the blank array created
18 array_push($result,array(
19 "id"=>$row['id'],
20 "name"=>$row['name']
21 ));
22 }
23
24 //Displaying the array in json format
25 echo json_encode(array('result'=>$result));
26
27 mysqli_close($con);
Now we need to display a selected employee. For this create a new file
named getEmp.php and write the following code.
getEmp.php
1 <?php
2
3 //Getting the requested id
4 $id = $_GET['id'];
5
6 //Importing database
7 require_once('dbConnect.php');
8
9 //Creating sql query with where clause to get an specific employee
10 $sql = "SELECT * FROM employee WHERE id=$id";
11
12 //getting result
13 $r = mysqli_query($con,$sql);
14
15 //pushing result to an array
16 $result = array();
17 $row = mysqli_fetch_array($r);
18 array_push($result,array(
19 "id"=>$row['id'],
20 "name"=>$row['name'],
21 "desg"=>$row['designation'],
22 "salary"=>$row['salary']
23 ));
54
ASETL CSE/VI SEM AJP LAB
24
25 //displaying in json format
26 echo json_encode(array('result'=>$result));
27
28 mysqli_close($con);
Now in CRUD we have completed (C-Create (Insert) and R-Read(Fetch)) the next
is U-Update. We may need to update the details of an existing employee. For this
create a new file named updateEmp.phpand write the following code.
updateEmp.php
<?php
1
if($_SERVER['REQUEST_METHOD']=='POST'){
2
//Getting values
3
$id = $_POST['id'];
4
$name = $_POST['name'];
5
$desg = $_POST['desg'];
6
$sal = $_POST['salary'];
7
8
//importing database connection script
9
require_once('dbConnect.php');
10
11
//Creating sql query
12
$sql = "UPDATE employee SET name = '$name', designation = '$desg', salary = '$sal'
13
WHERE id = $id;";
14
15
//Updating database table
16
if(mysqli_query($con,$sql)){
17
echo 'Employee Updated Successfully';
18
}else{
19
echo 'Could Not Update Employee Try Again';
20
}
21
22
//closing connection
23
mysqli_close($con);
24
}
Now the final thing which is D-Delete. We may need to delete an existing employee.
For this create a new file named deleteEmp.php and write the following.
deleteEmp.php
1 <?php
2 //Getting Id
3 $id = $_GET['id'];
4
5 //Importing database
6 require_once('dbConnect.php');
7
8 //Creating sql query
55
ASETL CSE/VI SEM AJP LAB
Now thats all we have created all the scripts for CRUD operation. Now we need the
address of these scripts. In my case I am using wamp server. And my server is
running in my ip -> http://192.168.94.1
To know what is the ip in your system you can use ipconfig command. Open
command prompt and write ipconfig and hit enter.
So we are using wamp server and for wamp the root directory is www (usually
c:/wamp/www). And we stored my scripts inside www/Android/CRUD. So the paths
to my scripts would be
http://192.168.94.1/Android/CRUD/file_name.php
Create a new Android Studio project. For this Android MySQL Tutorial I have
created my project named MySQLCRUD.
In this Android MySQL Application we will be performing some network operations
we need internet permission. So add internet permission to your manifest file.
Now create a new java class inside your package named Config. And write the
following code.
56
ASETL CSE/VI SEM AJP LAB
5 */
6 public class Config {
7
8 //Address of our scripts of the CRUD
9 public static final String
10 URL_ADD="http://192.168.94.1/Android/CRUD/addEmp.php";
11 public static final String URL_GET_ALL =
12 "http://192.168.94.1/Android/CRUD/getAllEmp.php";
13 public static final String URL_GET_EMP =
14 "http://192.168.94.1/Android/CRUD/getEmp.php?id=";
15 public static final String URL_UPDATE_EMP =
16 "http://192.168.94.1/Android/CRUD/updateEmp.php";
17 public static final String URL_DELETE_EMP =
18 "http://192.168.94.1/Android/CRUD/deleteEmp.php?id=";
19
20 //Keys that will be used to send the request to php scripts
21 public static final String KEY_EMP_ID = "id";
22 public static final String KEY_EMP_NAME = "name";
23 public static final String KEY_EMP_DESG = "desg";
24 public static final String KEY_EMP_SAL = "salary";
25
26 //JSON Tags
27 public static final String TAG_JSON_ARRAY="result";
28 public static final String TAG_ID = "id";
29 public static final String TAG_NAME = "name";
30 public static final String TAG_DESG = "desg";
public static final String TAG_SAL = "salary";
We will create a separate class for handling our networking request. So create a new
class inside your package named RequestHandler. And write the following code.
RequestHandler.java
1 package net.simplifiedcoding.mysqlcrud;
2
3 import java.io.BufferedReader;
4 import java.io.BufferedWriter;
5 import java.io.InputStreamReader;
6 import java.io.OutputStream;
7 import java.io.OutputStreamWriter;
8 import java.io.UnsupportedEncodingException;
9 import java.net.HttpURLConnection;
10 import java.net.URL;
11 import java.net.URLEncoder;
12 import java.util.HashMap;
13 import java.util.Map;
57
ASETL CSE/VI SEM AJP LAB
14
15 import javax.net.ssl.HttpsURLConnection;
16
17 /**
18 * Created by Belal on 10/24/2015.
19 */
20
21 public class RequestHandler {
22
23 //Method to send httpPostRequest
24 //This method is taking two arguments
25 //First argument is the URL of the script to which we will send the request
26 //Other is an HashMap with name value pairs containing the data to be send with the
27 request
28 public String sendPostRequest(String requestURL,
29 HashMap<String, String> postDataParams) {
30 //Creating a URL
31 URL url;
32
33 //StringBuilder object to store the message retrieved from the server
34 StringBuilder sb = new StringBuilder();
35 try {
36 //Initializing Url
37 url = new URL(requestURL);
38
39 //Creating an httmlurl connection
40 HttpURLConnection conn = (HttpURLConnection) url.openConnection();
41
42 //Configuring connection properties
43 conn.setReadTimeout(15000);
44 conn.setConnectTimeout(15000);
45 conn.setRequestMethod("POST");
46 conn.setDoInput(true);
47 conn.setDoOutput(true);
48
49 //Creating an output stream
50 OutputStream os = conn.getOutputStream();
51
52 //Writing parameters to the request
53 //We are using a method getPostDataString which is defined below
54 BufferedWriter writer = new BufferedWriter(
55 new OutputStreamWriter(os, "UTF-8"));
56 writer.write(getPostDataString(postDataParams));
57
58 writer.flush();
59 writer.close();
60 os.close();
61 int responseCode = conn.getResponseCode();
62
63 if (responseCode == HttpsURLConnection.HTTP_OK) {
58
ASETL CSE/VI SEM AJP LAB
64
65 BufferedReader br = new BufferedReader(new
66 InputStreamReader(conn.getInputStream()));
67 sb = new StringBuilder();
68 String response;
69 //Reading server response
70 while ((response = br.readLine()) != null){
71 sb.append(response);
72 }
73 }
74
75 } catch (Exception e) {
76 e.printStackTrace();
77 }
78 return sb.toString();
79 }
80
81 public String sendGetRequest(String requestURL){
82 StringBuilder sb =new StringBuilder();
83 try {
84 URL url = new URL(requestURL);
85 HttpURLConnection con = (HttpURLConnection) url.openConnection();
86 BufferedReader bufferedReader = new BufferedReader(new
87 InputStreamReader(con.getInputStream()));
88
89 String s;
90 while((s=bufferedReader.readLine())!=null){
91 sb.append(s+"\n");
92 }
93 }catch(Exception e){
94 }
95 return sb.toString();
96 }
97
98 public String sendGetRequestParam(String requestURL, String id){
99 StringBuilder sb =new StringBuilder();
100 try {
101 URL url = new URL(requestURL+id);
102 HttpURLConnection con = (HttpURLConnection) url.openConnection();
103 BufferedReader bufferedReader = new BufferedReader(new
104 InputStreamReader(con.getInputStream()));
105
106 String s;
107 while((s=bufferedReader.readLine())!=null){
108 sb.append(s+"\n");
109 }
110 }catch(Exception e){
111 }
112 return sb.toString();
113 }
59
ASETL CSE/VI SEM AJP LAB
114
115 private String getPostDataString(HashMap<String, String> params) throws
116 UnsupportedEncodingException {
117 StringBuilder result = new StringBuilder();
118 boolean first = true;
119 for (Map.Entry<String, String> entry : params.entrySet()) {
120 if (first)
121 first = false;
122 else
123 result.append("&");
124
125 result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
126 result.append("=");
127 result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
}
return result.toString();
}
}
For our application we will need two more activities other than our MainActivity.
One is to show the list of all employee from where user can select a particular
employee to see. And the other one is to show the details of selected employee from
where we can update and delete the employee as well. And from
the MainActivity we will add an employee. So before going further create two more
activities named ViewAllEmployee and ViewEmployee.
Now for activity_main.xml create the following layout
60
ASETL CSE/VI SEM AJP LAB
8 android:paddingTop="@dimen/activity_vertical_margin"
9 android:paddingBottom="@dimen/activity_vertical_margin"
10 tools:context=".MainActivity">
11
12 <TextView
13 android:layout_width="wrap_content"
14 android:layout_height="wrap_content"
15 android:text="Employee Name" />
16
17 <EditText
18 android:layout_width="match_parent"
19 android:layout_height="wrap_content"
20 android:id="@+id/editTextName" />
21
22 <TextView
23 android:layout_width="wrap_content"
24 android:layout_height="wrap_content"
25 android:text="Designation" />
26
27 <EditText
28 android:layout_width="match_parent"
29 android:layout_height="wrap_content"
30 android:id="@+id/editTextDesg" />
31
32 <TextView
33 android:layout_width="wrap_content"
34 android:layout_height="wrap_content"
35 android:text="Salary" />
36
37 <EditText
38 android:layout_width="match_parent"
39 android:layout_height="wrap_content"
40 android:id="@+id/editTextSalary" />
41
42 <Button
43 android:layout_width="match_parent"
44 android:layout_height="wrap_content"
45 android:text="Add Employee"
46 android:id="@+id/buttonAdd" />
47
48 <Button
49 android:layout_width="match_parent"
50 android:layout_height="wrap_content"
51 android:text="View Employee"
android:id="@+id/buttonView" />
</LinearLayout>
61
ASETL CSE/VI SEM AJP LAB
MainActivity.java
1 package net.simplifiedcoding.mysqlcrud;
2
3 import android.app.ProgressDialog;
4 import android.content.Intent;
5 import android.os.AsyncTask;
6 import android.support.v7.app.AppCompatActivity;
7 import android.os.Bundle;
8 import android.view.Menu;
9 import android.view.MenuItem;
10 import android.view.View;
11 import android.widget.Button;
12 import android.widget.EditText;
13 import android.widget.Toast;
14
15 import java.util.HashMap;
16
17 public class MainActivity extends AppCompatActivity implements
18 View.OnClickListener{
19
20 //Defining views
21 private EditText editTextName;
22 private EditText editTextDesg;
23 private EditText editTextSal;
24
25 private Button buttonAdd;
26 private Button buttonView;
27
28 @Override
29 protected void onCreate(Bundle savedInstanceState) {
30 super.onCreate(savedInstanceState);
31 setContentView(R.layout.activity_main);
32
33 //Initializing views
34 editTextName = (EditText) findViewById(R.id.editTextName);
35 editTextDesg = (EditText) findViewById(R.id.editTextDesg);
36 editTextSal = (EditText) findViewById(R.id.editTextSalary);
37
38 buttonAdd = (Button) findViewById(R.id.buttonAdd);
39 buttonView = (Button) findViewById(R.id.buttonView);
40
41 //Setting listeners to button
42 buttonAdd.setOnClickListener(this);
43 buttonView.setOnClickListener(this);
44 }
45
46
47 //Adding an employee
48 private void addEmployee(){
49
62
ASETL CSE/VI SEM AJP LAB
63
ASETL CSE/VI SEM AJP LAB
Now from this activity we will move to the activity ViewAllEmployee. So create the
following layout in ViewAllEmployee’s layout file which
is activity_view_all_employee.xml.
In this activity we will create a ListView only.
You can use the following code for the above layout
Because we are creating a ListView, we need one more Layout Resource File for our
ListView. Inside layouts create a new xml file named list_item.xml and write the
following code.
64
ASETL CSE/VI SEM AJP LAB
Java
1 package net.simplifiedcoding.mysqlcrud;
2
3 import android.app.ProgressDialog;
4 import android.content.Intent;
5 import android.os.AsyncTask;
6 import android.support.v7.app.AppCompatActivity;
7 import android.os.Bundle;
8 import android.view.Menu;
9 import android.view.MenuItem;
10 import android.view.View;
11 import android.widget.AdapterView;
12 import android.widget.ListAdapter;
13 import android.widget.ListView;
14 import android.widget.SimpleAdapter;
15 import android.widget.Toast;
16
17 import org.json.JSONArray;
18 import org.json.JSONException;
19 import org.json.JSONObject;
20
21 import java.util.ArrayList;
22 import java.util.HashMap;
23
24 public class ViewAllEmployee extends AppCompatActivity implements
25 ListView.OnItemClickListener {
26
27 private ListView listView;
28
65
ASETL CSE/VI SEM AJP LAB
66
ASETL CSE/VI SEM AJP LAB
79 loading = ProgressDialog.show(ViewAllEmployee.this,"Fetching
80 Data","Wait...",false,false);
81 }
82
83 @Override
84 protected void onPostExecute(String s) {
85 super.onPostExecute(s);
86 loading.dismiss();
87 JSON_STRING = s;
88 showEmployee();
89 }
90
91 @Override
92 protected String doInBackground(Void... params) {
93 RequestHandler rh = new RequestHandler();
94 String s = rh.sendGetRequest(Config.URL_GET_ALL);
95 return s;
96 }
97 }
98 GetJSON gj = new GetJSON();
99 gj.execute();
100 }
101
102 @Override
103 public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
104 Intent intent = new Intent(this, ViewEmployee.class);
105 HashMap<String,String> map =(HashMap)parent.getItemAtPosition(position);
106 String empId = map.get(Config.TAG_ID).toString();
107 intent.putExtra(Config.EMP_ID,empId);
startActivity(intent);
}
}
Now from this screen user can select a particular employee to see the detail. And from
this activity we will move to the next activity where we can delete or update
employee. So create following layout for your activity ViewEmployee. For this
activity I have activity_view_employee.xml . So we will create the following layout.
67
ASETL CSE/VI SEM AJP LAB
ViewEmployee.java
1 package net.simplifiedcoding.mysqlcrud;
2
3 import android.app.ProgressDialog;
4 import android.content.DialogInterface;
5 import android.content.Intent;
6 import android.os.AsyncTask;
7 import android.support.v7.app.AlertDialog;
8 import android.support.v7.app.AppCompatActivity;
9 import android.os.Bundle;
10 import android.view.Menu;
11 import android.view.MenuItem;
12 import android.view.View;
13 import android.widget.Button;
14 import android.widget.EditText;
15 import android.widget.Toast;
16
17 import org.json.JSONArray;
18 import org.json.JSONException;
19 import org.json.JSONObject;
20
21 import java.util.HashMap;
22
23 public class ViewEmployee extends AppCompatActivity implements
24 View.OnClickListener {
25
26 private EditText editTextId;
27 private EditText editTextName;
28 private EditText editTextDesg;
29 private EditText editTextSalary;
30
31 private Button buttonUpdate;
32 private Button buttonDelete;
33
68
ASETL CSE/VI SEM AJP LAB
69
ASETL CSE/VI SEM AJP LAB
84 }
85 GetEmployee ge = new GetEmployee();
86 ge.execute();
87 }
88
89 private void showEmployee(String json){
90 try {
91 JSONObject jsonObject = new JSONObject(json);
92 JSONArray result = jsonObject.getJSONArray(Config.TAG_JSON_ARRAY);
93 JSONObject c = result.getJSONObject(0);
94 String name = c.getString(Config.TAG_NAME);
95 String desg = c.getString(Config.TAG_DESG);
96 String sal = c.getString(Config.TAG_SAL);
97
98 editTextName.setText(name);
99 editTextDesg.setText(desg);
100 editTextSalary.setText(sal);
101
102 } catch (JSONException e) {
103 e.printStackTrace();
104 }
105 }
106
107
108 private void updateEmployee(){
109 final String name = editTextName.getText().toString().trim();
110 final String desg = editTextDesg.getText().toString().trim();
111 final String salary = editTextSalary.getText().toString().trim();
112
113 class UpdateEmployee extends AsyncTask<Void,Void,String>{
114 ProgressDialog loading;
115 @Override
116 protected void onPreExecute() {
117 super.onPreExecute();
118 loading =
119 ProgressDialog.show(ViewEmployee.this,"Updating...","Wait...",false,false);
120 }
121
122 @Override
123 protected void onPostExecute(String s) {
124 super.onPostExecute(s);
125 loading.dismiss();
126 Toast.makeText(ViewEmployee.this,s,Toast.LENGTH_LONG).show();
127 }
128
129 @Override
130 protected String doInBackground(Void... params) {
131 HashMap<String,String> hashMap = new HashMap<>();
132 hashMap.put(Config.KEY_EMP_ID,id);
133 hashMap.put(Config.KEY_EMP_NAME,name);
70
ASETL CSE/VI SEM AJP LAB
134 hashMap.put(Config.KEY_EMP_DESG,desg);
135 hashMap.put(Config.KEY_EMP_SAL,salary);
136
137 RequestHandler rh = new RequestHandler();
138
139 String s = rh.sendPostRequest(Config.URL_UPDATE_EMP,hashMap);
140
141 return s;
142 }
143 }
144
145 UpdateEmployee ue = new UpdateEmployee();
146 ue.execute();
147 }
148
149 private void deleteEmployee(){
150 class DeleteEmployee extends AsyncTask<Void,Void,String> {
151 ProgressDialog loading;
152
153 @Override
154 protected void onPreExecute() {
155 super.onPreExecute();
156 loading = ProgressDialog.show(ViewEmployee.this, "Updating...", "Wait...",
157 false, false);
158 }
159
160 @Override
161 protected void onPostExecute(String s) {
162 super.onPostExecute(s);
163 loading.dismiss();
164 Toast.makeText(ViewEmployee.this, s, Toast.LENGTH_LONG).show();
165 }
166
167 @Override
168 protected String doInBackground(Void... params) {
169 RequestHandler rh = new RequestHandler();
170 String s = rh.sendGetRequestParam(Config.URL_DELETE_EMP, id);
171 return s;
172 }
173 }
174
175 DeleteEmployee de = new DeleteEmployee();
176 de.execute();
177 }
178
179 private void confirmDeleteEmployee(){
180 AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(this);
181 alertDialogBuilder.setMessage("Are you sure you want to delete this employee?");
182
183 alertDialogBuilder.setPositiveButton("Yes",
71
ASETL CSE/VI SEM AJP LAB
Now try running your application and you will see the following output.
72
ASETL CSE/VI SEM AJP LAB
73
ASETL CSE/VI SEM AJP LAB
The RMI (Remote Method Invocation) is an API that provides a mechanism to create
distributed application in java. The RMI allows an object to invoke methods on an object
running in another JVM.
The RMI provides remote communication between the applications using two
objects stub and skeleton.
RMI uses stub and skeleton object for communication with the remote object.
A remote object is an object whose method can be invoked from another JVM. Let's
understand the stub and skeleton objects:
stub
The stub is an object, acts as a gateway for the client side. All the outgoing requests are routed
through it. It resides at the client side and represents the remote object. When the caller invokes
method on the stub object, it does the following tasks:
1. It initiates a connection with remote Virtual Machine (JVM),
2. It writes and transmits (marshals) the parameters to the remote Virtual Machine (JVM),
3. It waits for the result
4. It reads (unmarshals) the return value or exception, and
5. It finally, returns the value to the caller.
skeleton
The skeleton is an object, acts as a gateway for the server side object. All the incoming requests
are routed through it. When the skeleton receives the incoming request, it does the following
tasks:
1. It reads the parameter for the remote method
2. It invokes the method on the actual remote object, and
74
ASETL CSE/VI SEM AJP LAB
75
ASETL CSE/VI SEM AJP LAB
3) create the stub and skeleton objects using the rmic tool.
Next step is to create stub and skeleton objects using the rmi compiler. The rmic tool invokes
the RMI compiler and creates stub and skeleton objects.
rmic AdderRemote
76
ASETL CSE/VI SEM AJP LAB
In this example, we are binding the remote object by the name sonoo.
1. import java.rmi.*;
2. import java.rmi.registry.*;
3. public class MyServer{
4. public static void main(String args[]){
5. try{
6. Adder stub=new AdderRemote();
7. Naming.rebind("rmi://localhost:5000/sonoo",stub);
8. }catch(Exception e){System.out.println(e);}
9. }
10. }
77
ASETL CSE/VI SEM AJP LAB
Interface //RMICalIntf.java
import java.rmi.*;
import java.rmi.server.*;
public interface RMICalIntf extends Remote
{ //Declaring the methods to be implemented
double add(double a,double b) throws RemoteException;
double sub(double a,double b) throws RemoteException;
double mul(double a,double b) throws RemoteException;
double div(double a,double b) throws RemoteException;
}
Implementation //RMICalImpl.java
import java.rmi.*;
import java.io.*;
import java.rmi.server.*;
public class RMICalImpl extends UnicastRemoteObject implements RMICalIntf
{ //Defining the methods declared in the interface
RMICalImpl() throws RemoteException
{
}
public double add(double a, double b)throws RemoteException
{
return(a+b);
}
public double sub(double a,double b)throws RemoteException
{
return(a-b);
}
public double mul(double a,double b)throws RemoteException
{
return(a*b);
}
public double div(double a,double b)throws RemoteException
{
return(a/b);
}
}
78
ASETL CSE/VI SEM AJP LAB
}
}
Client side //RMICalClient.java
import javax.swing.*;
import java.awt.*;
import java.rmi.*;
import java.awt.event.*;
import java.io.*;
public class RMICalClient extends JFrame implements ActionListener
{
double n1 = 0.0;
double d1;
double n2 = 0.0;
JButton jb[] = new JButton[21];
JTextField tf;
Container con;
int button,i;
String str;
String num="";
JPanel tp,bp; //declaring 2 panels for textfield and buttons
public RMICalClient()
{
setTitle("calculator");
tp = new JPanel();
bp = new JPanel();
tf = new JTextField(22);
tf.setEditable(false);
con = getContentPane();
bp.setLayout(new GridLayout(5,4));
tp.add(tf);
con.add(tp,"North"); //placing the textfield in the north
for(int i=0;i<10;i++) //inserting and numbering buttons
{
jb[i] = new JButton(""+i);
}
jb[10] = new JButton("+");
jb[11] = new JButton("-");
jb[12] = new JButton("*");
jb[13] = new JButton("/");
jb[14] = new JButton("clear");
jb[15] = new JButton(".");
jb[16] = new JButton("=");
for(int i = 0;i<17;i++)
{
jb[i].addActionListener(this);
bp.add(jb[i]);
}
con.add(bp,"Center"); //placing the panel with the buttons in the center
setDefaultCloseOperation(EXIT_ON_CLOSE);
}
79
ASETL CSE/VI SEM AJP LAB
80
ASETL CSE/VI SEM AJP LAB
break;
case 2:
d1 = a.sub(n1,n2);
break;
case 3:
d1 = a.mul(n1,n2);
break;
case 4:
d1 = a.div(n1,n2);
break;
default:
d1 = 0.0;
}
str = String.valueOf(d1); //convert the //value to string
tf.setText(str); //print the value
}
catch(Exception e){}
}
Else
{
tf.setText("");
}
}
if(ae.getSource()==jb[14]) //if button pressed is “CLEAR”
{
tf.setText("");
num = "";
n1=0.0;
n2=0.0;
button=0;
}
}
public static void main(String args[])
{
JFrame f = new RMICalClient();
f.setSize(200,200);
f.setVisible(true);
}
}
81
ASETL CSE/VI SEM AJP LAB
In this example, we are using the Oracle10g database to match the emailId and password with
the database. The table name is user432 which have many fields like name, email, pass etc.
You may use this query to create the table:
index.jsp
4. <a href="login.jsp">login</a>|
5. <a href="logout.jsp">logout</a>|
6. <a href="profile.jsp">profile</a>
82
ASETL CSE/VI SEM AJP LAB
login.jsp
This file creates a login form for two input fields name and password. It is the simple login
form, you can change it for better look and feel. We are focusing on the concept only.
loginprocess.jsp
This jsp file contains all the incoming values to an object of bean class which is passed as an
argument in the validate method of the LoginDao class. If emailid and password is correct, it
displays a message you are successfully logged in! and maintains the session so that we may
recognize the user.
83
ASETL CSE/VI SEM AJP LAB
29. session.setAttribute("session","TRUE");
30. }
31. else
32. {
33. out.print("Sorry, email or password error");
34. %>
35. <jsp:include page="index.jsp"></jsp:include>
36. <%
37. }
38. %>
LoginBean.java
It is the bean class that have 2 properties email and pass with its setter and getter methods.
84
ASETL CSE/VI SEM AJP LAB
Provider.java
This interface contains four constants that may differ from database to database.
ConnectionProvider.java
This class provides a factory method that returns the object of Connection. Here, driver class
is loaded only once and connection object gets memory only once because it is static.
85
ASETL CSE/VI SEM AJP LAB
LoginDao.java
86