1. 程式人生 > >操作許可權的控制

操作許可權的控制

上傳檔案往往都必須登陸後才可以進行操作,以前我們已經講過上傳,註冊登陸但是並沒有將它們聯絡在一起,今天主要就是設定許可權只有登陸成功後才可以上傳檔案。

1、原本的介面如圖所示:不用登陸便可以上傳


2、給它加上條件

<c:choose>
  	 <c:when test="${empty sessionScope.user_name }">
	  	<form action="${pageContext.request.contextPath}/tishi.jsp" enctype="multipart/form-data" method="post">
	        <input id="submit" type="submit" value="提交" >
	  </form>
	 </c:when>
	  <c:otherwise>
	 	<form action="${pageContext.request.contextPath}/uploadservlet" enctype="multipart/form-data" method="post">
	        <input id="submit" type="submit" value="提交" >
	  </form>
	 </c:otherwise> 
  </c:choose>

當登入成功了才可以進行操作,否則,會跳轉到提示登陸的介面

這裡需要注意的是sessionScope.user_name對應的是login的servlet裡放到內建物件的變數名

3、因為jsp使用<c:choose>標籤來控制內容顯示,所以,引用

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>

 故必須新增jstl.jar和standard.jar兩個架包

4、jsp完整的程式碼及截圖如下所示

(1)目錄結構:


(2)login.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
   <form action="${pageContext.request.contextPath}/LoginServlet" method="post" class="" role="form">
   username<input type="username" name="username" class="" id="username" placeholder="請輸入使用者名稱...">
   password<input type="password" name="password" class="" id="password" placeholder="請輸入密碼...">
   <span style="color:red">${msg }</span> 
   <input type="submit">
   </form>
   <a href="upload.jsp">現在去上傳檔案</a>
</body>
</html>

(3)upload.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!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>Insert title here</title>
</head>
<body>
  <c:choose>
  	 <c:when test="${empty sessionScope.user_name }">
<form action="${pageContext.request.contextPath}/tishi.jsp" enctype="multipart/form-data" method="post"> 上傳使用者:<input type="text" name="username" >${name } <br/> <br/> 上傳檔案1:<input type="file" name="file1"><br/><br/> 上傳檔案2:<input type="file" name="file2"><br/><br/> 上傳檔案3:<input type="file" name="file3"><br/><br/> 上傳檔案4:<input type="file" name="file4"><br/><br/> 上傳檔案5:<input type="file" name="file5"><br/><br/> <input id="submit" type="submit" value="提交" > </form> </c:when> <c:otherwise> <form action="${pageContext.request.contextPath}/uploadservlet" enctype="multipart/form-data" method="post"> 上傳使用者:<input type="text" name="username" >${name } <br/> <br/> 上傳檔案1:<input type="file" name="file1"><br/><br/> 上傳檔案2:<input type="file" name="file2"><br/><br/> 上傳檔案3:<input type="file" name="file3"><br/><br/> 上傳檔案4:<input type="file" name="file4"><br/><br/> 上傳檔案5:<input type="file" name="file5"><br/><br/> <input id="submit" type="submit" value="提交" > </form> </c:otherwise> </c:choose> </body> </html>

注意:藍色字型部分對應的是login的serverlet類中的藍色字型部分。

          因為用的choose標籤,故必須加入引用語句:即紅色字型部分。

(4)其他的為各類提示介面,這裡就不做詳細的講解了。

message.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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>Insert title here</title>
</head>
<body>
  ${msg}
</body>
</html>

注意:${msg}獲取內建物件名為msg的變數的值,對應servlet類中的紫色字型部分

tishi.jsp

<%@ page language="java" pageEncoding="UTF-8"%>
<!DOCTYPE HTML>
<html>
  <head>
    <title>訊息提示</title>
     <link rel="stylesheet" type="text/css" href="css/help.css"/>
      <script type="text/javascript">
         window.onload=function(){
            function addzero(num){
                if(num>=10)
                { return ""+num;
                }
                else
                {return "0"+num;
                }
            }
            function times(){
                var date=new Date();
                var aTime=document.getElementById('aTime');
                var str= addzero(date.getHours())+":"+ addzero(date.getMinutes())+":"+ addzero(date.getSeconds());
                aTime.innerHTML=str;
            }
            setInterval(times,1000);
            times();
           
        }
    </script>
  </head>
  
  <body>
       <div id="tab">
            <h1 id="aTime"></h1>
        </div>
        <h1>您還沒有登陸,請先去登陸</h1>
        <h1><a href="login.jsp">登陸</a></h1>
  </body>
</html>

5、web.xml

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
  <display-name>web_test</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  
  <servlet>
    <servlet-name>LoginServlet</servlet-name>
    <servlet-class>demo.web.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>LoginServlet</servlet-name>
    <url-pattern>/LoginServlet</url-pattern>
  </servlet-mapping>
   <servlet>
    <description></description>
    <display-name>uploadservlet</display-name>
    <servlet-name>uploadservlet</servlet-name>
    <servlet-class>com.sunlizhen.upload.uploadservlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>uploadservlet</servlet-name>
    <url-pattern>/uploadservlet</url-pattern>
  </servlet-mapping>
</web-app>

6、servlet編寫

uploadservlet.jsp

package com.sunlizhen.upload;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

public class uploadservlet extends HttpServlet {

    public void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {
                //得到上傳檔案的儲存目錄,將上傳的檔案存放於WEB-INF目錄下,不允許外界直接訪問,保證上傳檔案的安全
    	        String savePath = "E://上傳//"; 
               /* String savePath = this.getServletContext().getRealPath("/WEB-INF/upload");*/
                /*String savePath = this.getServletContext().getContextPath();*/
                
                File file = new File(savePath);
                
                
                //判斷上傳檔案的儲存目錄是否存在
                if (!file.exists() && !file.isDirectory()) {
                    System.out.println(savePath+"目錄不存在,需要建立");
                    //建立目錄
                    file.mkdir();
                }
                //訊息提示
                String message = "";
                try{
                    //使用Apache檔案上傳元件處理檔案上傳步驟:
                    //1、建立一個DiskFileItemFactory工廠
                    DiskFileItemFactory factory = new DiskFileItemFactory();
                    //2、建立一個檔案上傳解析器
                    ServletFileUpload upload = new ServletFileUpload(factory);
                     //解決上傳檔名的中文亂碼
                    upload.setHeaderEncoding("UTF-8"); 
                    //3、判斷提交上來的資料是否是上傳表單的資料
                    if(!ServletFileUpload.isMultipartContent(request)){
                        //按照傳統方式獲取資料
                        return;
                    }
                    //4、使用ServletFileUpload解析器解析上傳資料,解析結果返回的是一個List<FileItem>集合,每一個FileItem對應一個Form表單的輸入項
                    List<FileItem> list = upload.parseRequest(request);
                    for(FileItem item : list){
                        //如果fileitem中封裝的是普通輸入項的資料
                        if(item.isFormField()){
                            String name = item.getFieldName();
                            //解決普通輸入項的資料的中文亂碼問題
                            String value = item.getString("UTF-8");
                            //value = new String(value.getBytes("iso8859-1"),"UTF-8");
                            System.out.println(name + "=" + value);
                        }else{//如果fileitem中封裝的是上傳檔案
                            //得到上傳的檔名稱,
                            String filename = item.getName();
                            System.out.println(filename);
                            if(filename==null || filename.trim().equals("")){
                                continue;
                            }
                            //注意:不同的瀏覽器提交的檔名是不一樣的,有些瀏覽器提交上來的檔名是帶有路徑的,如:  c:\a\b\1.txt,而有些只是單純的檔名,如:1.txt
                            //處理獲取到的上傳檔案的檔名的路徑部分,只保留檔名部分
                            filename = filename.substring(filename.lastIndexOf("\\")+1);
                            //獲取item中的上傳檔案的輸入流
                            InputStream in = item.getInputStream();
                            //建立一個檔案輸出流
                            FileOutputStream out = new FileOutputStream(savePath + "\\" + filename);
                            //建立一個緩衝區
                            byte buffer[] = new byte[1024];
                            //判斷輸入流中的資料是否已經讀完的標識
                            int len = 0;
                            //迴圈將輸入流讀入到緩衝區當中,(len=in.read(buffer))>0就表示in裡面還有資料
                            while((len=in.read(buffer))>0){
                                //使用FileOutputStream輸出流將緩衝區的資料寫入到指定的目錄(savePath + "\\" + filename)當中
                                out.write(buffer, 0, len);
                            }
                            //關閉輸入流
                            in.close();
                            //關閉輸出流
                            out.close();
                            //刪除處理檔案上傳時生成的臨時檔案
                            item.delete();
                            message = "檔案上傳成功!";
                        }
                    }
                }catch (Exception e) {
                    message= "檔案上傳失敗!";
                    e.printStackTrace();
                    
                }
                request.setAttribute("msg",message);
                request.getRequestDispatcher("/message.jsp").forward(request, response);
    }

    public void doPost(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        doGet(request, response);
    }
}

LoginServlet.jsp

package demo.web.servlet;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class LoginServlet extends HttpServlet {
	static final String driverClassName = "com.mysql.jdbc.Driver";
	static final String url = "jdbc:mysql://localhost:3306/test?characterEncoding=utf-8";
	static final String mysqlUsername = "root";
	static final String mysqlPassword = "slzslz";
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setContentType("text/html;charset=utf-8");
		Connection conn = null;
		PreparedStatement pstmt = null;
		ResultSet rs = null;
		try {
			Class.forName(driverClassName);
			conn = DriverManager.getConnection(url, mysqlUsername, mysqlPassword);
			String username = request.getParameter("username");
			String password = request.getParameter("password");
			String sql = "SELECT * FROM sign WHERE username=? and password=?";
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, username);
			pstmt.setString(2, password);
			rs = pstmt.executeQuery();
			System.out.println(username +", " + password);
			
			if(rs.next()) {
				request.setAttribute("username", rs.getString("username"));
				request.getSession().setAttribute("user_name", username);
				
				/*System.out.println(rs.getString("username"));*/
				request.setAttribute("msg", "成功登陸!");
				request.getRequestDispatcher("/message.jsp").forward(request, response);
			} else {
				request.setAttribute("msg", "使用者名稱或密碼不正確!");
				request.getRequestDispatcher("/login.jsp").forward(request,
						response);
			}
		} catch(Exception e) {
			throw new RuntimeException(e);
		} finally {
			try {
				if(conn != null) conn.close();
				if(pstmt != null) pstmt.close();
				if(conn != null) conn.close();	
			} catch(Exception e) {
				throw new RuntimeException(e);
			}
		}
	}
}