---
# System prepended metadata

title: 7號筆記本
tags: [筆記本]

---

# 7號筆記本
###### tags: `筆記本`
```YY5GFs93iZY9FXNK2k2nMHzso9ZpuBsUMqg227fTpUc=
String userid = req.getParameter("userid");    //取得html user欄位值
req.setAttribute("userid", userid);            //將值存入Attribute
req.getRequestDispatcher("/AccountServlet").forward(req, res);     //導向AccountServlet.java
req.getRequestDispatcher("/login.html").forward(req, res);         //導向login.html
String[] records = (String[]) data.get(userid);                    //取得init內容值
```
```
public void init()
	{
		data.put("ann", new String[]{ "01/01/2001 : 1000.00", "01/02/2001 : 1300.00", "01/03/2001 : 900.00"} );				
		data.put("john", new String[]{ "01/01/2001 : 4500.00", "01/02/2001 : 2100.00", "01/03/2001 : 2600.00"} );
		data.put("mark", new String[]{ "01/01/2001 : 7800.00", "01/02/2001 : 5200.00", "01/03/2001 : 1900.00"} );
	}
```

# servlet筆記 取xml(context-param值)         (AccountServlet.java LoginServlet.java Login.html)
```
ServletContext context = this.getServletContext();
String webmaster = context.getInitParameter("webmaster");     //去xml裡取context-parm的value
```

```
<context-param>
    <param-name>webmaster</param-name>
    <param-value>webmaster@abc.org.tw</param-value>
  </context-param>
 ```
 # servlet筆記 取xml(init-parm值)並透過相對路徑取得絕對入境  (CounterServlet.java)
(init部分)
```
ServletConfig config = this.getServletConfig();   
String relativePathName = null;    
String realPathName = null;   
BufferedReader bufferedReader = null;
relativePathName = config.getInitParameter("VisitingCounterNoFileName");    /*去xml裡取init-parm的value*/
InputStream inStream = context.getResourceAsStream(relativePathName);
bufferedReader = new BufferedReader(new InputStreamReader(inStream));
realPathName = context.getRealPath(relativePathName);	                    /*利用相對路徑得到真實路徑*/

(doget部分)
synchronized (context) {                                                                             //執行緒
	      localVisitingCounterNo = (String) context.getAttribute("visitingCounterNo"); 
	      localVisitingCounterNo = String.valueOf((Integer.parseInt(localVisitingCounterNo)+1));
	      context.setAttribute("visitingCounterNo",localVisitingCounterNo);
	    } 

(destroy部分)
          fileWriter = new FileWriter(realPathName);                                              //更改記事本內容
	      bufferedWriter = new BufferedWriter(fileWriter);
	      printWriter = new PrintWriter(bufferedWriter);
	      String visitingCounterNo = (String) context.getAttribute("visitingCounterNo");
	      printWriter.println(visitingCounterNo);
```

```
<init-param>
      <description></description>
      <param-name>VisitingCounterNoFileName</param-name>
      <param-value>/WEB-INF/VisitingCounterNoFileName.txt</param-value>
    </init-param>
    
```
 # servlet筆記 (DeclarativeErrorHandlingServlet.java)
 ``` 

  ```
# servlet筆記 Header範例
```
response.setStatus(HttpServletResponse.SC_OK);    //SC_OK=200 servlet回應200狀態碼
String tempSite ="http://127.0.0.1:8080/example/helloB";    //存放新的url位址
response.setHeader("location", tempSite);                   //第一個是header名稱，第二個是變數名稱

# servlet筆記 導向網站
response.sendRedirect("http://127.0.0.1:8080/example/helloB");

# servlet筆記
http://localhost:8080/WebDemo/EnglishGreeting    //對應xml <url-pattern>/EnglishGreeting</url-pattern>
```

```
 <servlet>
    <description></description>
    <display-name>EnglishGreeting</display-name>
    <servlet-name>EnglishGreeting23</servlet-name>
    <servlet-class>GreetingServlet</servlet-class>
    <init-param>
      <param-name>greetingText</param-name>        
      <param-value>Hello</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>EnglishGreeting23</servlet-name>
    <url-pattern>/EnglishGreeting</url-pattern>
  </servlet-mapping>
```
# servlet筆記 session
```
HttpSession session = req.getSession(true);          //Get the session object
session.isNew()                                      //是否是新的session
session.getId()                                      //session id
new Date(session.getCreationTime())                  //產生時間
new Date(session.getLastAccessedTime())              //最後存取時間
session.getAttribute("counter")                      //次數
session.invalidate();                                //關閉session
```


```
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql" %>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
 
<sql:setDataSource var="ds" dataSource="jdbc/EmployeeDB" />
<sql:query sql="select * from member" var="rs" dataSource="${ds}" /> 

<!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=UTF-8">
<title>Test Database Connection Pooling</title>
</head>
<body>
 <h2>Results</h2>
  <table border="1" >
    <th>author</th>
    <th>title</th> 
    <c:forEach var="row" items="${rs.rows}">
    <tr>
    <td>${row.userid}</td>
    <td>${row.password}</td>
    </tr>
    </c:forEach>
  </table>
</body>
</html>
```
<!DOCTYPE html>
<html>
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>02DOM2.html</title>
    <script>
        document.addEventListener("DOMContentLoaded", function () {
            document.getElementById("CEle").addEventListener("click", CreateElement)
            document.querySelector("#REle").addEventListener("click",RempveElement)
        });

        function RempveElement() {
            let theNode=document.querySelector("#idImg")
            console.log(theNode)
            // theNode.parentNode.removeChild(theNode)
            theNode.remove();
        }

        function CreateElement() {
            let theDIV = document.getElementById("iddiv");  //取得div物件

            let eleP = document.createElement("p"); //<p></p>
            let txtP = document.createTextNode("Hello World"); //Hello World
            eleP.appendChild(txtP); // <p>Hello World</p>

            theDIV.appendChild(eleP);//<div id="iddiv">div<p>Hello World</p></div>

            let eleImg = document.createElement("img"); //<img>
            eleImg.setAttribute("src", "DOM/DOMImage/rabbit-hat.gif"); //<img src="...">
            eleImg.setAttribute("id","idImg")
            theDIV.appendChild(eleImg);//<div id="iddiv">div<p>Hello World</p><img src="..."></div>
        }
    </script>
</head>

<body>
    <div id="iddiv">div</div>
    <input type="button" id="CEle" value="CreateElement">
    <input type="button" id="REle" value="RempveElement">

</body>
</html>

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
       	 	HttpSession session = request.getSession();
       	 	MemberBean logoutmb = (MemberBean) session.getAttribute("loginuser");  
       	 	logoutmb.setLogout_time(sdf.format(new Date(session.getLastAccessedTime())));
       	 	MemberDao.InsertLogoutTime(logoutmb);

String sql="" +
					"insert into member" +
					"(userid,password,chinesename,sex,phone,email,address,birthday)" +
					"values(" +
					"?,?,?,?,?,?,?,?)";
                    
re=/^((((19|20)(([02468][048])|([13579][26]))(\/02\/29|\/2\/29)))|((20[0-9][0-9])|(19[0-9][0-9]))\/(((|(0[1-9])|([1-9])|(1[0-2]))\/(([1-9])|(0[1-9])|(1[0-9])|(2[0-8])))|((((0[13578])|(1[02]))\/31)|(((0[1,3-9])|([1])|([3-9])|(1[0-2]))\/(29|30)))))$/;


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    
    <form action="/somewhere/to/upload" enctype="multipart/form-data">

        <input name="progressbarTW_img" type="file" id="imgInp" accept="image/gif, image/jpeg, image/png"/ >
     
        <img id="preview_progressbarTW_img" src="#" style="width: 50px;height: 50px;"/>
     
     </form>
     <script src="../JQUERY/jquery-3.5.1.js"></script>
     <script>
         $("#imgInp").change(function(){
      //當檔案改變後，做一些事 
     readURL(this);   // this代表<input id="imgInp">
   });


    function readURL(input){
        if(input.files && input.files[0]){
        var reader = new FileReader();
        reader.onload = function (e) {
        $("#preview_progressbarTW_img").attr('src', e.target.result);
        console.log(e.target.result)
        }
        
        reader.readAsDataURL(input.files[0]);
    }
    }
     </script>
</body>
</html
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
sp.innerHTML="<i class=\"fa fa-times\" style=\"color: red;\"></i>
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
re = /^(?=.*[A-Za-z])(?=.*\d)(?=.*[@$!%*#?&])[A-Za-z\d@$!%*#?&]{6,}$/;
re = /^([\u4e00-\u9fa5]){2,}$/;






<c:set var = "empId" value = "<%=loginuser.getUserid()%>"/>
<sql:query  var="rs" dataSource="${ds}" >
	select * from logininf where userid = ? order by logintime;
	<sql:param value = "${empId}"/>
</sql:query> 





<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
 <% 
response.setContentType("text/html;charset=UTF-8");
response.setHeader("Cache-Control","no-cache"); // HTTP 1.1
response.setHeader("Pragma","no-cache"); // HTTP 1.0
response.setDateHeader ("Expires", -1); // Prevents caching at the proxy server
%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>新增</title>
<style>
        body {
            background-color: #F0F0F0;
        }
        h2{
	   		text-align: center;
	   		color:	#003D79;
	   	}
        fieldset{
        	background-color: 	#FFFFFF;
            width: 450px;
            border:1px solid #ADADAD;
            border-radius: 15px;
            margin: 0px auto;
            padding:0 50px ;
        }

        .divst {
            width: 450px;
            border-bottom: 1px dotted #ADADAD;
            margin: 10px;
            padding-bottom: 5px;
        }
        legend {
  			margin:auto; 
        }
        .sub {
            width: 450px;
            margin: 10px;
            text-align: center;
        }
        .st1 {
            width: 70px;
            float: left;
            text-align: left;
        }

    </style>
    <script type="text/javascript">
            document.addEventListener("DOMContentLoaded", function () {
            document.getElementById("name").addEventListener("blur", check1); //事件繫結，焦點離開
            document.getElementById("address").addEventListener("blur", check2); //事件繫結，焦點離開
            document.getElementById("image").addEventListener("blur", check3); //事件繫結，焦點離開
            document.getElementById("introduction").addEventListener("blur", check4); //事件繫結，焦點離開
        });

            function check1() {
            	let nameObjVal = document.getElementById("name").value;
                let sp_name = document.getElementById("sp_name");
                if (nameObjVal == "")
                	sp_name.innerHTML = "不可為空白";
            }
            function check2() {    	
            	let addressObjVal = document.getElementById("address").value;
                let sp_name = document.getElementById("sp_name");
                if (addressObjVal == "")
                	sp_address.innerHTML = "不可為空白";
            }
            function check3() {	
                let imageObjVal = document.getElementById("image").value;
                let sp_image = document.getElementById("sp_image");
                if (imageObjVal == "")
                	sp_image.innerHTML = "不可為空白";
            }
            function check4() {
                let introductionObjVal = document.getElementById("introduction").value;
                let sp_introduction = document.getElementById("sp_introduction");
                if (introductionObjVal == "")
                	sp_introduction.innerHTML = "不可為空白";
            }
    </script>
    
    
</head>
<body>
 <form action="AttrationsServlet?action=up" method="post" enctype = "multipart/form-data">
		 <div>
		 		<h2>請輸入景點資料</h2>
		 </div>
        <fieldset>
            <legend>新增內容</legend>
             <div class="divst">
                <label for="name" class="st1">景點名稱:</label>
                <input type="text" id="name" name="name" size="20"> 
                <span id="sp_name"></span><br/>
            </div>
            <div class="divst">
              	<label class="st1">縣市:</label>
	             <select name="counties">
		           <option value="台北市">台北市</option>
		           <option value="新北市">新北市</option>
		           <option value="桃園縣">桃園縣</option>
		           <option value="新竹市">新竹市</option>
		           <option value="苗栗縣">苗栗縣</option>
		           <option value="臺中市">臺中市</option>
		           <option value="彰化縣">彰化縣</option>
		           <option value="南投縣">南投縣</option>
		           <option value="雲林縣">雲林縣</option>
		           <option value="嘉義縣">嘉義縣</option>
		           <option value="臺南市">臺南市</option>
		           <option value="高雄市">高雄市</option>
		           <option value="屏東縣">屏東縣</option>
		           <option value="宜蘭縣">宜蘭縣</option>
		           <option value="花蓮縣">花蓮縣</option>
		           <option value="臺東縣">臺東縣</option>
		           <option value="澎湖縣">澎湖縣</option>
		           <option value="金門縣">金門縣</option>
		           <option value="連江縣">連江縣</option>
	        	</select>
            </div>
            <div class="divst">
                <label class="st1" for="address">完整地址:</label>
                <input type="text" id="address"  name="address" size="40">
                <span id="sp_address"></span><br/>
            </div>
             <div class="divst">
             	<input type='hidden' name='image1' id='image1' >
                <label class="st1" for="image">照片:</label>
                <input type="file" id="image"  name="image"  accept="image/gif, image/jpeg, image/png">
                <span id="sp_image"></span><br/>
            </div>
            <div class="divst">
                <label for="introduction" class="st1">介紹:</label>
                <input type="text" id="introduction" name="introduction" placeholder="250字以內" size="40">
            	<span id="sp_introduction"></span><br/>
            </div>
            <div class="sub">
            <br>
                <input type="submit" name="submit" value="送出">
                <input type="reset" value="清除輸入">
            </div>
        </fieldset>
    </form>
</body>
<script src="https://code.jquery.com/jquery-3.1.0.min.js"></script>
<script type="text/javascript">
	$("#image").change(function(){
    	//當檔案改變後，做一些事 
   		readURL(this);   // this代表<input id="imgInp">
 	});


  	function readURL(input){
      if(input.files && input.files[0]){
      var reader = new FileReader();
      reader.onload = function (e) {
      	console.log(e.target.result)
      	let a=document.querySelector('#image1')
      	a.value=e.target.result;
      }
      
      reader.readAsDataURL(input.files[0]);
  	}
  	}
  	
  	$('input[type=file]').each(function()
  			{
  			var max_size=102400;
  			$(this).change(function(evt)
  			{
  			var finput = $(this);
  			var files = evt.target.files; // 獲得檔案物件
  			var output = [];
  			for (var i = 0, f; f = files[i]; i++)
  			{//檢查檔案大小
  			if(f.size > max_size)
  			{
  			alert("上傳的圖片不能超過100KB!");
  			window.location.reload();
  			$(this).val('');
  			}
  			}
  			});
  			});
</script>
</html>