1. 程式人生 > >JavaEE(5)——Servlet技術

JavaEE(5)——Servlet技術

1 實驗目的

  1. 掌握Servlet工作原理;
  2. 重點掌握Servlet設計要點;
  3. 在JSP中靈活運用Servlet。

2實驗注意事項

  1. Servlet嚮導生成的doGet()方法中使用response.setContentType(“text/html;charset=UTF-8”);避免輸出中文亂碼;
  2. 表單提交資料是,應使用:request.setCharacterEncoding(“utf-8”);解決post提交的中文亂碼問題;
  3. Servlet的訪問路徑是在設計Servlet時由Mapping URL決定的,使用者訪問Servlet路徑為:專案虛擬路徑+Mapping URL路徑,表單提交或頁面跳轉時,要注意原始檔路徑與目標檔案URL路徑之間的關係,要靈活運用“. /”、 “. ./”、“/”相對路徑符號: “. /”:頁面基準路徑是當前路徑; “. ./”:上一級路徑; “/”:Web伺服器的根路徑。

3 實驗任務與步驟

3.1 Servlet輸出表單的全部資料項

任務描述: 設計一個Servlet接收表單,尋找表單傳過來的所有變數名稱,並將其放入表格中,沒有值或有多個值的變數都突出顯示。 首先,通過HttpServletRequest的getParameterNames()方法獲取表單中所有變數的名稱,該方法返回的是一個列舉型別集合(Enumeration),接下來迴圈遍歷該Enumeration,通過hasMoreElements()方法確定何時結束迴圈,通nextElement()方法得到集合中各個項,nextElement()方法返回的是Object型別,需要將其強制轉換為所需要的String型別。再呼叫getParameterValues()方法得到字串陣列如果這個陣列只有一個元素且為空字串,說明這個表單變數沒有值,Servlet以斜體形式輸出“No Value”,如果陣列元素個數大於1,說明這個表單變數有多個值,以列表形式輸出這些值;其它情況下Servlet直接把變數值放入表格。

3.1.1 建立ShowParameterServlet.java

package exp05.bean;

import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.
*; public class ShowParameterServlet extends HttpServlet { @Override public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { request.setCharacterEncoding("UTF-8"); response.setContentType("text/html;charset=UTF-8"); PrintWriter out = response.getWriter(); String title = "讀取所有請求引數"; out.println(ServletUtilities.headWithTitle(title) + "<BODY BGCOLOR=\"#FDF5E6\">\n" + "<H1 ALIGN=CENTER>" + title + "</H1>\n" + "<TABLE BORDER=1 ALIGN=CENTER>\n" + "<TR BGCOLOR=\"#FFAD00\">\n" + "<TH>引數名字<TH>引數值"); Enumeration paramNames = request.getParameterNames(); while (paramNames.hasMoreElements()) { String paramName = (String) paramNames.nextElement(); out.println("<TR><TD>" + paramName + "\n<TD>"); String[] paramValues = request.getParameterValues(paramName); if (paramValues.length == 1) { String paramValue = paramValues[0]; if (paramValue.length() == 0) { out.print("<I>No Value</I>"); } else { out.print(paramValue); } } else { out.println("<UL>"); for (int i = 0; i < paramValues.length; i++) { out.println("<LI>" + paramValues[i]); } out.println("</UL>"); } } out.println("</TABLE>\n</BODY></HTML>"); } @Override public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException { doGet(request, response); } }

3.1.2 編寫ServletUtilities.java

ShowParameterServlet.java中使用了ServletUtilities類的headWithTitle(String title)方法設定頁面head資訊,

package exp05.bean;

public class ServletUtilities {

    public static final String DOCTYPE
            = "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.0 Transitional//EN\">";

    public static String headWithTitle(String title) {
        return (DOCTYPE + "\n" + "<HTML>\n" + "<HEAD><TITLE>" + title + "</TITLE></HEAD>\n");
    }
}

3.1.3 編寫postForm.html

<!DOCTYPE html>
<HTML>
<HEAD>
  <TITLE>示例頁面</TITLE>
  <meta http-equiv="Content-Type" content="text/html;charset=UTF-8">
</HEAD>
<BODY BGCOLOR="#FDF5E6">
<H1 ALIGN="CENTER">用Post方法傳送表單</H1>
<FORM ACTION="../../../ShowParameterServlet" METHOD="POST">
  職工編號:<INPUT TYPE="TEXT" NAME="xh"><BR>
  職工姓名:<INPUT TYPE="TEXT" NAME="name"><BR>
  所學專業:<INPUT TYPE="TEXT" NAME="zy" value="通訊工程"><BR>  <HR>
  email:<INPUT TYPE="TEXT" NAME="email"><BR>
  聯絡電話:<INPUT TYPE="TEXT" NAME="tele"><BR>
 家庭住址: <TEXTAREA NAME="address" ROWS=3 COLS=40></TEXTAREA><BR>
  銀行卡型別:<BR>  
<INPUT TYPE="RADIO" NAME="cardType" value="Visa">Visa<BR>
        <INPUT TYPE="RADIO" NAME="cardType" value="Amex">American Express<BR>
        <INPUT TYPE="RADIO" NAME="cardType" value="Discover">Discover<BR>
        <INPUT TYPE="RADIO" NAME="cardType" value="Java SmartCard">SmartCard<BR>
 銀行卡號: <INPUT TYPE="PASSWORD" NAME="cardNum"><BR>
  請重複輸入銀行卡號: <INPUT TYPE="PASSWORD" NAME="cardNum"><BR><BR>
  <CENTER>  <INPUT  TYPE="SUBMIT"  value="提交">  </CENTER>
</FORM>
</BODY>
</HTML>

3.1.4 編寫web.xml配置檔案

<?xml version="1.0" encoding="UTF-8"?>
<web-app version="3.1" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
    <servlet>
        <servlet-name>ShowParameterServlet</servlet-name>
        <servlet-class>exp05.bean.ShowParameterServlet</servlet-class>
    </servlet>
    <servlet>
        <servlet-name>LoginServlet</servlet-name>
        <servlet-class>exp05.bean.LoginServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>ShowParameterServlet</servlet-name>
        <url-pattern>/ShowParameterServlet</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>LoginServlet</servlet-name>
        <url-pattern>/LoginServlet</url-pattern>
    </servlet-mapping>
    <session-config>
        <session-timeout>
            30
        </session-timeout>
    </session-config>
</web-app>

3.1.5 測試執行

3.2 使用者登入驗證功能

任務描述: 編寫JSP程式,實習使用者提交登入表單資料到Servlet,由Servlet查詢資料庫,對使用者是否存在進行驗證。

3.2.1 建立資料庫db_user

SET FOREIGN_KEY_CHECKS=0;

DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `loginname` varchar(15) DEFAULT NULL,
  `password` varchar(20) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM AUTO_INCREMENT=6 DEFAULT CHARSET=utf8;

INSERT INTO `user` VALUES ('1', '張轉', '123');
INSERT INTO `user` VALUES ('2', '楊和', '123');
INSERT INTO `user` VALUES ('3', '李智', '123');
INSERT INTO `user` VALUES ('4', '何輝', '123');
INSERT INTO `user` VALUES ('5', 'tom', '123');

3.2.2 編寫DBConn.java

package exp05.bean;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class DBConn {

    private static final String DRIVER_CLASS = "com.mysql.jdbc.Driver";
    private static final String DATABASE_URL = "jdbc:mysql://localhost:3306/db_user?useUnicode=true&characterEncoding=utf-8";
    private static final String DATABASE_USRE = "root";
    private static final String DATABASE_PASSWORD = "root";

    // 返回連線
    public static Connection getConnction() {
        Connection dbConnection = null;
        try {
            Class.forName(DRIVER_CLASS);
            dbConnection = DriverManager.getConnection(DATABASE_URL,
                    DATABASE_USRE, DATABASE_PASSWORD);
        } catch (ClassNotFoundException | SQLException e) {
        }

        return dbConnection;
    }

    // 關閉連線
    public static void closeConnection(Connection dbConnection) {
        try {
            if (dbConnection != null && (!dbConnection.isClosed())) {
                dbConnection.close();
            }
        } catch (SQLException sqlEx) {
        }

    }

    // 關閉結果集
    public static void closeResultSet(ResultSet res) {
        try {
            if (res != null) {
                res.close();
                res = null;
            }
        } catch (SQLException e) {
        }
    }

    public static void closeStatement(PreparedStatement pStatement) {
        try {
            if (pStatement != null) {
                pStatement.close();
                pStatement = null;
            }
        } catch (SQLException e) {
        }
    }
}

3.2.3 編寫LoinServlet.java

package exp05.bean;

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

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

public class LoginServlet extends HttpServlet {

    public LoginServlet() {
        super();
    }

    @Override
    public void destroy() {
        super.destroy();
    }

    @Override
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
        request.setCharacterEncoding("UTF-8");
        String userName = request.getParameter("loginName");//
        String passWord = request.getParameter("passWord");//
        String sql = "select * from user";  //
        sql += " where loginname='" + userName + "' and password='" + passWord + "'";
        HttpSession session = request.getSession();
        Connection con = DBConn.getConnction();
        Statement stmt;
        ResultSet rs;
        try {
            stmt = con.createStatement();
            rs = stmt.executeQuery(sql);
            if (rs.next()) //
            {
                session.setAttribute("userName", userName); //
                response.sendRedirect("jsp/exp05/content02/welcome.jsp");
            } else {
                response.sendRedirect("jsp/exp05/content02/loginFail.jsp");//
            }
        } catch (SQLException e) {
        }
    }

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

    @Override
    public void init() throws ServletException {
    }
}

3.2.4 編寫login.html

<!DOCTYPE html>
<html>
    <head>
        <title>login.html</title>
        <meta http-equiv="content-type" content="text/html;charset=UTF-8">
    </head>
    <body>
        <table align="center">
            <tr><td align="center"><p>
                    <font color="red" size="3"  style="font-family:simhei">請登入</font><p>
                    <form method="post" action="../../../LoginServlet" target="_blank"><p>