1. 程式人生 > 實用技巧 >小白之路 | 從小學一年級期末考試看servlet+jsp技術

小白之路 | 從小學一年級期末考試看servlet+jsp技術

先上介面

  (前端可以使用css、js等庫進行美化,相關章節可以參見前面關於css、js的總結。當然,“技術不是最重要的,最重要的想法、創意瞎扯,都重要!其實藝術和技術的結合,是一件挺有意思的事情)

  1. 本地tomcat上部署後,訪問連結:http://localhost:9001/BS/

成績單:

原始碼:

index.jsp:

<%@page contentType="text/html;charset=GBK"%>
<html>
<head>
<title>小學一年級數學期末考試</title>
</head>
<
style> #all{ width: 800px; height: 450px; border: 1px solid green; position:absolute; top:50%; left:50%; margin:-225px 0 0 -400px; } </style> <% int errorTag=0;////errorTag!=0是因為使用者非法輸入,非法輸入不更新題目 if(session.getAttribute("errorTagInput")!=null){ errorTag
= (int)session.getAttribute("errorTagInput"); session.setAttribute("errorTagInput", null);// 重新監聽非法輸入 } if(errorTag == 0){// 正常輸入 int a = (int)(Math.random() * 1000) + 1; int b = (int)(Math.random() * 1000) + 1; session.setAttribute(
"a", a); session.setAttribute("b", b); } %> <!-- 顯示正確/錯誤的提示資訊 --> <jsp:useBean id="ci" scope="session" class="exec.CInfo"> <jsp:setProperty name="ci" property="info" value="****" /> </jsp:useBean> <body> <div id="all" style="border:1px #cccccc solid; width:50%; height:80%px; text-align:center;"> <br> <h1>小學一年級期末考試</h1> <h2>計時開始...</h2> <br> <b>Please Answer:</b><br> <%= session.getAttribute("a") %> + <%= session.getAttribute("b") %>= <br><br> <b>The last time to answer:</b> <p style="color:red"><jsp:getProperty name="ci" property="info" /><p> <br> <!-- 輸入猜數的表單介面 --> <form method="POST" action="Action"> <b>Answer:<input type="text" name="guessNumber" size="20"></b> <input type="submit" value="SUBMIT" name="B1"> </form> <form method="POST" action="Action"> <input type="submit" value="QUIT" name="B1"> </form> </div> </body> </html>

success.js:

<%@page contentType="text/html;charset=GBK"%>
<html>
<head>
<title>數學期末成績</title>
</head>
<pre>
<%
        if(session.getAttribute("true_total")!=null && session.getAttribute("total")!=null){
            int true_total = (int)session.getAttribute("true_total");
            int total = (int)session.getAttribute("total");
            out.println("正確數:" + true_total);
            out.println("答題數:" + total);
            out.println("正確率:" + String.format("%.2f",true_total*100.0/total)+"%");          
        }else{
            out.println("請不要交白卷!");
        }
        session.invalidate();                 
%>
</pre>

<body>
<p><a href='index.jsp'>是否對成績還不滿意?點選重考!</a>
</body>
</html>

Action.java:

import java.io.IOException;
import java.io.PrintWriter;

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

//判斷題目是否正確的Servlet類,並做相應的處理
public class Action extends javax.servlet.http.HttpServlet implements
        javax.servlet.Servlet {

    // 建構函式
    public Action() {
        super();
    }

    // 記錄題目數
    int total = 0;
    int true_total = 0;
    // 處理GET請求
    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        // 設定傳送到客戶端的內容型別
        response.setContentType("text/html;charset=GB2312");
        
        //判斷點選的是哪個按鈕
        String btn = request.getParameter("B1");
        if(btn.equals("QUIT")) {//如果是退出按鈕,直接返回了,不用執行下面else裡面的程式碼了
            total = 0;
            true_total = 0;
            RequestDispatcher dispatcher = request
                    .getRequestDispatcher("success.jsp");
            dispatcher.forward(request, response);
        }else {
        
        // 獲取客戶端寫入器
        PrintWriter out = response.getWriter();
        // 獲取客戶端請求資訊中的guessNumber屬性值
        String s1 = request.getParameter("guessNumber");
//        System.out.println(s1);
        // 獲取當前會話
        HttpSession session = request.getSession(true);
        session.setAttribute("total", ++total);
        session.setAttribute("true_total", true_total);//為了防止全答錯的情況
        
        // 獲取會話資訊中的ci屬性
        exec.CInfo ci = (exec.CInfo) session.getAttribute("ci");
        int num1=0;    
        int a = (int) session.getAttribute("a");
        int b = (int) session.getAttribute("b");
        System.out.println(a+"+"+b);
                
        // 得到輸入的內容
        if(isNumeric(s1)) {
            num1 = Integer.parseInt(s1);
        }else {
            session.setAttribute("errorTagInput", 1);
            ci.setInfo("Input error, please retype******\n"+a+"+"+b+"=");
            RequestDispatcher dispatcher = request
                    .getRequestDispatcher("index.jsp");
            dispatcher.forward(request, response);
        }
        
        // 如果猜數與系統生成的初始隨機數相等
        if (num1 == a+b) {
            // 跳轉到成功頁面
            session.setAttribute("true_total", ++true_total);
            ci.setInfo(a+"+"+b+"="+num1+"******"+"True");
            RequestDispatcher dispatcher = request
                    .getRequestDispatcher("index.jsp");
            dispatcher.forward(request, response);
            // 結束當前會話
//            session.invalidate();
        }
        
        else {
            // 設定顯示的提示資訊
            ci.setInfo(a+"+"+b+"="+num1+"******"+"False"+"******The correct result:"+(a+b));
            // 跳轉到主頁面頁面
            RequestDispatcher dispatcher = request
                    .getRequestDispatcher("index.jsp");
            dispatcher.forward(request, response);
            // 結束當前會話
//            session.invalidate();
        }
    }}

    // 處理POST請求,執行和處理GET請求一樣的方法
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
    
    // 判斷傳入的值是否為數字型別
    public static boolean isNumeric(final String str) {
        // null or empty
        if (str == null || str.length() == 0) {
            return false;
        }

        try {
            Integer.parseInt(str);
            return true;
        } catch (NumberFormatException e) {
            try {
                Double.parseDouble(str);
                return true;
            } catch (NumberFormatException ex) {
                try {
                    Float.parseFloat(str);
                    return true;
                } catch (NumberFormatException exx) {
                    return false;
                }
            }
        }
    }
}

CInfo.java:(這個類其實沒有必要做,直接返回一個字串到session中即可,但這是一個時代留下來的經典用法,簡單熟悉一下,算是回顧吧)

package exec;

//提示資訊類
public class CInfo {
    // 提示資訊
    private String info;

    // 提示資訊的設定函式
    public void setInfo(String str) {
        info = str;
    }

    // 提示資訊的讀取函式
    public String getInfo() {
        return info;
    }
}

-----------servlet+jsp end ---------

連結https://github.com/tangdiao/Explore/

  相關的基礎和高深的知識,其他部落格已有更新,這裡不再贅述。其實servlet+jsp很可愛,加上資料庫訪問層,對於一般的web應用完全沒問題。從實際專案開發中,我發現,一個應用要真正的落地,構建應用階段其實問題不大,不斷地update就行了。重在後面維護和運營等一系列事情,這裡涉及到一個軟體的整個生命週期的問題。我是正在探索中的小白,一起加油吧。