---
# System prepended metadata

title: JSP

---

# *JSP*
:::info
 :+1: 每個JSP檔案前都要加此行，否則中文亂碼。
```java=
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" import="java.io.*"%>
```
 :+1: 接收表單的JSP需加這行，否則中文亂碼。
```java=
request.setCharacterEncoding("UTF-8");
```
:::

## <font color="magenta ">Cookie</font>
### 創建Cookie:+1: 

```java=
//創建cookie物件
Cookie cookie = new Cookie(key, value);
//設定存活時間
cookie.setMaxAge(3600);
//設置cookie
response.addCookie(cookie);

```


### 讀取Cookie:+1: 
#### **讀取**
```java=
//讀取鍵
cookie.getName();
//讀取值
cookie.getValue();
```
#### **獲取方法**
```java=
//(重要)一定要先獲取所有cookie，才能做後續動作!!
Cookie[] cookies = request.getCookies();
```
#### **印出Cookie(全部找)**
```java=
if(cookies != null){
    for(Cookie cookie: cookies){
      //找尋想要的
      if(cookie.getName().equals("name")){
          String name = cookie.getValue();
          //修改值
          cookie.setValue("newValue");
          response.addCookie(cookie);
      }
      //單純印出
	  String name = cookie.getName();
   	  String value = cookie.getValue();
	}
}
```
### 刪除
```java!
//直接把時間設為零
cookie.setMaxAge(0);
response.addCookie(cookie);
```
## <font color="magenta ">表單</font>
### 取得表單值
```java=
request.setCharacterEncoding("UTF-8");
String name = request.getParameter("name");
```

## <font color="magenta ">Session</font>
### 創建Session物件(不用創，系統幫你創好了)
```java!
//系統預設Session的變數名稱為session，還想創新的要自己新建名字
HttpSession session_2 = request.getSession();
```
### 存資料(修改、刪除)
```java=
//修改
session.setAttribute(key, value);
//刪除
session.setAttribute(key, null);
//所有session刪除
session.invalidate();
```
### 讀取資料
```java!
String username = (String) session.getAttribute("username");
```

### 查找全部Session
```java!
java.util.Enumeration<String> names = session.getAttributeNames();
        while (names.hasMoreElements()) {
          String key = names.nextElement();
          Object value = session.getAttribute(key);
          out.println("key: " + key + " ..value: " + value + "<br>");
        }
```

## <font color="magenta ">讀取.bat檔案</font>
### 取得檔案位置
```java=
    //這是bat檔案與jsp放在一起的情況，請把現實存放JSP檔案資料夾替換進"JSP/"
    String fileName = "JSP/score_UTF8_2.dat";
    String filePath = application.getRealPath("/") + fileName;
```
### 讀取檔案(UTF-8)
```java=
    request.setCharacterEncoding("UTF-8");
    //表單傳值
    String userId = request.getParameter("userId");
    String password = request.getParameter("password");
    try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"))){
        String line;
        //讀取每一行，以作業當範例。
        while((line = br.readLine()) != null){
            //將每一行值取出來(以空格作為取代)，存進value中
            String[] values = line.split(" ");
            //將value中的值放進對應的變數中。
            String id = values[0];
            String passwordD = values[1];
            String name = values[2];
            int scoreA = Integer.parseInt(values[3]);
            int scoreB = Integer.parseInt(values[4]);
            int scoreC = Integer.parseInt(values[5]);  
            //帳號密碼比對，以實際應用做調整。
            if( userId.equals(id) && password.equals(passwordD)){
                out.println("成功登入! 你好: " + name);
                break;
            }
        }
        br.close();
    }catch(Exception e){
        out.println("錯誤: " + e.getMessage());
    }
```

## <font color="magenta ">寫入.bat檔案</font>
```java=
<%@ page language="java" contentType="text/html; charset=utf-8" pageEncoding="utf-8" import="java.io.*"%>
<%
String fileName = "TEST/p5_input_UTF8.dat";
String filePath = application.getRealPath("/") + fileName;

//新增檔案(testIn3)
String writefile = application.getRealPath("/") + "TEST/testIn3.dat";

FileWriter fw = new FileWriter(writefile);

try(BufferedReader br = new BufferedReader(new InputStreamReader(new FileInputStream(filePath), "UTF-8"))){
    String line;
    //讀取每一行，以作業當範例。
    while((line = br.readLine()) != null){
        //將每一行值取出來(以空格作為取代)，存進value中
        String[] values = line.split(" ");
        String a = values[0];
        String b = values[1];
        String c = values[2];
        String d = values[3];
        out.println(a+b+c+d+"<br>");
       String text = a+b+c+d+"\n";
        //寫入
       fw.write(text);
    }
    //必須關
    fw.close();
    br.close();
}catch(Exception e){
    out.println("錯誤: " + e.getMessage());
}
%>

```

## <font color="magenta ">重新導向</font>
```java=
response.sendRedirect("hehehe"); 
```

## ACCESS
### 驅動
[下載UCANACCESS](https://sourceforge.net/projects/ucanaccess/files/)
將**lib內所有文件**與**最外層ucanaccess.jar**，共計五個檔案放入**tomcat/lib**，放完記得重開server
![圖片](https://hackmd.io/_uploads/HJ7CDrxOT.png)

### 連接
```java=
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.io.*"%>
<%@ page import="net.ucanaccess.jdbc.*" %>
<%@ page import="java.sql.*" %>
<%@ page import="java.util.*" %>
Class.forName("net.ucanaccess.jdbc.UcanaccessDriver");

Connection conn = null;
PreparedStatement preparedStatement = null;
//請將access實際路徑更新
String url = "jdbc:ucanaccess://C:/xampp/tomcat/webapps/ROOT/work/database_crud/customer.accdb";
conn = DriverManager.getConnection(url);
Statement stmt = conn.createStatement();
```
### 查詢(prepare)
```java=
//prepare，將資料塞入sql中
String sql = "SELECT * FROM BASIC WHERE CUST_NO = ?";
preparedStatement  = conn.prepareStatement(sql);
//注意 如果不是要塞string不可用setString
preparedStatement.setString(1, customer_num);
//執行查詢
resultSet = preparedStatement.executeQuery();
//將查詢之結果取出
while(resultSet.next()){
    String cust_no = resultSet("cust_no");
}
```
### 創建(prepare)
```java=
//先查詢有無資料
String sql = "SELECT * FROM BASIC WHERE CUST_NO = ?";
preparedStatement = conn.prepareStatement(seSql);
preparedStatement.setString(1, cust_no);
resultSet = preparedStatement.executeQuery();
//如果沒有資料才創建
if(resultSet.isBeforeFirst()){
    String crSql = "INSERT INTO BASIC(CUST_NO, NAME, ID, ADDRESS, TEL_NO) VALUES(?, ?, ?, ?, ?)";
preparedStatement  = conn.prepareStatement(crSql);
preparedStatement.setString(1, cust_no);
preparedStatement.setString(2, name);
preparedStatement.setString(3, id);
preparedStatement.setString(4, address);
preparedStatement.setString(5, tel_no);
int rowsAffected = preparedStatement.executeUpdate();
if(rowsAffected >= 1){
    out.println("新增成功!");
}else{
    out.println("新增失敗!");
}
}
```
### 更新(先查詢有無)
```java=
//同創建 先查詢有無(PASS)
//prepare一下
String sql = "UPDATE BASIC SET NAME = ?, ID = ?, ADDRESS = ?, TEL_NO = ? WHERE CUST_NO = cust_no";
preparedStatement  = conn.prepareStatement(sql);
preparedStatement.setString(1, name);
preparedStatement.setString(2, id);
preparedStatement.setString(3, address);
preparedStatement.setString(4, tel_no);
int rowsAffected = preparedStatement.executeUpdate();
if(rowsAffected > 0){
    out.println("有更新!");
}else{
    out.println("沒有更新!");
}
```
### 刪除(先查詢有無)
```java=
//先查詢有沒有再刪除
String sql = "DELETE FROM BASIC WHERE CUST_NO = ?";
preparedStatement  = conn.prepareStatement(sql);
preparedStatement.setString(1, customer_num);
int rowsAffected = preparedStatement.executeUpdate();
if(rowsAffected > 0){
  out.println("有刪除");  
}else{
    out.println("沒刪除!");
}
```

## AJAX
> 將**A網頁**本需處理的內容交由**B網頁**處理，**B網頁**再傳回結果。
### A網頁端(.html)
[A網頁程式碼(含html)](https://drive.google.com/file/d/1LfnmO5VbDKXgF4oN0tvf17QmbrgfsU07/view?usp=sharing)
```javascript=
function ajaxLogin(){
            //將表單原本的送出功能阻擋，因表單送出後會重整網頁
            event.preventDefault();
            //放B網頁回傳訊息的地方
            let response = document.getElementById("response");
            //取得使用者輸入之帳號
            let account = document.getElementById("floatingInput");
            //取得使用者輸入之密碼
            let passwd = document.getElementById("floatingPassword");
            //A網頁要傳送給B網頁處理的資料，將以網址(get)私下傳送給B網頁，ex: account=M12345678&passwd=0000000a
            let params = "account=" + account.value + "&passwd=" + passwd.value;
            
            //建立xmlhttp物件，將開啟一個 URL，並發起一個請求
            var xmlhttp;
            //如果瀏覽器支援就創立XMLHttpRequest，否則就用舊標準ActiveXObject
            if(window.XMLHttpRequest){
                xmlhttp = new XMLHttpRequest();
            }else{
                xmlhttp = new ActiveXObject("Microsoft.XMLHTTP");
            }
            
            //給他一個callback，等待回傳，onreadystatechange為如果xmlhttp有變化就觸發
            xmlhttp.onreadystatechange = function(){
                //如果readyState=4(數據接收完成)&status=200(請求成功)
                if(this.readyState == 4 && this.status == 200){
                    //接收B網頁傳回之資料放進變數
                    let responsetext = this.responseText;
                    //將回傳之資料放進A網頁中(變數response)
                    response.innerHTML = responsetext;
                }
            };
            //設定xmlhttp為post，送往ajax.jsp，且請求為"非同步"
            xmlhttp.open("POST", "ajax.jsp", true);
            //設定請求標頭
            xmlhttp.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
    //發送實際請求，將變數param(數據)發送到B網頁
            xmlhttp.send(params);
        }
```
### B網頁端(.jsp)
```java=
<%@ page contentType="text/html; charset=UTF-8"
import="java.util.*, java.text.*"%>
 <%request.setCharacterEncoding("UTF-8");%>
 <%  
    String acc1 = "9923701";
    String acc2 = "9923702";
    String pwd1 = "1073299";
    String pwd2 = "2073299";
    //接收A網頁傳來之account
    String strName = request.getParameter("account");
    //接收A網頁傳來之password
    String strPasswd = request.getParameter("passwd");
    if((strName.equals(acc1) && strPasswd.equals(pwd1)) || (strName.equals(acc2) && strPasswd.equals(pwd2))){
        String ss = "<div id=\"response\" class=\"alert alert-success\" role=\"alert\"><h4 class=\"alert-heading\">成功登入</h4><p>成功登入</p><hr><p class=\"mb-0\">成功登入</p></div>";
        out.println(ss);
    }else if((strName.equals(acc1) && !strPasswd.equals(pwd1)) || (strName.equals(acc2) && !strPasswd.equals(pwd2))){
        String ss = "<div id=\"response\" class=\"alert alert-danger\" role=\"alert\"><h4 class=\"alert-heading\">密碼錯誤</h4><p>密碼錯誤</p><hr><p class=\"mb-0\">密碼錯誤</p></div>";
        out.println(ss);
    }else if(!strName.equals(acc1) || !strName.equals(acc2)){
        String ss = "<div id=\"response\" class=\"alert alert-danger\" role=\"alert\"><h4 class=\"alert-heading\">帳號錯誤</h4><p>帳號錯誤</p><hr><p class=\"mb-0\">帳號錯誤</p></div>";
        out.println(ss);
    }


 %>
```
## BOOTSTRAP
```htmlembedded=
<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>Bootstrap demo</title>
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous">
  </head>
  <body>
    <h1>Hello, world!</h1>
    <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script>
  </body>
</html>
```