The first JSP + Servlet + JavaBean + JDBC sample programs

sponsored links
Operating Environment:
Quote

JDK1.5
Tomcat5.5
MyEclips5.5.1 GA
SqlServer2000
windows2003

1. SqlServer Query Analyzer under the new table:
create table dbuser(
userId int identity(1,1) primary key not null,
userName varchar(50),
userPasswd varchar(50))


2. In the new MyEclipse Web project and create a package structure.

The first JSP + Servlet + JavaBean + JDBC sample programs


3. Preparation of the login screen.
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
<style type="text/css">
body{
 color : #000 ;
 font-size : 12px ;

 margin : 0px auto ;
 }

</style>

<script type="text/javascript">
    function check(form){
    //document.forms.form1.username.value Get the Form1  Username Values and determine whether the is empty  
        if(document.forms.form1.username.value==""){
        // If  "" The pop-up tips  
            alert("pls input username");
            // The input focus to navigate to the place where did not enter  
            document.forms.form1.username.focus();
            // Returns an error  
            return false;
        }
                if(document.forms.form1.password.value==""){
            alert("pls input password");
            document.forms.form1.password.focus();
            return false;
        }
    }

</script>
</head>
<body>
<form action="LoginServlet" method="post" name="form1">
    
    
<table border="1" cellspacing="1" cellpadding="1"  bordercolor="silver" align="center">
   <tr>
      <td colspan="2" align="center" bgcolor="#e8e8e8"> User.  </td>
   </tr>
   <tr>
      <td> User name  :</td>
      <td><input type="text" name="username"/></td>
   </tr>
   <tr>
      <td> Password  :</td>
      <td><input type="password" name="password"/></td>
   </tr>
   <tr>
      <td><a href="rsg.jsp" > New user registration  </a></td>
      <!--"return check(this)  Call the above Script validation   -->
      <td><input type="submit" name="submit"/><input type="reset" name="reset"/></td>
   </tr>
</table>

</form>
</body>
</html>


The first JSP + Servlet + JavaBean + JDBC sample programs


3. Preparation tools DBConn.
package utils;

        import java.io.*;   
import java.sql.*;   

public class DBConn {   
            public static String driver;// Define driver     
            public static String url;// Definition  URL   
            public static String user;// Define username     
            public static String password;// Defines the password     
            public static Connection conn;// Define the connection     
            public static Statement stmt;// Definition  STMT   
            public ResultSet rs;// Defines the result set     
            // Set  CONN   
            static{   
                try { 
                        driver="com.microsoft.jdbc.sqlserver.SQLServerDriver";
                        url="jdbc:microsoft:sqlserver://localhost:1433;DatabaseName=qtliu";
                        user="sa";
                        password="sa";
                    Class.forName(driver);   
                    conn = DriverManager.getConnection(url,user,password);
                    System.out.println("------- The connection is successful  ------");
                } catch(ClassNotFoundException classnotfoundexception) {   
                      classnotfoundexception.printStackTrace();   
                    System.err.println("db: " + classnotfoundexception.getMessage());   
                } catch(SQLException sqlexception) {   
                    System.err.println("db.getconn(): " + sqlexception.getMessage());   
                }   
            }   
            // Constructor, the default profile for Canada cutting  jdbc.driver   
            public DBConn(){   
                this.conn=this.getConn();
            }   
            // Returns the  Conn   
            public Connection getConn(){   
                return this.conn;   
            }   
            // Performs an insert     
               public void doInsert(String sql) {   
                try {   
                    stmt = conn.createStatement();   
                    int i = stmt.executeUpdate(sql);   
                } catch(SQLException sqlexception) {   
                    System.err.println("db.executeInset:" + sqlexception.getMessage());   
                }finally{   
                       
                }   
            }   
            // Perform removal     
            public void doDelete(String sql) {   
                try {   
                    stmt = conn.createStatement();   
                    int i = stmt.executeUpdate(sql);   
                } catch(SQLException sqlexception) {   
                    System.err.println("db.executeDelete:" + sqlexception.getMessage());   
                }   
            }   
            // To perform the update     
            public void doUpdate(String sql) {   
                try {   
                    stmt = conn.createStatement();   
                    int i = stmt.executeUpdate(sql);   
                } catch(SQLException sqlexception) {   
                    System.err.println("db.executeUpdate:" + sqlexception.getMessage());   
                }   
            }   
            // The query result set     
            public ResultSet doSelect(String sql) {   
                try {
                        conn=DriverManager.getConnection(url,user,password);
                        stmt = conn.createStatement(java.sql.ResultSet.TYPE_SCROLL_INSENSITIVE,java.sql.ResultSet.CONCUR_READ_ONLY);     
                    rs = stmt.executeQuery(sql); 
                    System.out.println(" Get result set  ");
                } catch(SQLException sqlexception) {   
                    System.err.println("db.executeQuery: " + sqlexception.getMessage());   
                }   
                return rs;   
            }   
            /**  
             * Close the database result set, the database operation object  , The database link    
               @Function: Close all the statement and conn int this instance and close the parameter ResultSet  
               @Param: ResultSet  
               @Exception: SQLException,Exception  
              **/  
             public void close(ResultSet rs) throws SQLException, Exception {   
          
               if (rs != null) {   
                 rs.close();   
                 rs = null;   
               }   
          
               if (stmt != null) {   
                 stmt.close();   
                 stmt = null;   
               }   
          
               if (conn != null) {   
                 conn.close();   
                 conn = null;   
               }   
             }   
          
             /**  
              * Close the database object, the database connection object    
              * Close all the statement and conn int this instance  
              * @throws SQLException  
              * @throws Exception  
              */  
             public void close() throws SQLException, Exception {   
               if (stmt != null) {   
                 stmt.close();   
                 stmt = null;   
               }   
          
               if (conn != null) {   
                 conn.close();   
                 conn = null;   
               }   
             }   
            // The test class     
//           public static void main(String []args){
//               DBConn db=new DBConn();
//               db.getConn();
//              ResultSet rs=db.doSelect("select * from db_user where userName='admin'");
//              try {
//                              while(rs.next()){
//                                      System.out.println(rs.getInt(1));
//                                      System.out.println(rs.getString(3));
//                                      
//                              }
//                      } catch (SQLException e) {
//                              // TODO Auto-generated catch block
//                              e.printStackTrace();
//                      }
//           }
        }  


4. Write Servlet, LoginServlet.java.
package servlet;

import java.io.IOException;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import model.CheckUser;
import beans.UserBean;

public class LoginServlet extends HttpServlet {

        /**
         * 
         */
        private static final long serialVersionUID = 7381169134016556647L;

        public void doGet(HttpServletRequest request, HttpServletResponse response)
                        throws ServletException, IOException {
                        doPost(request,response);
        }

        public void doPost(HttpServletRequest request, HttpServletResponse response)
                        throws ServletException, IOException {
                // Set up the document types  , Here is a Text/html, if you change to  application\msword It is set to Word document format  
                response.setContentType("text/html");
                // Set the response the encoding  
                response.setCharacterEncoding("GB18030");
                // Get the value of the username parameter  
                String uname=request.getParameter("username");
                String passwd=request.getParameter("password");
                
                
                UserBean user=new UserBean();
                user.setUsername(uname);
                user.setPassword(passwd);
                CheckUser cku=new CheckUser();
                boolean bool=cku.checkUsre(user);
                
                String forward;
                if(bool){
                        forward="success.jsp";
                        
                }else{
                        forward="error.jsp";
                }
                RequestDispatcher rd=request.getRequestDispatcher(forward);
                rd.forward(request,response);
        }


}

5. Web.xml to configure Servlet.

Quote

Configuration key code
 <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>servlet.LoginServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>


The machine code for the entire Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" 
        xmlns="http://java.sun.com/xml/ns/javaee" 
        xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
        xsi:schemaLocation="http://java.sun.com/xml/ns/javaee 
        http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>servlet.LoginServlet</servlet-class>
  </servlet>

  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
</web-app>


5. Write userBean.
package beans;

public class UserBean {
        

        public String username;
        public String password;
        
        public UserBean() {
                super();
        }
        
        
        public String getPassword() {
                return password;
        }
        public void setPassword(String password) {
                this.password = password;
        }
        public String getUsername() {
                return username;
        }
        public void setUsername(String username) {
                this.username = username;
        }

}


6. Write JavaBean CheckUser.
package model;

import java.sql.ResultSet;
import java.sql.SQLException;

import utils.DBConn;
import utils.DBUtils;
import beans.UserBean;

public class CheckUser {
        
        public boolean checkUsre(UserBean user){
                if(user.username.equals("")||user.username!=null){
                        ResultSet rs=null;
                        DBConn db=new DBConn();
                        rs=db.doSelect("select * from db_user where userName='"+user.getUsername()+"'");
                        try {
                                if(rs.next()){
                                        if(user.password.equals("")||user.password!=null){
                                                rs=db.doSelect("select * from db_user where userPasswd="+user.password);
                                                return true;
                                        }
                                }
                        } catch (SQLException e) {
                                e.printStackTrace();
                        }
                }
                
                return false;
                
        }

}


7. Preparation of the error page and the successful landing page.

error.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
Sorry! Your login information is not correct  ! The system cannot log you  !<a href="login.jsp"> Click on return  </a>
</body>
</html>


success.jsp
<%@ page language="java" contentType="text/html; charset=GB18030"
    pageEncoding="GB18030"%>

<jsp:useBean scope="request"/>
<jsp:setProperty name="user" property="*"/>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=GB18030">
<title>Insert title here</title>
</head>
<body>
<% 
        session.setAttribute("user",user);
        String username=user.getUsername();
 %>
 
 <%=username %>, Welcome to FUCK network  !<br>
  Your IP is  :<%=request.getRemoteAddr() %><br>
 Your host is  :<%=request.getRemoteHost() %><br>
 Your use of the Protocol is  :<%=request.getProtocol() %><br>
 Is your current address  :<%=request.getRealPath("/") %>
 Your host port is  :<%=request.getRemotePort() %>
</body>
</html>


================================================== ===================
Page flow chart

The first JSP + Servlet + JavaBean + JDBC sample programs


The knowledge points:
* JDBC connection to the database written

* Servlet configured in Web.xml

The first JSP + Servlet + JavaBean + JDBC sample programs


* Use JavaBean in JSP

<jsp:useBean> and <jsp:setProperty>
<jsp:useBean> and <jsp:setProperty> is linked, in the name value <jsp:setProperty> <jsp:useBean> the ID should be and the same value.

<jsp:useBean scope="request"/>
<jsp:setProperty name="user" property="*"/>


* Js validation written, and the trigger in the page
<script type="text/javascript">
    function check(form){
        if(document.forms.form1.username.value==""){
            alert("pls input username");
            document.forms.form1.username.focus();
            return false;
        }
                if(document.forms.form1.password.value==""){
            alert("pls input password");
            document.forms.form1.password.focus();
            return false;
        }
    }

</script>

<input type="submit" name="submit"/>


* Request, response of common usage

request Common methods  

 Obtaining relevant information  :
 Your IP is  :<%=request.getRemoteAddr() %><br>
 Your host is  :<%=request.getRemoteHost() %><br>
 Your use of the Protocol is  :<%=request.getProtocol() %><br>
 Is your current address  :<%=request.getRealPath("/") %>

 Receives the request content  :

 Through  :Request.getParemeter("username")  Receives the request content  : The code looks like this  :
String name = request.getParameter("uname") ;
 Get text information submitted  
String name = request.getParameter("uname") ;
 Get the button name  :
String name = request.getParameter("submit") ;

 Set the browser's output file type, and the coding standard  
<%@page contentType="text/html;charset=gb2312"%>

 Two seconds to jump to a new page  :
<%response.setHeader("refresh","3;URL=login.jsp");%>

// Set up the document types  , Here is a Text/html, if you change to  application\msword It is set to Word document format  

response.setContentType("text/html");

// Set the response the encoding  
response.setCharacterEncoding("GB18030");


* The difference between forward and redirect

Turn the page:
Redirect (redirect): previous store request variables in all the failure, and enter a new request scope.
Forward (Forward): previous request stored in the variable will not fail, would be like to fight with two pages.
<jsp:forward page="login_success.jsp"/>
(Note: if using the server-side jump <jsp:forward>, then request the content pages can be continued after the jump)
Response.sendRedirect("URL");// Redirect  

request.getRequestDispatcher("apage.jsp").forward(request, response);// Forwarded to  apage.jsp
<jsp:forward page="d.jsp"/>   // Forwarded to d.jsp in  JSP In use  
response.sendRedirect("apage.jsp");// Redirect to  apage.jsp
  • del.icio.us
  • StumbleUpon
  • Digg
  • TwitThis
  • Mixx
  • Technorati
  • Facebook
  • NewsVine
  • Reddit
  • Google
  • LinkedIn
  • YahooMyWeb

Related Posts of The first JSP + Servlet + JavaBean + JDBC sample programs

  • Built environment using appfuse2.0 Express (myeclipse)

    http://blog.csdn.net/ljah/archive/2008/06/06/2516187.aspx Usually we use APPFUSE2.0 project into eclipse, the compiler can not be normal, can only use maven I feel very uncomfortable, after exploring and found that after such a configuration, it will make

  • Javascript object inheritance

    Javascript object inheritance

  • fck pages

    <% @ Page contentType = "text / html; charset = UTF-8"%> <% @ Include file = "/ commons / taglibs.jsp"%> <% @ Taglib uri = "/ FCKeditor" prefix = "FCK"%> <script language = "javascript

  • javascript regular expressions Basic Usage

    <script type="text/javascript"> window.onload = function(){ //RegExpInitialization ,gRefers to the global ,iIs case-insensitive var reg = new RegExp("cat","gi"); var exp = /cat/gi; //RegExpThe test ()Method ,The return value is true or false alert(r

  • Javascript Object Model

    Javascript Object Model

  • JUnit Unit Testing Summary

    Read some of the unit test article, from the article in the interception of a number of information, which could be considered in the learning process, a summary of it! See future! Unit testing code is not used to prove you are right, but in order to ...

  • JavaScript inheritance

    About JavaScript inherited a small example ... <! DOCTYPE HTML PUBLIC "- / / W3C / / DTD HTML 4.01 / / EN" "http://www.w3.org/TR/html4/strict.dtd"> <html> <head> <meta http-equiv="Content-Type" conte ...

  • RoR explained

    ROR is Ruby on Rails. Ruby is a well-known has been very good dynamic language It's dynamic language. Simple and easy. Dynamic languages are interpreted, but the performance may make a discount, but not absolute, because the application is complex, th

  • spring + hibernate + oracle9i to read and write CLOB

    Database-driven update classes12-9i.jar Hibernate modify the configuration of the following code <bean/> <bean Lazy-init="true"> <property name="nativeJdbcExtractor"> <ref local="nativejdbcExtractor"/>

  • In the servlet use Bean

    According to Sun's definition, JavaBean is a reusable software components. In fact JavaBean is a Java class, through the package into a property and methods of treatment of a function or a business object, referred to as bean. Because JavaBean is ...

blog comments powered by Disqus
Recent
Recent Entries
Tag Cloud
Random Entries