HTTP headers are the request to a server for information and the resulting response. When you input an address into your browser, it sends a request to the server hosting the domain and the server responds. You can see the request and response using the basic HTTP Header Viewer. The HTTP Header Viewer can be used to view the Headers or Headers and Content of any valid http:/ / url. When the HEAD is selected, the request is for the server to only send header information. A GET selection requests both headers and file content just like a browser request. Information in response headers may include: [Read more…] about What is Http Header?
Describing ServletRequest and ServletResponse.
The ServletRequest is a predefined interface present in javax.serviet package. The object of ServletRequest interface deals with the client request and fetches it to the servlet program. This object is created by the servlet container and is used as the argument of service method (life cycle method).
This interface is also used by javax.http package.
Methods in ServlelRequest
(i) public Object getAttribute(String name)
Returns the value of the named attribute as an Object, or null if no attribute of the given name exists.
(ii) public Enumeration getAttributeNames()
Returns an Enumeration containing the names of the attributes available to this request.
(iii) public String getCharacterEncoding()
Returns the name of the character encoding used in the body of this request.
(iv) public intgetContentLength()
Returns the length, in bytes, of the request body and made available by the input stream, or -1 if the length is not known. For HTTP Servlets, same as the value of the CGI variable CONTENT_LENGTH.
(v) public String getContentType()
Returns the MIME type of the body of the request, or null if the type is not known.
(vi) public ServletInputStreamgetInputStream() throws IOException
Retrieves the body of the request as binary data using a ServletInputStream.
(vii) public Locale getLocal()
Returns the preferred Locale that the client will accept content in, based on the Accept-Language header.
(viii) public Enumeration getLocales()
Returns an Enumeration of Locale objects indicating, in decreasing order starting with the preferred locale, the locales that are acceptable to the client based on the Accept-Language header.
(ix) public String getParameter(String name)
Returns the value of a request parameter as a String, or null if the parameter does not exist.
(x) public Map getParameterMap()
Returns a java.uti1.Map of the parameters of this request
(xi) public Enumeration getParameterNames()
Returns an Enumeration of String objects containing the names of the parameters contained in this request.
(xii) public String[] getParameterValues(String name)
Returns an array of String objects containing all of the values the given request parameter has, or null if the parameter does not exist.
(xiii) public String getProtocol()
Returns the name and version of the protocol the request uses in the form protocol/majorVersion.minorVersion, for example, HTTP/1.1 For HTTP servlets, the value returned is the same as the value of the CGI variable SERVER_PROTOCOL.
(xiv) public BufferedReadergetReader() throws IOException
Retrieves the body of the request as character data using a BufferedReader.
(xv) public String getRemoteAddr()
Returns the Internet Protocol (IP) address of the client that sent the request.
(xvi) public String getRemoteHost()
Returns the fully qualified name of the client that sent the request.
(xvii) public RequestDispatchergetRequestDispatcher(String path)
Returns a RequestDispatcher object that acts as a wrapper for the resource located at the given path.
(xviii) public String getScheme()
Returns the name of the scheme used to make this request, for example, http, https, or ftp.
(xix) public String getServerName.()
Returns the host name of the server that received the request.
(xx) public intgetServerPort()
Returns the port number on which this request was received.
(xxi) public booleanisSecure()
Returns a boolean indicating whether this request was made using a secure channel, such as HTTPS.
(xxii) public void removeAttribute(String name)
Removes an attribute from this request. This method is not generally needed as attributes only persist as long as the request is being handled.
(xxiii) public void setAttribute(String name,Object 0)
Stores an attribute in this request. Attributes are reset between requests.
(xxiv) public void setCharacterEncoding(String env) throws Unsupported EncodingException
Overrides the name of the character encoding used in the body of this request.
ServletResponse
The ServletResponse is a predefined interface present in javax.servlet package. The object of this interface sends response to the client. Its object is created by the servlet container. To send binary data in MIME body response, we have to use ServletOutputStream returned by getOutputStream. To send text data we will use PrintWriter returned by getWriter.
Melhods in ServlelResponse
(i) public void flushBuffer() throws IOException
Forces any content in the buffer to be written to the client.
(ii) public intgetBufferSize()
Returns the actual buffer size used for the response. lf no buffering is used, this method returns().
(iii) public String getCharacterEncoding()
Returns the name of the charset used for the MIME body sent in this response. lf no charset has been assigned, it is implicitly set to 150-8859-1 (Latin-1).
(iv) public Locale getLocal()
Returns the locale assigned to the response.
(v) public ServletOutputStreamgetOutputStream() throws IOException
Returns a ServletOutputStream suitable for writing binary data in the response. The servlet container does not encode the binary data.
(vi) public PrintWritergetWriter() throws IOException
Returns a PrintWriter object that can send character text to the client.
(vii) public booleanisCommitted()
Returns a boolean indicating if the response has been committed. A commited response has already had its status code and headers written.
(viii) public void reset()
Clears any data that exists in the buffer as well as the status code and headers.
(xi) public void resetBuffer()
Clears the content of the underlying buffer in the response without clearing headers or status code.
(x) public void setBufferSize(int size)
Sets the preferred buffer size for the body of the response.
(xi) public void setContentLength(intlen)
Sets the length of the content body in the response In HTTP servlets, this method sets the HTTP Content-Length header.
(xii) public void setContentType(String type)
Sets the content type of the response being sent to the client.
(xiii) public void setLocaIe(Locale loc)
Sets the locale of the response, setting the headers (including the Content-Type’s charset) as appropriate.
Implementing Servlet Object
The Servlet object is a Java object that is initiated and managed by the Servlet container. However, the Java object needs to be implemented descriptive to the Servlet container. The following rules are specified by the Java Servlet specification for implementing the Servlet object:
• Should be a public non-abstract class.
• Should be a subtype of the javax.servlet.Servlet interface, as the Servlet container understands the Servlet object by using this interface.
• Should support a no-argument constructor.
• Recommended not to declare the methods of the javax.servlet.Servlet interface implemented by the Servlet object as final.
As we understood the rules for implementing servlet object, let us learn about the javax.servlet.Servlet andjavax.servlet.ServletConfig interfaces,which arethe basic and important elements of Java Servlet API to understand the Servlet life cycle.
ServletConfig OBJECT
• It is one per Servlet Class Object so it is called right hand object of the servlet class object.
• ServletContainer creates this object along with our servlet class object and also destroys this object along with our Servlet class object.
• This is the object of underlying Servlet Container Supplied java class that implements javax.servlet.ServletConf ig interface.
• This object is useful to gather details about Servlet program and to pass information to servlet program.
• This object is useful to gather unit parameter values from web.xml file.
• This object is required to get access to ServletContext object.
ServletContext Object
• It is one per web application and visible to all web resource programs of the web application, it is called global memory of the web application.
• Servlet Container creates this object either during server startup (cold deployment) or during deployment of the web application (hot deployment) using this object.
(a) We can get underlying server info.
(b) We can get details of the web resource program of the web.
(c) We can get servlet API version that server uses.
(d) We can get streams pointing to the resource program of the web application.
(e) We can write message to long files.
•Different ways of access to ServletConfig obj.in our Servlet program.
Explain Server Side Programming
All of us would have started programming in java with the famous “hello world” program. If you can recollect, we saved the file with a ‘.java’ extension and later compiled the program using ‘javac’ and then executed the program using ‘java’. Apart from introducing you to the language basics, the important point is that it is a client-side program. That means you write, compile and execute the program in the client machine (i.e., your PC). No doubt, it is the easiest and fastest way to write, compile and execute the program. However, it has little practical significance when it comes to real-world programming.
Why Server Side Programming
Though it is technically feasible to implement almost any business logic using client-side programs, logically or functionally it server no purpose when it comes to enterprises application (e.g., banking, air ticketing, e-shopping, etc). To further explain, going by the client-side programming logic; a bank having 10,000customers would mean that each customer would have a copy of the program(s) in his or her PC (and now even mobiles) which translates to 10,000 programs! In addition, there are issues like security, resource pooling, concurrent access and manipulations to the database which simply cannot be handled by client-side programs. The answer to most of the issues cited above is-“Server Side Programming”. Figure illustrates the Server Side Architecture in the simplest way.
Advantages of Server Side Programs
Some of the advantages of Server Side programs are as follows:
1. All programs reside in one machine called server. Any number of remote machines (called clients) can access the server programs.
ii. New functionalities to existing programs can be added at the server side which the clients can take advantage of without having to change anything.
iii. Migrating to newer versions, architectures, design patterns, adding patches, switching to new databases can be done at the server side without having to bother about client’s hardware or software capabilities.
iv. Issues relating to enterprise applications like resource management, concurrency, session management, security and performance are managed by the server side applications.
v. They are portable and possess the capability to generate dynamic and user-based content (e.g., displaying transaction information of credit card or debit card depending on user’s choice).
Types of Server Side Programs
The following are the different types of server side programs:
(a) Active Server Pages (ASP)
(b) Java Servlets
(c) Java Server Pages (JSP)
(d) Enterprise JavaBeans (EJB)
(e)PHP
To summarize, the objectives of server side programs are to centrally manage all programs relating to a particular application (e.g., banking, insurance, e-shopping, etc). Clients with bare minimum requirements (e.g., Pentium II, Windows XP professional, MS Internet Explorer and an internet connection) can experience the power and performance of a server (e.g., IBM Mainframe, Unix Server, etc.) from a remote location without having to compromise on security or speed. More importantly server programs are not only portable but also possess the capability to generate dynamic responses based on user’s request.
Terminology in Web Application
Important terms used in web application are discussed here.
Common Gateway Interface (CGI)
The Common Gateway Interface (CGI) is one of the practical techniques developed for creating dynamic content. By using the CGI, web server passes request to an external program and after executing the program the content is sent to the client as an output. In CGI, when the server receives a request, it creates a new process to run the CGI program; so creating a process for each request requires significant server resources and time, which limits the number the of requests that can be processed concurrently. CGI applications are platform dependent. There is no doubt that CGI has played a major role in explosion of internet and its performance and scalability issues make it optimal solution.
Java Servlets
Java Servlet is a generic server extension that means a Java class can be loaded dynamically to expand the functionality of the server. Servlets are used with web servers and run inside the Java Virtual Machine (JVM) on the server so it is safe and portable. Unlike applets they do not need support from Java in the browsers. In contrast to CGI, servlets do not use multiple processes to handle separate requests. Servlets can be handled by separate threads in the same process. Servlets are portable and platform independent.
Web Server
A web server extension is the combination of computer and the program installed on it. The web server interacts with the client through a web browser. It delivers the web pages to the client and to an application by using web browser and the Hypertext Transfer Protocol (HTTP) protocols respectively. We can also define the web browser as the package of large number of programs installed on the computer connected to internet or intranet for downloading the requested files using File Transfer Protocol (FTP), serving email and building and publishing web pages. A computer connected to internet or intranet must have a server program. In Java language, a web server is a server that is used to support the web component like servlet and Java server page (JSP).
A computer connected to the internet for providing services to a small company or a departmental store may contain the HTTP server (to access and store the web pages and file), Simple Mail Transfer Protocol (SMTP) server (to support mail services), FTP server (for file downloading) and Network News Transfer Protocol (NNTP) server (for newsgroup). The computer containing all of these servers is called web server. Internet service providers and large companies may have all these servers and many more on separate machines. In case of Java, a web server can be defined as a server that only supports the web components like servlet and JSP. It does not support the business component like EJB.
Application Server
An application server is a software framework dedicated to the efficient execution of procedures (programs, routines, scripts, etc.) for supporting the construction of applications. Normally, the term refers to Java application servers. When this is the case, the application server behaves like an extended virtual machine for the running applications, handling transparently connections to the database at one side, and connecting to the web client at the other end.
An application server is typically used for complex transaction-based applications. To support high-end needs, an application server has to have built-in redundancy, monitor for high-availability, high-performance distributed application services and support for complex database access.
Servlet Container
A servlet container is nothing but a compiled, executable program. The main function
of the container is to load, initialize and execute servlets. The servlet container is the official Reference Implementation for the Java Servlet and Java server pages technologies. The Java servlets and Java server pages specifications are developed by Sun Microsystems under the Java Community Process (JCP).
A container handles large number of requests as it can hold many active servlets, listeners, etc. It is interesting to note that the container and objects in a container are multithreaded. So each object must be thread safe in a container as the multiple requests are handled by the container due to entrance of more than one thread at a time.
We can categorize the servlet container as:
(a)A simple servlet container is not fully functional; therefore, it can run very simple servlets and do the following:
• Wait for HTTP request.
• Construct ServletRequest object and ServletResponse object.
• If the request is for static method, invoke the process method of StaticResourceProccesor instance, passing ServletRequest object and ServletResponse object.
• If the request is for servlet, load the servlet class and invoke the service method passing ServletRequest object and ServletResponse object. Note that in this servlet container, the servlet class is loaded every time the servlet is requested.
(b)A fully functional servlet container additionally does the following for each HTTP request:
• When the servlet is called for the first time, load the servlet class and its init method (once only).
• For each request, construct an instance of javax. servlet. ServletRequest and an instance of javax. servlet. ServletResponse objects.
• Invoke servlet’s service method, passing ServletRequest object and ServletResponse object.
• When the servlet class is shut down, call the servlet’s destroy method and unload the servlet class.
Major Classes and Interfaces used to developing Java Application.
Some of major classes and interfaces which are frequently used while developing a Java application are as follows:
• DriverManager class
• Driver interface
• Connection interface
• Statement interface
DriverManagerClass
It is a predefined class present/declared in java.sql package. It is a non-abstract class in the JDBC API. It has no constructor which implies that this class cannot be inherited or initialized directly.
All the methods or properties of this class are declared as static, so it is not necessary to construct an object of DriverManager Class. We can call these static methods using class name.
The main responsibility of the DriverManager class is preparing a connection by using Driver implementation that accepts the given JDBC URL.
Methods in DriverManager
(a) public static Connection getConnection (String url, String user name, String pswd);
Establishes connection between driver and database. This class selects a driver from the list of drivers and creates a connection by checking user parameter for which the connection is being made. Password parameter represents the password of the user.
(b) public static Driver getDriver (String url) throws SQLException
Locates the requested driver in the DriverManager class. The URL parameter specifies the URL of requested driver.
(c) public static void register (Driver drvr) throws SQLException:
Registers a requested driver with DriverManager Class.
(d) public static void deregister (Driver drvr) throws SQLException
Drops a driver from the list of the driver maintained by DriverManager.
Driver Interface
It is a predefined interface present in java.sql. package. It is a basic interface that every JDBC driver provider has to implement. The java.sql.Driver is an Interface defined under JDBCAPI to describe an object that is responsible to establish connection to database. All the driver classes implement this interface to connect to a database.
Methods in Driver Interface
(a) public Connection connect (String url, Properties info)
This method establishes connectivity with database. The URL parameter specifies a URL that describes the database details to which the driver is to be connected. The info parameter specifies the information of the tag/value pair used in driver.
Connection Interface
It is an interface present in java.sql package. This interface defines an abstraction to access the session, established with the database server. The JDBC connection helps to perform the following operation:
• Create JDBC Statement
• Control local transaction
Methods in Connection Interface
(a) public void close () throws SQLException
Closes the connection and releases the connection object associated with the connected database.
(b) public Statement createStatement () throws SQLException
Create a Statement object to send sql statements to the specified database.
(c) public PreparedStatement prepareStatement (String sql) throws SQLException
Create a PreparedStatement object to send sql statements over a connection.
(d) public CallableStatement prepareCall (String sql) throws SQLException
Create a CallableStatement object for calling database stored procedures.
(e) public void commit () throws SQLException
Commits the changes made in the previous commit and releases any database locks held by the current Connection object.
(f) public void rollback () throws SQLException
Rolls back all the transactions and releases any locks that are currently held by the Connection object.
Statement Interface
It is a predefined interface present in java.sql package. It is a part of JDBC API that abstracts an object. It is responsible to execute sql statement and return the result. A
Statement object can open a single ResultSet object at a time.
The PreparedStatement interface is dealing with IN parameter whereas the CallableStatement interface deals with both IN and OUT.
Methods of Statement Interface
(a) public int executeUpdate (String sql) throws SQLException
Execute the Insert, Update and Delete Statement or the SQL DDL statements.
(b) public ResultSet executeQuery (String sql) throws SQLException
Execute a sql command and return a single ResultSet.
(c) public void close () throws SQLException
Closes the Statement object, therefore, it releases its control from the database and also from the connection.
(d) public ResultSet getResultSet () throws SQLException
Retrieves the current Resultset object generated by Statement object.
(e) public Connection getConnection () throws SQLException
Accepts the Connection object made to the database.
ResultSet Interface
This interface provides methods for the retrieval of data returned by an SQL statement execution. A ResultSet maintains a cursor pointing to its current row of data. The most often used methods, namely, getXXX and updateXXX methods are present in this interface.
Methods in ResultSet
(a) public booleannext () throws SQLException
Moves the cursor down one row from its current position.
(b) public void close () throws SQLException
Releases this ResultSet object’s database and JDBC resources immediately instead of waiting for this to happen when it is automatically closed.
(c) public booleanwasNull () throws SQLException
Reports whether the last column read had a value of SQL NULL.
(d) public StringgetXXX (int columnIndex) throws SQLException
Retrieves the value of the designated column in the current row of this ResultSet object as per the type of data.
(e) public void beforeFirst () throws SQLException
Moves the cursor to the front of this ResultSet object, just before the first row.
(f) public void afterLast () throws SQLException
Moves the cursor to the end of this ResultSet object, just after the last row.
(g) public booleanabsolute (int row) throws SQLException
Moves the cursor to the given row number in this ResultSet object.
(h) public booleanprevious () throws SQLException
Moves the cursor to the previous row in this ResultSet object.
(i) public void deleteRow () throws SQLException
Deletes the current row from this ResultSet object and from the underlying database.
(j) public void insertRow () throws SQLException
Inserts the contents of the insert row into this ResultSet object and into the database.
What is JDBC API? Important Goals of JDBC-API.
The JDBC specification related API in the form of java.sql package.
In the JDBC API packages given in the next page can create methods of abstract, can create classes represent guidelines to develop JDBC drivers, whereas abstract methods of interface and abstract classes represent rules to develop JDBC drivers.
Each JDBC driver is set of classes implementing various interfaces of JDBC API packages. While defining methods of these interfaces the classes contain logic to interact with specific database software.
JDBC API provides a standard abstraction for Java application to access JOBC drivers, which is implemented by 3rd party vendor, i.e., database. In other words, JDBC API defines a standard protocol between a Java application and JDBC driver.
Important Goals of JDBC-API
• Provides a standard abstraction for submitting the SQL statements to access the data is database.
• Maintains focus on SQL.
• Support the compatibility with connectors.
• Provides a foundation for high-level API and keep it simple.
MySql YEARWEEK Function in Java Servlet
This function Will Returns the year and week.
We have create database named ‘dbase’. After that a class is been declared named ‘MySqlYearWeekFunc’ extends the ‘HttpServlet’. With that kind of efforts, we need to define some methods, which do their job for exporting output. After we just declare Service method () (service method does the job of calling doGet() method for getting request).some variables also define as Connection,Resultset,PreparedStatement. Connection variable use to link between database and actual code (FrontEnd and BackEnd). preparedStatement will use to send the query to database like (Select YEARWEEK(CURDATE()) AS yrwk). This statement will work according to condition it shows. Now the next method executeQuery() will execute desired query and statement. And in the end doGet() method will be used to fetch the result on a web browser.
While getting the output on the web browser I use ‘HTML’ code and tag that will bring output in tabular form.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlYearWeekFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select YEARWEEK(CURDATE()) AS yrwk");
rs = ps.executeQuery();
String title = "Using Year Week Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>The Week Is</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlYearWeekFunc</servlet-name>
<servlet-class>MySqlYearWeekFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlYearWeekFunc</servlet-name>
<url-pattern>/MySqlYearWeekFunc</url-pattern>
</servlet-mapping>
MySql Year Function in Java Servlet
This Function will Returns the year.
i made a table in database named ‘dbase’ with required fields and within the reference of mySql(php myAdmin).then i import all the required java packages from java library. Then I made class, which extends ‘HttpServlet’ named ‘MySqlYearFunc’. I use here serviceMethod() that will use to getting the request from the doGet ()method. Before declaring desired variables, i loaded all the required drivers for database accessing. Then after, i declare variable like ‘connection’ that will make a link between the database and the actual code. Here i declare ‘resultSet’ Also which is been responsible for the fetching value from the columns and rows. I declare ‘preparedStatement’ that will use to executing selected query like executeQuery() as (Select YEAR(CURDATE()) AS yr).I use doGet()Method that will get Output on the web browser.
On the web Browser i use ‘Html’ tags to print the output in tabular form on the web browser this will present output in a Efficient look.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlYearFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select YEAR(CURDATE()) AS yr");
rs = ps.executeQuery();
String title = "Using Year Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>The Year Is</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlYearFunc</servlet-name>
<servlet-class>MySqlYearFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlYearFunc</servlet-name>
<url-pattern>/MySqlYearFunc</url-pattern>
</servlet-mapping>
MySql Where Clause in Java Servlet
This function will show to the result according to Where Query in mysql.
Firstly, we need to make a table named ‘inq’ into a database named ‘dbase’. And after that we have to call the java Packages from java library. Now to define a class named ‘MySqlWhereClauseJavaServlet’ which is been, extend ‘HttpServlet’. And we need to be load the driver for database calling. To getting request we need to define serviceMethod().for whole procedure to produce output need to define some mandatory variables like connection (for making link between frontend and Backend).Resultset which represents the output table of data resulted from a SELECT query. preparedStatement the object of this statement will use to execute the query like executeQuery() it will return the object to resultset for produced output.preparedStatement will execute written query (SELECT emp_id, last_name,salary, manager_id FROM inq WHERE manager_id = 410″).At the last step we need to call the doGet() for getting request output on a web browser.
On to the web browser, we need to use ‘HTML’ code and its tags to get Output in Tabular form or in a manner Look.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlWhereClauseJavaServlet extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("SELECT emp_id, last_name,salary, manager_id FROM inq WHERE manager_id = 410");
rs = ps.executeQuery();
String title = "Info With Where Clause";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h3 align=\"center\">" + title + "</h3>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Employee Id</th><th>Last Name</th><th>Salary</th><th>Manager Id</th>\n"+ "</body> </html>");
while(rs.next())
{
int e_id = rs.getInt("emp_id");
String l_name = rs.getString("last_name");
int sal = rs.getInt("salary");
int m_id = rs.getInt("manager_id");
disp.println("<tr><td align=\"center\">"+ e_id +"<td align=\"center\">"+ l_name +"<td align=\"center\">"+ sal + "<td align=\"center\">"+ m_id +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlWhereClauseJavaServlet</servlet-name>
<servlet-class>MySqlWhereClauseJavaServlet</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlWhereClauseJavaServlet</servlet-name>
<url-pattern>/MySqlWhereClauseJavaServlet</url-pattern>
</servlet-mapping>
MySql WEEKOFYEAR Function in Java Servlet
This function Will Returns calendar week of the date (1-53).
First i made a table with required fields and values in that into a database named ‘dbase’ with the reference of mySql(php Myadmin). Then i import all the required packages from java library. Then i made a class named ‘MySqlWeekOfYearFunc’ extends the ‘HttpServlet’. Then i use serviceMethod() which will use to getting request from the doGet()Method for Output. Then load all the required Drivers. Then i declare some mandatory variables like connection (Connection variable is been used to make a bridge or link between database and actual code (java code)). As after creating link between both platforms, i declare resultSet, which will be use to fetch the values from required fields according to user. The other one variable is preparedStatement the object of this variable is ‘ps’ this will use to execute the query like executeQuery() as(Select WEEKOFYEAR(CURDATE()) AS week). To in the end i use doGet()Method for getting value on the web Browser.
While on the web browser to get output in tabular form i use ‘HTML’ code and tags for a Designer look.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlWeekOfYearFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select WEEKOFYEAR(CURDATE()) AS week");
rs = ps.executeQuery();
String title = "Using Week of Year Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>The Week Is</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlWeekOfYearFunc</servlet-name>
<servlet-class>MySqlWeekOfYearFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlWeekOfYearFunc</servlet-name>
<url-pattern>/MySqlWeekOfYearFunc</url-pattern>
</servlet-mapping>
MySql WEEKDAY Function in Java Servlet
This Function will return the weekday index.
i made a table in database named ‘dbase’ with required fields and within the reference of mySql(php myAdmin).Then i import all the required java packages from java library. Then i made class, which extends ‘HttpServlet’ named ‘MySqlWeekDayFunc’. I use here serviceMethod() that will use to getting the request from the doGet ()method. Before declaring desired variables, i load all the required drivers for database accessing. Then after, i declare variable like ‘connection’ that will make a link between the database and the actual code. Here i declare ‘resultSet’ Also that is been responsible for the fetching value from the columns and rows. I declare ‘preparedStatement’ that will use to executing selected query like executeQuery() as (Select WEEKDAY(‘2014-06-01’) AS wd)). I use doGet()Method that will get Output on the web browser.
To getting output on the web browser, I used ‘HTML’ code and tags that will bring output in tabular form that will make it a manner form.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlWeekDayFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select WEEKDAY('2014-06-01') AS wd");
rs = ps.executeQuery();
String title = "Using WEEKDAY Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>The Day is</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlWeekDayFunc</servlet-name>
<servlet-class>MySqlWeekDayFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlWeekDayFunc</servlet-name>
<url-pattern>/MySqlWeekDayFunc</url-pattern>
</servlet-mapping>
MySql UTC_TIMESTAMP Function in Java Servlet
This Function will Returns the current UTC date and time.
First i made a table in database named ‘dbase’ within the reference of mySql(php myAdmin). Then i import all the mandatory java packages from the java library as required for program. I made a class named ‘MySqlUTCTimeStampFunc’, which extends ‘HttpServlet’. I use serviceMethod() which is been carry the request from doGet()Method for Output. Then after, to declare the variable i loaded all the required drivers before for database accessing. Here i declare the variables like ‘connection’ this variable will create a link between database and java code. Then i call ‘resultSet’ this will be responsible for Getting value from the selected columns and the rows.
Then i declare ‘preparedStatement’ which will get to execute the selected query like executeQuery() as (Select UTC_TIMESTAMP() AS utc).Here i use doGet()Method which will use to get output on the web browser.
I use here ‘Html’ code and tags that will present the output in tabular form on the web browser.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlUTCTimeStampFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select UTC_TIMESTAMP() AS utc");
rs = ps.executeQuery();
String title = "Using UTC_TIMESTAMP Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Required Result Is</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlUTCTimeStampFunc</servlet-name>
<servlet-class>MySqlUTCTimeStampFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlUTCTimeStampFunc</servlet-name>
<url-pattern>/MySqlUTCTimeStampFunc</url-pattern>
</servlet-mapping>
MySql UTC_TIME Function in Java Servlet
This function will Returns the current UTC time.
I made a table in database named ‘dbase’ with required fields and within the reference of mySql(php myAdmin). Then i import all the required java packages from java library. Then i made class, which extends ‘HttpServlet’ named ‘MySqlUTCTimeFunc’. I use here serviceMethod() that will use to getting the request from the doGet ()method. Before declaring desired variables, i loaded all the required drivers for database accessing. Then after, i declare variable like ‘connection’ that will make a link between the database and the actual code. Here i declare ‘resultSet’ Also that is been responsible for the fetching value from the columns and rows. I declare ‘preparedStatement’ that will use to executing selected query like executeQuery() as (Select UTC_TIME() AS utc).I use doGet()Method that will get Output on the web browser.
To get output on the web browser in a tabular form i use ‘HTML’ code and tag which bring output In Impressive mode.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlUTCTimeFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select UTC_TIME() AS utc");
rs = ps.executeQuery();
String title = "Using UTC_TIME Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Required Result Is</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlUTCTimeFunc</servlet-name>
<servlet-class>MySqlUTCTimeFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlUTCTimeFunc</servlet-name>
<url-pattern>/MySqlUTCTimeFunc</url-pattern>
</servlet-mapping>
MySql UNIX_TIMESTAMP Function in Java Servlet
This Function will Returns a UNIX timestamp.
First i made a database named ‘dbase’ within the reference of mySql(php myAdmin).Then after i import all java packages from java library as program need. Here i made a class named ‘MySqlUnixTimeStampFunc’,which extends ‘HttpServlet’. I use service()Method that will help to getting the request from doGet()Method for output on web browser. Then i loaded all the required Drivers that will help to accessing Database. After then, I declare variable first i use ‘connection’ variable that will create a link between database and the actual code(frontEnd and the backEnd).other variable is ‘ResultSet’ that will help to fetch value from the columns and rows as required query. The next variable is ‘preparedStatement’ that will use to executing the selected Query like executeQuery as (Select UNIX_TIMESTAMP(NOW()) AS uts).I use doGet()Method in last instance that will bring the output on web browser.
To Getting Output on web browser in a tabular form i use ‘HTML’ code and tags.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlUnixTimeStampFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select UNIX_TIMESTAMP(NOW()) AS uts");
rs = ps.executeQuery();
String title = "Using UNIX_TIMESTAMP Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Required Result Is</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlUnixTimeStampFunc</servlet-name>
<servlet-class>MySqlUnixTimeStampFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlUnixTimeStampFunc</servlet-name>
<url-pattern>/MySqlUnixTimeStampFunc</url-pattern>
</servlet-mapping>
MySql UNIXTIME () in Java Servlet
This Function will Returns a UNIX time.
First i made a table in database named ‘dbase’ within the reference of mySql(php myAdmin). Then after, i import all the java packages from java library. I made a class named ‘MySqlUnixTime’, which extends ‘HttpServlet’. I use here the method service()Method that will use to getting the request from the doGet()Method for an output on the web browser. I loaded all the required drivers for accessing the database. I use here variables as required as i use ‘connection’ this variable will create a link between the database and the java code. This variable named ‘resultSet’ will use to get the value from the selected columns and rows from the selected table as required. After that i use to declare ‘preparedStatement’ that will use to executing the Selected query like executeQuery as (Select FROM_UNIXTIME(0) AS ut). I use doGet()Method for getting output on the web browser.
I Use ‘HTML’ code and some tags, which will show the output in tabular form on the web browser.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlUnixTime extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select FROM_UNIXTIME(0) AS ut");
rs = ps.executeQuery();
String title = "Using From_UNIXTIME Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Required Result</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlUnixTime</servlet-name>
<servlet-class>MySqlUnixTime</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlUnixTime</servlet-name>
<url-pattern>/MySqlUnixTime</url-pattern>
</servlet-mapping>
MySql UNHEX Function in Java Servlet
This Function will convert each pair of hexadecimal digits to a character.
Here i made a database named ‘dbase’ within the reference of mySql(php myAdmin). First, i import all the required java packages from java library. Then after, i made a class named ‘MySqlUNHEXFunction’ extends the ‘HttpServlet’. I use the serviceMethod() which is responsible for the getting request from doGet() method. Then after, need to load all the drivers as required. And to declare the mandatory variables like Connection (the variable Connection will use to establish the link between database and java code (actual code). ResultSet the variable resultset does the job to fetch the value from required columns and rows. preparedStatement this variable use to execute the query like executeQuery() as (Select UNHEX(‘4D7953514C’)) And after then i use doGet() method to get the output on the web Browser.
On the web Browser, i use ‘HTML’ tags that will represent the output in tabular form.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlUNHEXFunction extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select UNHEX('4D7953514C')");
rs = ps.executeQuery();
String title = "Using UNHEX Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Value Is </th>\n"+ "</body> </html>");
while(rs.next())
{
String val = rs.getString(1);
disp.println("<tr><td align=\"center\">" + val +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlUNHEXFunction</servlet-name>
<servlet-class>MySqlUNHEXFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlUNHEXFunction</servlet-name>
<url-pattern>/MySqlUNHEXFunction</url-pattern>
</servlet-mapping>
MySql UCASE Function in Java Servlet
This Function is Synonym for UPPER () Case.
I use to made a database first named ‘dbase’ within the reference of mySql(php myAdmin). Then i import all important java packages from java library. Then i made a class named ‘MySqlUCASEFunction’ extends ‘HttpServlet’. Then i use service()Method this will be responsible for the getting the request from the doGet()Method for output. Then i loaded all the required drivers for the database accessing. Then i use to set variables like i use first variable ‘connection’ that will be responsible for the creating a link between database and the java code. Then i use ‘resultSet’ this will use to get value from the selected columns and the rows from table. i use here ‘preparedStatement’ that use to executing the selected query like executeQuery() as (Select UCASE(‘mysql’) AS ucs). Then in last phase i use doGet()Method that will provide the output on the web browser.
To Getting Output on web browser in a tabular form i use ‘HTML’ code and tags.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlUCASEFunction extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select UCASE('mysql') AS ucs");
rs = ps.executeQuery();
String title = "Using UCASE Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Value Is </th>\n"+ "</body> </html>");
while(rs.next())
{
String val = rs.getString(1);
disp.println("<tr><td align=\"center\">" + val +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlUCASEFunction</servlet-name>
<servlet-class>MySqlUCASEFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlUCASEFunction</servlet-name>
<url-pattern>/MySqlUCASEFunction</url-pattern>
</servlet-mapping>
MySql TRUNCATE Function in Java Servlet
This Function Returns numeric exp 1 truncated to exp 2 decimal places.
First i made a database named ‘dbase’ within the complete reference of mySql(php myAdmin). Then i import all the required java package from java library as program need. Then after i made a class named ‘MySqlTRUNCATEFunction’ that is been extends the ‘HttpServlet’. Then i use to get request from doGet()method the serviceMethod() for output on web browser. Then i loaded all the mandatory drivers for database accessing. After then the next move is to declare variables like i use ‘connection’ this will use to make a bridge or link between database and the actual code(java code).After then i use ‘resultSet’ that will be responsible for the getting value from the selected columns and rows. Then i use ‘preparedStatement’ this will use to executing the selected query like executeQuery as (Select TRUNCATE(4.678,1)). In the last i use doGet() method that will bring the output on the web browser.
To get Output in a manner form i use ‘Html’ tags, which will appear Output in a tabular form on the web browser.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlTRUNCATEFunction extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select TRUNCATE(4.678,1)");
rs = ps.executeQuery();
String title = "Using TRUNCATE Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Value</th>\n"+ "</body> </html>");
while(rs.next())
{
String val = rs.getString(1);
disp.println("<tr><td align=\"center\">" + val +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlTRUNCATEFunction</servlet-name>
<servlet-class>MySqlTRUNCATEFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlTRUNCATEFunction</servlet-name>
<url-pattern>/MySqlTRUNCATEFunction</url-pattern>
</servlet-mapping>
MySql TRIM Function in Java Servlet
This function will remove leading and trailing spaces.
First i made a database named ‘dbase’ within the reference of mySql(php myAdmin). Then after I import all java packages from java library as program need. Here i made a class named ‘MySqlTRIMFunction’, which extends ‘HttpServlet’. I use service()Method that will help to getting the request from doGet()Method for output on web browser. Then i loaded all the required Drivers that will help to accessing Database. After, then i declare variable first i use ‘connection’ variable that will create a link between database and the actual code (frontend and the backend). Other variable is ‘ResultSet’ that will help to fetch value from the columns and rows as required query. The next variable is ‘preparedStatement’ that will use to executing the selected Query like executeQuery as (Select TRIM(‘ mysql ‘). I use doGet()Method in last instance that will bring the output on web browser.
While getting the output on the web browser i use ‘HTML’ code and tags that present output in tabular form.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlTRIMFunction extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select TRIM(' mysql ')");
rs = ps.executeQuery();
String title = "Using TRIM Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Value Is </th>\n"+ "</body> </html>");
while(rs.next())
{
String val = rs.getString(1);
disp.println("<tr><td align=\"center\">" + val +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlTRIMFunction</servlet-name>
<servlet-class>MySqlTRIMFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlTRIMFunction</servlet-name>
<url-pattern>/MySqlTRIMFunction</url-pattern>
</servlet-mapping>
MySql TO_DAYS Function in Java Servlet
This Function Will Returns the date argument converted to days.
First i made a database named ‘dbase’ within the reference of mySql(php myAdmin). Then i import all the required java packages from java library as program essentials. I made a class named ‘MySqlToDaysFunc’, which extends ‘HttpServlet’. Then i use service()Method which will use to get the request from the doGet()Method for output on the browser. I loaded all the required drivers for accessing database as required. Then i use to declare the variable as i use ‘connection’ this will use to create a link between the database and the java code. Then i declare ‘resultSet’ this will responsible for get the value from selected columns and the rows. i use here now ‘preparedStatement’ this will execute the selected Query like executeQuery as (SELECT TO_DAYS(‘2014-05-31’) AS todys). Then i use doGet()Method that will bring the output on the web browser.
On the other hand, i use ‘HTML’ code and tags for presenting the output in a tabular form or in a manner way on the web browser.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlToDaysFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("SELECT TO_DAYS('2014-05-31') AS todys");
rs = ps.executeQuery();
String title = "Using To_Days Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Result</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlToDaysFunc</servlet-name>
<servlet-class>MySqlToDaysFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlToDaysFunc</servlet-name>
<url-pattern>/MySqlToDaysFunc</url-pattern>
</servlet-mapping>
MySql TIME_TO_SEC Function in Java Servlet
This Function will Returns the argument converted to seconds.
First i made a table in database named ‘dbase’ within the reference of mySql(php myAdmin). Then i import all the required java package from java library. I make a class named ‘MySqlTimeToSecondFunc’ extends the ‘HttpServlet’.i use here serviceMethod() which is use to getting request from the doGet()Method for output. Before activating all the variable i loaded all the required drivers for the database accessing then after i declare variables like first i declare ‘connection'(this variable will act as to create a link between database and the actual code. Here i declare second one is ‘resultSet’ this will take the responsible for fetching the value from columns and the selected rows. Here i declare one more ‘preparedStatement’ this will use to executing the selected query like executeQuery() as (SELECT TIME_TO_SEC(’01:00′) AS tmtosec)).I use doGet()Method which will bring the output on the web browser.
To get the Output in an impressive look i use some tags of ‘HTML’ Code, which will bring the Output in tabular form on a web browser.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlTimeToSecondFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("SELECT TIME_TO_SEC('01:00') AS tmtosec");
rs = ps.executeQuery();
String title = "Using Time To Second Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Result</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlTimeToSecondFunc</servlet-name>
<servlet-class>MySqlTimeToSecondFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlTimeToSecondFunc</servlet-name>
<url-pattern>/MySqlTimeToSecondFunc</url-pattern>
</servlet-mapping>
MySql TimeStamp Function in Java Servlet
This function returns the date or date time expression.
First i make a table in database named ‘dbase’ with required fields and values in it and within the reference of mySql(Php Admin).then i import all the required java package from java library. I made a class named ‘MySqlTimeStampFunc’ extends the ‘HttpServlet’. Then i use serviceMethod() which will bring the request from doGet()Method for Output. Then i load all the drivers for database accessing. After, then i declare variables, which are necessary for database conditions as i declare connection (this variable will use to make a link between database and java code or actual code). After, then i declare resultset (this variable will use to get the values from desired columns and rows as required from query).The next one will be the preparedStatement (this variable will responsible for the executing query like executeQuery() as (SELECT TIMESTAMP(‘2014-05-31 22:11:11’) AS ts). In the last i used the doGet()Method which will bring the output on the web Browser.
I use here some tags of ‘HTML’ that will bring output in a tabular form as required.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlTimeStampFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("SELECT TIMESTAMP('2014-05-31 22:11:11') AS ts");
rs = ps.executeQuery();
String title = "Using Time Stamp Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Result</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlTimeStampFunc</servlet-name>
<servlet-class>MySqlTimeStampFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlTimeStampFunc</servlet-name>
<url-pattern>/MySqlTimeStampFunc</url-pattern>
</servlet-mapping>
MySql TIMESTAMPDIFF Function in Java Servlet
This function will Subtracts an interval from a date time expression.
First i make a table in database named ‘dbase’ within the reference of mySql(php myAdmin).Then i import all the required java packages from the java library. Then i made a class named ‘MySqlTimeStampDiffFunc’, which extends ‘HttpServlet’. Then after i use service()Mehod which will get the request from the doGet()Method. Then i load all the require drivers for the database accessing. Here I declare the variables like ‘connection’ this variable will take over to create a link between a database and the java code. The other i declare ‘resultSet’ this will use to fetch the value from the columns and the rows from selected table. Then i declare the ‘preparedStatement’ this variable will execute the selected query like executeQuery() as (SELECT TIMESTAMPDIFF(MONTH,’2014-05-31′,’2014-07-20′) AS tsdiff).I here use doGet()Method that will bring the output on the web browser.
On the web Browser I use ‘Html’ tags to print the output in tabular form on the web browser this will present output in a manner way.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlTimeStampDiffFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("SELECT TIMESTAMPDIFF(MONTH,'2014-05-31','2014-07-20') AS tsdiff");
rs = ps.executeQuery();
String title = "Using Time Stamp Difference Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Result</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlTimeStampDiffFunc</servlet-name>
<servlet-class>MySqlTimeStampDiffFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlTimeStampDiffFunc</servlet-name>
<url-pattern>/MySqlTimeStampDiffFunc</url-pattern>
</servlet-mapping>
MySql TimeStampAdd Function in Java Servlet
This Function adds an interval to a date time expression.
i made a table in database named ‘dbase’ with required fields and within the reference of mySql(php myAdmin). Then i import all the required java packages from java library. Then i made class, which extends ‘HttpServlet’ named ‘MySqlTimeStampAddFunc’. I use here serviceMethod() that will use to getting the request from the doGet()method. Before declaring desired variables, i loaded all the required drivers for database accessing. Then after, i declare variable like ‘connection’ that will make a link between the database and the actual code. Here i declare ‘resultSet’ Also that is been responsible for the fetching value from the columns and rows. I declare ‘preparedStatement’ that will use to executing selected query like executeQuery() as (SELECT TIMESTAMPADD(HOUR,2,’22:11:11′) AS tsadd).I use doGet()Method that will get Output on the web browser.
To feel look good the result we use a tabular form concept. For this kind of requirement, we use ‘HTML’ coding and some of tags to use Output in Designer look to show on a web browser.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlTimeStampAddFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("SELECT TIMESTAMPADD(HOUR,2,'22:11:11') AS tsadd");
rs = ps.executeQuery();
String title = "Using Time Stamp Add Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Result</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlTimeStampAddFunc</servlet-name>
<servlet-class>MySqlTimeStampAddFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlTimeStampAddFunc</servlet-name>
<url-pattern>/MySqlTimeStampAddFunc</url-pattern>
</servlet-mapping>
MySqlTime Function in Java Servlet
The function ‘TIME’ will show the current TIME of System.
I made a table in database named ‘dbase’ with required fields and within the reference of mySql(php myAdmin). Then i import all the required java packages from java library. Then i made class, which extends ‘HttpServlet’ named ‘MySqlTimeFunc’. I use here serviceMethod() that will use to getting the request from the doGet ()method. Before declaring desired variables, i load all the required drivers for database accessing. Then after, i declare variable like ‘connection’ that will make a link between the database and the actual code. Here i declare ‘resultSet’ Also that is been responsible for the fetching value from the columns and rows. I declare ‘preparedStatement’ that will use to executing selected query like executeQuery() as (Select TIME(now()) AS tm).I use doGet()Method that will get Output on the web browser.
While getting the output on the web browser i use ‘HTML’ code and tags that present output in tabular form.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlTimeFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select TIME(now()) AS tm");
rs = ps.executeQuery();
String title = "Using Time Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Result</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlTimeFunc</servlet-name>
<servlet-class>MySqlTimeFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlTimeFunc</servlet-name>
<url-pattern>/MySqlTimeFunc</url-pattern>
</servlet-mapping>
MySql TIMEDIFF Function in Java Servlet
This Function is use to check the difference of Time or subtracts the time.
First i make a table in database named ‘dbase’ with required fields and values which is under the reference of mySql(php myAdmin).Here i import all mandatory java package from the java library as program needs. Then after, i make a class named ‘MySqlTimeDiffFunc’ extends ‘HttpServlet’. And here i use serviceMethod() which will get request from the doGet()Method for getting output on the web browser. After, i load all the required drivers for accessing database. After then i declare mandatory variables as i declare ‘Connection’ this variable does the job to create a link between database and the actual code. The other one i declare is ‘resultSet’ that will fetch the value from selected column and rows. Now here i declare the ‘preparedStatement’ that will use to execute the selected query like executeQuery() as (SELECT TIMEDIFF(‘2014-05-31 15:45:57′,’2014-05-31 13:40:50’) AS td).Here i use the doGet()Method for output on a web browser.
To get output in tabular form on the web browser i use ‘HTML’ code and some tags.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlTimeDiffFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("SELECT TIMEDIFF('2014-05-31 15:45:57','2014-05-31 13:40:50') AS td");
rs = ps.executeQuery();
String title = "Using Time Difference Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Result</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlTimeDiffFunc</servlet-name>
<servlet-class>MySqlTimeDiffFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlTimeDiffFunc</servlet-name>
<url-pattern>/MySqlTimeDiffFunc</url-pattern>
</servlet-mapping>
MySql TAN Function in Java Servlet
This function will Returns the tangent of numeric expression expressed in radians.
I make a table in database named ‘dbase’ which is been created in the reference of mySql(php myAdmin). Then i import all the required java packages from java library as required from program need. Then, i make a class named ‘MySqlTANFunction’ extends ‘HttpServlet’. After that i use serviceMethod()that will get request from doGet()method for output on the web browser. Before declaring the variables as required, i loaded all the mandatory drivers for database accessing. Here i declare ‘Connection’ this variable will be the responsible for the making bridge or path between the database and the java code. The other one will be the ‘resultSet’ this one will help to fetch the values from the selected columns and the rows. Here i declare ‘preparedStatement’ this will bring execute the selected query like executeQuery() as (Select TAN(1)).Here i use doGet()Method that will bring the output on the web browser.
To make output Impressive I use ‘HTML’ tags to get Output in tabular form on a web browser.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlTANFunction extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("Select TAN(1)");
rs = ps.executeQuery();
String title = "Using TAN Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Value</th>\n"+ "</body> </html>");
while(rs.next())
{
String val = rs.getString(1);
disp.println("<tr><td align=\"center\">" + val +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlTANFunction</servlet-name>
<servlet-class>MySqlTANFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlTANFunction</servlet-name>
<url-pattern>/MySqlTANFunction</url-pattern>
</servlet-mapping>
MySql SYSDATE Function in Java Servlet
This function Will Returns the time at which the function executes.
First i make a table in database named ‘dbase’ with required fields and values in it and within the reference of mySql(Php Admin).Then i import all the required java package from java library. I made a class named ‘MySqlSystemDateFunc’ extends the ‘HttpServlet’. Then i use serviceMethod() which will bring the request from doGet()Method for Output. Then i load all the drivers for database accessing. After then, i declare variables, which are necessary for database conditions as i declare connection (this variable will use to make a link between database and java code or actual code). After then i declare resultset (this variable will use to get the values from desired columns and rows as required from query). The next one will be the preparedStatement (this variable will responsible for the executing query like executeQuery() as (SELECT SYSDATE() AS dt). In the last i used the doGet()Method which will bring the output on the web Browser.
For getting the output in the tabular form, i use ‘HTML’ code and tags that will show output in a manner way on web browser.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlSystemDateFunc extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("SELECT SYSDATE() AS dt");
rs = ps.executeQuery();
String title = "Using System Date Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Result</th>\n"+ "</body> </html>");
while(rs.next())
{
String curr = rs.getString(1);
disp.println("<tr><td align=\"center\">" + curr +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlSystemDateFunc</servlet-name>
<servlet-class>MySqlSystemDateFunc</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlSystemDateFunc</servlet-name>
<url-pattern>/MySqlSystemDateFunc</url-pattern>
</servlet-mapping>
MySql SUM Function in Java Servlet
This function Will Return the ADD (sum) value of the required field from a table like (salary, age etc…).
We need to make a table named ‘worker’ into a database named ‘dbase’. The required fields must be filling with values. After that, Java packages to be call from java library. Here we need to define a class named ‘MySqlSUMFunction’ extends the ‘HttpServlet’. This program is been responsible for desired output as required statement from user. Here we use the service method() (this method is responsible for calling the doGet() method to getting the request). the variable which are mandatory to use link or present Backend and Frontend will have to be declared like Connection,ResultSet,preparedStatement all these variables does their required functions or job. Like the connection variable will use to make Connection between database and java code. The drivers are also to be load then created an object of Connection interface. After that preparedStatement will use to represent the Query for output like ‘SELECT SUM(salary) AS total FROM worker’. The resultset will be define as executeQuery() to execute the query for desired result. And in the last we used doGet() method for fetching result on a web browser.
Now on the browser to get an output in designer look we just use the ‘HTML’ code tags, which will present the Output in Tabular form for an efficient look.
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.DriverManager;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class MySqlSUMFunction extends HttpServlet
{
public void service(HttpServletRequest rq, HttpServletResponse rp)throws IOException, ServletException
{
rp.setContentType("text/html");
PrintWriter disp = rp.getWriter();
String driver = "com.mysql.jdbc.Driver";
String url = "jdbc:mysql://localhost/dbase";
String uid = "root";
String psw = "root";
Connection con=null;
PreparedStatement ps = null;
ResultSet rs;
try
{
Class.forName(driver);
con = DriverManager.getConnection(url,uid,psw);
ps=con.prepareStatement("SELECT SUM(salary) AS total FROM worker");
rs = ps.executeQuery();
String title = "Using SUM(Total) Function";
String docType ="<!doctype html public \"-//w3c//dtd html 4.0 " + "transitional//en\">\n";
disp.println(docType + "<html>\n" + "<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f4efef\">\n" + "<h1 align=\"center\">" + title + "</h1>\n" + "<ul>\n" +
"<table width=\"50%\" border=\"1\" align=\"center\">\n" + "<th>Total</th>\n"+ "</body> </html>");
while(rs.next())
{
String tl = rs.getString("total");
disp.println("<tr><td align=\"center\">" + tl +"</td></tr>" );
}
}
catch(Exception e)
{
e.printStackTrace();
}
disp.close();
}
public void doPost(HttpServletRequest rq,HttpServletResponse rp)throws IOException,ServletException
{
doGet(rq,rp);
}
}
WEB.xml
<servlet>
<servlet-name>MySqlSUMFunction</servlet-name>
<servlet-class>MySqlSUMFunction</servlet-class>
</servlet>
<!-- servlet mapping -->
<servlet-mapping>
<servlet-name>MySqlSUMFunction</servlet-name>
<url-pattern>/MySqlSUMFunction</url-pattern>
</servlet-mapping>