現在許多開發web項目都需要使用登錄界面,而開發JSP是一種動態頁面技術,下面錯新技術頻道小編和大家分享JSP制作簡單登錄界面實例,希望對你學習這方面知識有所幫助。
運行環境
eclipse+tomcat+MySQL 不知道的可以參考Jsp運行環境——Tomcat
項目列表
這里我先把jsp文件先放在Web-INF外面訪問
1.需要建立的幾個文件在圖上.jsp
2.還要導入MySQL的jar包mysql-5.0.5.jar,導到WEB-INF中的lib文件夾就可以不需要Bulid Path
3.開始編寫代碼:
代碼演示:
index.jsp就好像一般網站的首頁一樣感覺,將header.jsp和footer.jsp引入其中
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ include file="header.jsp" %>
<%@include file="footer.jsp" %>
header.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
footer.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
xxxxxxxxxxx可以試試|xxxxxxxxxxxx技術有限公司
京 ICP 證 1234567 號|Copyright ? 1999-2017, All Rights Reserved
頁面內容展示:
login.jsp登陸用戶名密碼填寫界面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%--表單--%>
內容顯示:
test.jsp 是對表單login.jsp 的提交的內容與數據庫中的數據對比驗證,再相應的跳轉
<%@page import="java.sql.*"%><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%><%//請求獲取login.jsp的用戶名username的值 String username=request.getParameter("username");//請求獲取login.jsp的密碼password的值String password=request.getParameter("password");//數據庫MySQL的地址String DBURL="jdbc:mysql://localhost:3306/zhou?useUnicode=true&characterEncoding=utf-8"; String DBName="root"; //登入用戶名String DBPwd="123456";//登入密碼//加載mysql驅動Class.forName("com.mysql.jdbc.Driver");//連接數據庫Connection conn=DriverManager.getConnection(DBURL,DBName,DBPwd);//創建Statement對象Statement st=conn.createStatement();//sql語句,搜索這個username和password在數據庫是否存在String sql="select * from user where name='"+username+"'and pwd='"+password+"'";//運行sql語句,并把得到的結果放入結果集ResultSet中ResultSet rs=st.executeQuery(sql);//判斷這個結果集是否存在,一般username只有一個if(rs.next()){ //設置一個username,將后面username其內容賦值給前面一個username,可以以便下一個頁面使用 request.setAttribute("username", username); //跳轉頁面到userpage.jsp request.getRequestDispatcher("userpage.jsp").forward(request, response);}else{ //設置一個error,將后面的字賦給這個error,以便先一個跳轉頁面的使用,request的作用域有限 request.setAttribute("error", "用戶名或密碼錯誤!!!"); request.getRequestDispatcher("login.jsp").forward(request, response);}conn.close();rs.close();%>
登陸錯誤顯示的頁面內容:
userpage.jsp這個頁面就是登陸成功之后顯示的頁面
<%@page import="javafx.scene.chart.PieChart.Data"%><%@page import="java.util.Date"%><%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
${username},你好,登陸成功?。?/p>
<% //session的作用域問題,可以記錄一個網站的瀏覽量。先得到一個count Object obj=session.getAttribute("count"); //判斷這個對象是否為空 if(obj==null){ //空則重新設置一下count的值 session.setAttribute("count", 0); }else{ //否則將得到的對象強轉加1,就可以記錄瀏覽量 int i=(int)obj+1; session.setAttribute("count", i); %>
<% } //獲取當前時間 Date date=new Date(); out.print("現在時間:"+date); %>
頁面內容:localhost就是127.0.0.1,有時候地址欄是local host時會顯示8個0:
整個簡單的登陸就完事了
大家看完了錯新技術頻道介紹的JSP制作簡單登錄界面實例,是不是覺得這些知識也很不錯,如果適合自己的項目可以嘗試操作看看。
新聞熱點
疑難解答