SlideShare une entreprise Scribd logo
1  sur  17
I
       • Forms and Actions

 II
       • Processing Form Data

VIII
       • Request and Response Objects

III
       • Database

IV
       • DB Connectivity

 V
       • Working With DB

VII
       • The Login Servlet
   HTML forms are used to pass data to a server.

   The most important form element is the input element.

   The input element is used to select user information.
    ◦ An input element can vary in many ways, depending on the type attribute. An input
      element can be of type text field, checkbox, password, radio button, submit button,
      and more.

                     Text Field: <input type="text" name="firstname" />

                   Password Field: <input type="password" name="pwd" />



                               A Great Source to Lookup on:
                               http://www.w3schools.com/
                      http://www.w3schools.com/html/html_forms.asp
   The required action attribute specifies where to send the form-data
    when a form is submitted.
              <form action="form_action.asp" method="get">
               First name: <input type="text" name="fname" /><br />
               Last name: <input type="text" name="lname" /><br />
               <input type="submit" value="Submit" />
              </form>


   The method attribute specifies how to send form-data (the form-
    data is sent to the page specified in the action attribute).
   Notes on the "get" method:
    ◦ This method appends the form-data to the URL in name/value pairs
    ◦ This method is useful for form submissions where a user want to bookmark the
      result
    ◦ There is a limit to how much data you can place in a URL (varies between browsers),
      therefore, you cannot be sure that all of the form-data will be correctly transferred
    ◦ Never use the "get" method to pass sensitive information! (password or other
      sensitive information will be visible in the browser's address bar)


   Notes on the "post" method:
    ◦ This method sends the form-data as an HTTP post transaction
    ◦ Form submissions with the "post" method cannot be bookmarked
    ◦ The "post" method is more robust and secure than "get", and "post" does not have
      size limitations
   ServletRequest
    ◦ Defines an object to provide client request information to a servlet.

    ◦ A ServletRequest object provides data including parameter name and values,
      attributes, and an input stream.



   HttpServletRequest
    ◦ Extends the ServletRequest interface to provide request information for HTTP
      servlets.

    ◦ The servlet container creates an HttpServletRequest object and passes it as an
      argument to the servlet's service methods (doGet, doPost, etc).




                     Note: A servlet container is nothing but a compiled, executable program. The main
                     function of the container is to load, initialize and execute servlets. A Servlet container
                     may run stand alone i.e. without a web server or even on another host.
   ServletResponse
    ◦ Defines an object to assist a servlet in sending a response to the client.




   HttpServletResponse
    ◦ Extends the ServletResponse interface to provide HTTP-specific functionality in
      sending a response. For example, it has methods to access HTTP headers and
      cookies.

    ◦ The servlet container creates an HttpServletResponse object and passes it as an
      argument to the servlet's service methods (doGet, doPost, etc).
import java.io.*;
import javax.servlet.*;
import javax.servlet.http.*;

public class Hello extends HttpServlet {

    public void doGet(HttpServletRequest req, HttpServletResponse res)
                      throws ServletException, IOException {

        res.setContentType("text/html");
        PrintWriter out = res.getWriter();

        String name = req.getParameter("name");
        out.println("<HTML>");
        out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>");
        out.println("<BODY>");
        out.println("Hello, " + name);
        out.println("</BODY></HTML>");
    }

    public String getServletInfo() {
      return "A servlet that knows the name of the person to whom it's" +
           "saying hello";
    }
}
   Often abbreviated DB. A collection of information organized in such
    a way that a computer program can quickly select desired pieces of
    data.

   A relational database is a collection of data items organized as a set
    of formally-described tables from which data can be accessed or
    reassembled in many different ways without having to reorganize
    the database tables.
   MySQL
    ◦ MySQL Community Edition is a freely downloadable version of the world's most
        popular open source database that is supported by an active community of open
        source developers and enthusiasts.
                               http://www.mysql.com/downloads/mysql/


   You will also need a GUI tool for designing the DB
    ◦   MySQL Workbench provides DBAs and developers an integrated tools environment for:

              Database Design & Modeling
              SQL Development (replacing MySQL Query Browser)
              Database Administration (replacing MySQL Administrator)
              The Community (OSS) Edition is available from:
               http://dev.mysql.com/downloads/workbench/
   Use the library provided to establish MySQL DB connectivity:
                       mysql-connector-java-5.1.19-bin.jar



   Initialize the DB using context listener in web.xml

   Use context-param for setting up DB parameters from web.xml

   Use MVC pattern to handle DB requests – e.g. DBManager class (It
    should be singleton)



                      How to use MySQL Java Connector:
                   http://dev.mysql.com/usingmysql/java/
private DatabaseManager(String hostName, String databaseName, String userName, String
password) {
super();
try {
         StringBuilder builder = new StringBuilder(“jdbc:mysql://”);
          builder.append(hostName)
.append("/").append(databaseName).append("?").append(PARAM_USER + "=" +
userName).append("&" + PARAM_PASSWORD + "=" + password);

         Class.forName(“com.mysql.jdbc.Driver”).newInstance();

         conn = DriverManager.getConnection(builder.toString());

         System.out.println("[DatabaseManager] Connection is created.");
 }
catch (SQLException ex) { // handle any errors
         System.out.println("SQLException: " + ex.getMessage());
         System.out.println("SQLState:     " + ex.getSQLState());
         System.out.println("VendorError: " + ex.getErrorCode());
 }
catch (Exception ex) { ex.printStackTrace(); } }
private Connection conn;
private static DatabaseManager instance = null;
private static final boolean[] LOCK_INSTANCE = new boolean[]{};

public static DatabaseManager getInstance(String hostName, String databaseName,
String userName, String password) {

    if (instance != null) { return instance; }

    synchronized (LOCK_INSTANCE) { if (instance != null) { return instance; }

     instance = new DatabaseManager(hostName, databaseName, userName, password);
    return instance;
    }

}
import java.sql.Statement;

public boolean isRegisteredUser(String username, String password) throws SQLException {

Statement stmt = conn.createStatement();

ResultSet rs = stmt.executeQuery("SELECT * " + "from users WHERE username='" + username
+ "' AND password='" + password + "'");

return rs.next();
 /**********************************************************/   }
   All the content should be placed under tomcat’s “webapps” directory
   Write a login and registration pages, using database for keeping
    accounts
AUA – CoE
Apr.21, Spring 2012

Contenu connexe

Tendances

MongoDB - A next-generation database that lets you create applications never ...
MongoDB - A next-generation database that lets you create applications never ...MongoDB - A next-generation database that lets you create applications never ...
MongoDB - A next-generation database that lets you create applications never ...Ram Murat Sharma
 
Running ms sql stored procedures in mule
Running ms sql stored procedures in muleRunning ms sql stored procedures in mule
Running ms sql stored procedures in muleAnilKumar Etagowni
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core DataMake School
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code FirstJames Johnson
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Michał Orman
 
Data Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesData Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesArvind Krishnaa
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesWebStackAcademy
 
Suportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EESuportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EERodrigo Cândido da Silva
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentalsMadhuri Kavade
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0Korhan Bircan
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generationEleonora Ciceri
 

Tendances (20)

Ch 7 data binding
Ch 7 data bindingCh 7 data binding
Ch 7 data binding
 
Ch05 state management
Ch05 state managementCh05 state management
Ch05 state management
 
MongoDB - A next-generation database that lets you create applications never ...
MongoDB - A next-generation database that lets you create applications never ...MongoDB - A next-generation database that lets you create applications never ...
MongoDB - A next-generation database that lets you create applications never ...
 
Running ms sql stored procedures in mule
Running ms sql stored procedures in muleRunning ms sql stored procedures in mule
Running ms sql stored procedures in mule
 
Intro to Core Data
Intro to Core DataIntro to Core Data
Intro to Core Data
 
ReactJS
ReactJSReactJS
ReactJS
 
Entity Framework Database and Code First
Entity Framework Database and Code FirstEntity Framework Database and Code First
Entity Framework Database and Code First
 
Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1Integration of Backbone.js with Spring 3.1
Integration of Backbone.js with Spring 3.1
 
Data Binding and Data Grid View Classes
Data Binding and Data Grid View ClassesData Binding and Data Grid View Classes
Data Binding and Data Grid View Classes
 
Angular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP ServicesAngular - Chapter 7 - HTTP Services
Angular - Chapter 7 - HTTP Services
 
Sqllite
SqlliteSqllite
Sqllite
 
Suportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EESuportando Aplicações Multi-tenancy com Java EE
Suportando Aplicações Multi-tenancy com Java EE
 
Ch06 ado.net fundamentals
Ch06 ado.net fundamentalsCh06 ado.net fundamentals
Ch06 ado.net fundamentals
 
ADO.NET
ADO.NETADO.NET
ADO.NET
 
ASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NETASP.NET 09 - ADO.NET
ASP.NET 09 - ADO.NET
 
Ajax
AjaxAjax
Ajax
 
Core Data with Swift 3.0
Core Data with Swift 3.0Core Data with Swift 3.0
Core Data with Swift 3.0
 
Mule caching strategy with redis cache
Mule caching strategy with redis cacheMule caching strategy with redis cache
Mule caching strategy with redis cache
 
Dynamic content generation
Dynamic content generationDynamic content generation
Dynamic content generation
 
jsp MySQL database connectivity
jsp MySQL database connectivityjsp MySQL database connectivity
jsp MySQL database connectivity
 

Similaire à Forms, Databases, Servlets: The Essentials

Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRPeter Elst
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Servicesukdpe
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical filevarun arora
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface pptTaha Malampatti
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...WebStackAcademy
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile appsIvano Malavolta
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jerseyb_kathir
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)Talha Ocakçı
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/ServletSunil OS
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to TornadoGavin Roy
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentjoearunraja2
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasyJBug Italy
 

Similaire à Forms, Databases, Servlets: The Essentials (20)

Practical OData
Practical ODataPractical OData
Practical OData
 
Servlets
ServletsServlets
Servlets
 
Introduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIRIntroduction to SQLite in Adobe AIR
Introduction to SQLite in Adobe AIR
 
Windows Azure and a little SQL Data Services
Windows Azure and a little SQL Data ServicesWindows Azure and a little SQL Data Services
Windows Azure and a little SQL Data Services
 
Advance Java Practical file
Advance Java Practical fileAdvance Java Practical file
Advance Java Practical file
 
Php summary
Php summaryPhp summary
Php summary
 
Servlets intro
Servlets introServlets intro
Servlets intro
 
Request dispacther interface ppt
Request dispacther interface pptRequest dispacther interface ppt
Request dispacther interface ppt
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
 
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4... Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
Web Component Development Using Servlet & JSP Technologies (EE6) - Chapter 4...
 
Local data storage for mobile apps
Local data storage for mobile appsLocal data storage for mobile apps
Local data storage for mobile apps
 
Developing RESTful WebServices using Jersey
Developing RESTful WebServices using JerseyDeveloping RESTful WebServices using Jersey
Developing RESTful WebServices using Jersey
 
RESTEasy
RESTEasyRESTEasy
RESTEasy
 
JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)JAVA EE DEVELOPMENT (JSP and Servlets)
JAVA EE DEVELOPMENT (JSP and Servlets)
 
Jsp/Servlet
Jsp/ServletJsp/Servlet
Jsp/Servlet
 
Servlets
ServletsServlets
Servlets
 
An Introduction to Tornado
An Introduction to TornadoAn Introduction to Tornado
An Introduction to Tornado
 
Ajax
AjaxAjax
Ajax
 
J2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environmentJ2EE : Java servlet and its types, environment
J2EE : Java servlet and its types, environment
 
May 2010 - RestEasy
May 2010 - RestEasyMay 2010 - RestEasy
May 2010 - RestEasy
 

Dernier

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGSujit Pal
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024Rafal Los
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationSafe Software
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Miguel Araújo
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerThousandEyes
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonetsnaman860154
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...HostedbyConfluent
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...gurkirankumar98700
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024BookNet Canada
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking MenDelhi Call girls
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Allon Mureinik
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)Gabriella Davis
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationRidwan Fadjar
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonAnna Loughnan Colquhoun
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 

Dernier (20)

Google AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAGGoogle AI Hackathon: LLM based Evaluator for RAG
Google AI Hackathon: LLM based Evaluator for RAG
 
The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024The 7 Things I Know About Cyber Security After 25 Years | April 2024
The 7 Things I Know About Cyber Security After 25 Years | April 2024
 
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time AutomationFrom Event to Action: Accelerate Your Decision Making with Real-Time Automation
From Event to Action: Accelerate Your Decision Making with Real-Time Automation
 
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
Mastering MySQL Database Architecture: Deep Dive into MySQL Shell and MySQL R...
 
How to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected WorkerHow to Troubleshoot Apps for the Modern Connected Worker
How to Troubleshoot Apps for the Modern Connected Worker
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
How to convert PDF to text with Nanonets
How to convert PDF to text with NanonetsHow to convert PDF to text with Nanonets
How to convert PDF to text with Nanonets
 
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
Transforming Data Streams with Kafka Connect: An Introduction to Single Messa...
 
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
Kalyanpur ) Call Girls in Lucknow Finest Escorts Service 🍸 8923113531 🎰 Avail...
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
Transcript: #StandardsGoals for 2024: What’s new for BISAC - Tech Forum 2024
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men08448380779 Call Girls In Friends Colony Women Seeking Men
08448380779 Call Girls In Friends Colony Women Seeking Men
 
Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)Injustice - Developers Among Us (SciFiDevCon 2024)
Injustice - Developers Among Us (SciFiDevCon 2024)
 
A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)A Domino Admins Adventures (Engage 2024)
A Domino Admins Adventures (Engage 2024)
 
My Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 PresentationMy Hashitalk Indonesia April 2024 Presentation
My Hashitalk Indonesia April 2024 Presentation
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 
Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
Data Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt RobisonData Cloud, More than a CDP by Matt Robison
Data Cloud, More than a CDP by Matt Robison
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 

Forms, Databases, Servlets: The Essentials

  • 1.
  • 2. I • Forms and Actions II • Processing Form Data VIII • Request and Response Objects III • Database IV • DB Connectivity V • Working With DB VII • The Login Servlet
  • 3. HTML forms are used to pass data to a server.  The most important form element is the input element.  The input element is used to select user information. ◦ An input element can vary in many ways, depending on the type attribute. An input element can be of type text field, checkbox, password, radio button, submit button, and more. Text Field: <input type="text" name="firstname" /> Password Field: <input type="password" name="pwd" /> A Great Source to Lookup on: http://www.w3schools.com/ http://www.w3schools.com/html/html_forms.asp
  • 4. The required action attribute specifies where to send the form-data when a form is submitted. <form action="form_action.asp" method="get"> First name: <input type="text" name="fname" /><br /> Last name: <input type="text" name="lname" /><br /> <input type="submit" value="Submit" /> </form>  The method attribute specifies how to send form-data (the form- data is sent to the page specified in the action attribute).
  • 5. Notes on the "get" method: ◦ This method appends the form-data to the URL in name/value pairs ◦ This method is useful for form submissions where a user want to bookmark the result ◦ There is a limit to how much data you can place in a URL (varies between browsers), therefore, you cannot be sure that all of the form-data will be correctly transferred ◦ Never use the "get" method to pass sensitive information! (password or other sensitive information will be visible in the browser's address bar)  Notes on the "post" method: ◦ This method sends the form-data as an HTTP post transaction ◦ Form submissions with the "post" method cannot be bookmarked ◦ The "post" method is more robust and secure than "get", and "post" does not have size limitations
  • 6. ServletRequest ◦ Defines an object to provide client request information to a servlet. ◦ A ServletRequest object provides data including parameter name and values, attributes, and an input stream.  HttpServletRequest ◦ Extends the ServletRequest interface to provide request information for HTTP servlets. ◦ The servlet container creates an HttpServletRequest object and passes it as an argument to the servlet's service methods (doGet, doPost, etc). Note: A servlet container is nothing but a compiled, executable program. The main function of the container is to load, initialize and execute servlets. A Servlet container may run stand alone i.e. without a web server or even on another host.
  • 7. ServletResponse ◦ Defines an object to assist a servlet in sending a response to the client.  HttpServletResponse ◦ Extends the ServletResponse interface to provide HTTP-specific functionality in sending a response. For example, it has methods to access HTTP headers and cookies. ◦ The servlet container creates an HttpServletResponse object and passes it as an argument to the servlet's service methods (doGet, doPost, etc).
  • 8. import java.io.*; import javax.servlet.*; import javax.servlet.http.*; public class Hello extends HttpServlet { public void doGet(HttpServletRequest req, HttpServletResponse res) throws ServletException, IOException { res.setContentType("text/html"); PrintWriter out = res.getWriter(); String name = req.getParameter("name"); out.println("<HTML>"); out.println("<HEAD><TITLE>Hello, " + name + "</TITLE></HEAD>"); out.println("<BODY>"); out.println("Hello, " + name); out.println("</BODY></HTML>"); } public String getServletInfo() { return "A servlet that knows the name of the person to whom it's" + "saying hello"; } }
  • 9. Often abbreviated DB. A collection of information organized in such a way that a computer program can quickly select desired pieces of data.  A relational database is a collection of data items organized as a set of formally-described tables from which data can be accessed or reassembled in many different ways without having to reorganize the database tables.
  • 10. MySQL ◦ MySQL Community Edition is a freely downloadable version of the world's most popular open source database that is supported by an active community of open source developers and enthusiasts. http://www.mysql.com/downloads/mysql/  You will also need a GUI tool for designing the DB ◦ MySQL Workbench provides DBAs and developers an integrated tools environment for:  Database Design & Modeling  SQL Development (replacing MySQL Query Browser)  Database Administration (replacing MySQL Administrator)  The Community (OSS) Edition is available from: http://dev.mysql.com/downloads/workbench/
  • 11. Use the library provided to establish MySQL DB connectivity: mysql-connector-java-5.1.19-bin.jar  Initialize the DB using context listener in web.xml  Use context-param for setting up DB parameters from web.xml  Use MVC pattern to handle DB requests – e.g. DBManager class (It should be singleton) How to use MySQL Java Connector: http://dev.mysql.com/usingmysql/java/
  • 12. private DatabaseManager(String hostName, String databaseName, String userName, String password) { super(); try { StringBuilder builder = new StringBuilder(“jdbc:mysql://”); builder.append(hostName) .append("/").append(databaseName).append("?").append(PARAM_USER + "=" + userName).append("&" + PARAM_PASSWORD + "=" + password); Class.forName(“com.mysql.jdbc.Driver”).newInstance(); conn = DriverManager.getConnection(builder.toString()); System.out.println("[DatabaseManager] Connection is created."); } catch (SQLException ex) { // handle any errors System.out.println("SQLException: " + ex.getMessage()); System.out.println("SQLState: " + ex.getSQLState()); System.out.println("VendorError: " + ex.getErrorCode()); } catch (Exception ex) { ex.printStackTrace(); } }
  • 13. private Connection conn; private static DatabaseManager instance = null; private static final boolean[] LOCK_INSTANCE = new boolean[]{}; public static DatabaseManager getInstance(String hostName, String databaseName, String userName, String password) { if (instance != null) { return instance; } synchronized (LOCK_INSTANCE) { if (instance != null) { return instance; } instance = new DatabaseManager(hostName, databaseName, userName, password); return instance; } }
  • 14. import java.sql.Statement; public boolean isRegisteredUser(String username, String password) throws SQLException { Statement stmt = conn.createStatement(); ResultSet rs = stmt.executeQuery("SELECT * " + "from users WHERE username='" + username + "' AND password='" + password + "'"); return rs.next(); /**********************************************************/ }
  • 15. All the content should be placed under tomcat’s “webapps” directory
  • 16. Write a login and registration pages, using database for keeping accounts
  • 17. AUA – CoE Apr.21, Spring 2012