Servlet以及一個簡單的登錄案例


1.servlet的概述

  就是一個運行在web服務器上的小的java程序,用來接收和響應從客戶端發送過來的請求,通常使用http協議

  就是sun公司提供的一個動態網頁開發技術

  作用:用來處理從客戶端瀏覽器發送的請求,並且可以對請求作出響應

  編寫類實現servlet:

public class Demo1 implements Servlet{

    @Override
    /**
     * 為用戶處理請求和響應的方法.
     */
    public void service(ServletRequest req, ServletResponse res) throws ServletException, IOException {
        res.getWriter().println("Hello Servlet...");
    }
...
}

servlet的配置:

 <servlet>
      <!-- Servlet的名稱 -->
      <servlet-name>Demo1</servlet-name>
      <!-- SErvlet的全路徑 -->
      <servlet-class>com.learn.servlet.Demo1</servlet-class>
  </servlet>
  
  <!-- Servlet的映射 -->
  <servlet-mapping>
      <!-- Servlet的名稱 -->
      <servlet-name>Demo1</servlet-name>
      <!-- Servlet的訪問路徑 -->
      <url-pattern>/Demo1</url-pattern>
  </servlet-mapping>

訪問路徑:

http://localhost:8080/day09/Demo1

  servlet接收參數的方法
String getParameter(String name); 用於接收一個名稱對應一個值的參數

String [] getParameterValues(String name) ;用於接收一個名稱對應多個值的參數

Map getParamterMap();  用於接收表單中的所有的參數,map中的key是表示表單提交的參數名稱,map的value是提交參數的值

Servlet的實現關系

Servlet         :接口

   |

GenericServlet  :通用的Servlet

   |

HttpServlet     :HttpServlet

2.使用servlet完成一個用戶登錄的案例

  需求:登錄的鏈接,點擊登錄連接,可以跳轉到登錄的頁面,在登錄的頁面中輸入用戶名和密碼點擊登錄完成登錄

創建數據庫和表

create database demo;
use demo;
create table user(
    id int primary key auto_increment,
    username varchar(20),
    password varchar(20)
);
insert into user values (null,'張三','111');
insert into user values (null,'李四','111');

引入jar包

  

* mysql的數據庫的驅動包

* c3p0連接池的jar包

* dbutils的包

編寫servle

  servlet層

protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //設置編碼表
        response.setContentType("text/html;charset=utf-8");
        //獲取表單數據
        String username = request.getParameter("username");
        String password = request.getParameter("password");
        //調用業務層
        UserService us = new UserService();
        
        try {
            //判斷從數據庫中查找的 user是否為空
            User user = us.login(username,password);
            System.out.println("從數據庫中獲取的數據為"+user);
            if(user == null) {
                response.getWriter().write("登錄失敗!");
                //結束方法后面不再執行
                return;
            }
            //登錄成功時
            response.getWriter().write("登錄成功,3秒后跳轉");
            response.sendRedirect(request.getContextPath()+"/LoginDemo/demo3-login/refresh.html");
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }

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

service層

//調用dao層
    UserDao dao = new UserDao();
    public User login(String username, String password) throws SQLException {
        User user = dao.login(username,password);
        return user;
    }

dao層

//初始化連接池
    QueryRunner qr = new QueryRunner(JDBCUtils.getDataSource());
    public User login(String username, String password) throws SQLException {
        //准備sql語句
        String sql = "select * from user where username=? and password=?";
        //設置占位符
        Object [] params = {username,password};
        //執行sql語句
        User user = qr.query(sql, new BeanHandler<User>(User.class), params);
        System.out.println("dao層的user為"+user);
        return user;
    }

utils層

private static final ComboPooledDataSource DATA_SOURCE =new ComboPooledDataSource();
    /**
     * 獲得連接的方法
     */
    public static Connection getConnection(){
        Connection conn = null;
        try {
            conn = DATA_SOURCE.getConnection();
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return conn;
    }
    
    public static DataSource getDataSource(){
        return DATA_SOURCE;
    }
    

c3p0配置文件

<?xml version="1.0" encoding="UTF-8"?>
<c3p0-config>
  <default-config>
    <property name="driverClass">com.mysql.jdbc.Driver</property>
    <property name="jdbcUrl">jdbc:mysql://localhost:3306/demo</property>
    <property name="user">root</property>
    <property name="password">root</property>
    <property name="initialPoolSize">10</property>
    <property name="maxIdleTime">30</property>
    <property name="maxPoolSize">100</property>
    <property name="minPoolSize">10</property>
  </default-config>
</c3p0-config>

3.servlet的聲明周期

  指的是servlet從創建到銷毀的過程

何時創建:用戶第一次訪問servlet創建servlet實例

何時銷毀:當項目從服務器中移除的時候,或者關閉服務器的時候

  用戶第一次訪問servlet的時候,服務器會創建一個servlet的實例,那么servlet中init方法就會執行.任何一次請求服務器都會創建一個新的線程訪問servlet中的service方法,在service方法內部根據請求的方式的不同調用do...方法,當servlet中服務器停止,就會調用destory方法

4.servlet的相關配置

  servlet默認是在第一次訪問 的時候創建的,現在讓servlet在服務器啟動的時候創建好

<load-on-startup>2</load-on-startup>  --- 傳入正整數,整數越小,被創建的優先級就越高.

  url-pattern的配置

 

1.完全路徑匹配    :以 / 開始              例如:    /ServletDemo1,/aaa/ServletDemo2

2.目錄匹配       :以 / 開始 需要以 * 結束. 例如: /* ,/aaa/* ,/aaa/bbb/*

3.擴展名匹配     :不能以 / 開始 以 * 開始的. 例如: *.do , *.action

***** 錯誤的寫法  : /*.do

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM