The first JSP + Servlet + JavaBean + JDBC sample programs

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

分类:Java 时间:2010-04-20 人气:958
分享到:
blog comments powered by Disqus

相关文章

  • [Turn] on 2147217913 from the char data type to a datetime data type datetime value of the conversion result in cross-border problem-solving methods 2010-07-23

    Transfer from: http://blog.csdn.net/derryzhang/archive/2009/06/29/4306071.aspx Bolivia recently received customer feedback, run the program always prompts: 2147217913: La conversión del tipo de datos char a datetime produjo un valor datetime fuera de

  • mysql pagination jsp + servlet + javabean achieve 2011-04-19

    MYSQL page summary of the software development often many occasions we need to use paging technology, now a lot of paging technology, but I do not know much, such as displaytag paging plugin I feel really very good but a bit You can export the pdf, w

  • Refresh the page to retain the value of input type 2009-06-13

    Transfer from: http://unbounder.javaeye.com/blog/459183 In general, the page refreshes without the need to retain the value of input type are more, but there are exceptions, for example, I it was a case of the need to retain the value of input type .

  • input type = file against the user to manually enter 2010-07-31

    1. Replace the law Using hidden <input type="file"/> control, then a read-only text box and a button to simulate <input type="file"/> function. <input type="file" name="file" onpropertychange="fi

  • input type = file tag ban the user to manually enter 2010-08-02

    Surface is the method used: 1. Substitution Using hidden <input type="file"/> control, then a read-only text box and a button to simulate <input type="file"/> function. <Input type = "file" name = "file&qu

  • input type description 2010-11-19

    Form Input in the form that an input object, its type and with different sub-Type text input box, the password input box, radio / check box, and submit / reset buttons, the following introduced one by one. 1, type = text Input type is text, this is t

  • Dynamically change the input type tag attributes (such as the password to text) 2010-12-25

    <HTML> <head> <meta http-equiv="Content-Type" content="text/html; charset=gb2312"> <script> function removeSubmitFocus () { document.all ('pass'). outerHTML = "<input type = text name ='" + document

  • js 获取.清空input type="file"的值示例代码 2014-09-28

    本篇文章主要是对js获取.清空input type="file"的值的示例代码进行了介绍,需要的朋友可以过来参考下,希望对大家有所帮助 上传控件基础知识说明: 上传控件(<input type="file"/>)用于在客户端浏览并上传文件,用户选取的路径可以由value属性获取,但value属性是只读的,不能通过javascript来赋值,这就使得不能通过value=""语句来清空它.很容易理解为什么只读,如果可以随意赋值的话,那么用

  • firefox下input type="file"的size是多大 2014-12-20

    firefox对type="file" 的input的width定义目前是不支持的,但是FF支持size属性,可以给size设置一个值,来控制上传框的大小 但是这个size值怎么设置,size="10"是多宽,默认值又是多少,不能光凭感觉去设置. 用脚本来查看下: <script type="text/javascript"> $(function() { var fileArray = []; var i = 0; while (i

  • js 获取.清空input type="file"的值(示例代码) 2015-01-07

    本篇文章主要介绍了js 获取.清空input type="file"的值(示例代码) 需要的朋友可以过来参考下,希望对大家有所帮助 上传控件(<input type="file"/>)用于在客户端浏览并上传文件,用户选取的路径可以由value属性获取,但value属性是只读的,不能通过 javascript来赋值,这就使得不能通过value=""语句来清空它.很容易理解为什么只读,如果可以随意赋值的话,那么用户只要打开你的网页, 你就

iOS 开发

Android 开发

Python 开发

JAVA 开发

开发语言

PHP 开发

Ruby 开发

搜索

前端开发

数据库

开发工具

开放平台

Javascript 开发

.NET 开发

云计算

服务器

Copyright (C) codeweblog.com, All Rights Reserved.

CodeWeblog.com 版权所有 黔ICP备15002463号-1

processed in 0.654 (s). 12 q(s)