1. 程式人生 > >JavaWeb+Servlet:(一)實現簡單登入

JavaWeb+Servlet:(一)實現簡單登入

注:專案常見錯誤

  1. tomcat無法啟動;報錯:Failed to start component [StandardEngine[Catalina].StandardHost[localhost].

    web.xml檔案servlet配置(注意斜槓):<url-pattern>/login/loginServlet</url-pattern>

  2. eclipse 新建 Dynamic Web Project;建立專案後報錯:**The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path**

表示未新增執行環境:1. 選擇專案,右鍵 選擇 Build Path ---> Configura Build Path

 

 

一、連線資料庫(mysql),編寫dao層

0. 資料庫資訊;

主鍵id;欄位username 唯一,即不重複

CREATE TABLE `admin` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主鍵',
  `username` varchar(25) NOT NULL COMMENT '管理員,姓名',
  `password` varchar(25) NOT NULL COMMENT '登入密碼',
  PRIMARY KEY (`id`),
  UNIQUE KEY `UNIQUE` (`username`)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=utf8

1. JDBCUtil工具類,獲取jdbc連線

//獲取jdbc 連線
public class JDBCUtil {
	private Connection conn;
	
	private final String Driver = "com.mysql.jdbc.Driver";
	private final String url = "jdbc:mysql://localhost:3306/myblog";
	private final String username = "root" ;
	private final String password = "123456" ;
	
	public Connection getConnection(){
		
		try {
			Class.forName(Driver);
			conn = DriverManager.getConnection(url, username, password);
		} catch (ClassNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		return conn;
	}
}

 

2. dao層登入註冊(UserDao.java)

public class UserDao {
	private JDBCUtil jdbcUtil = new JDBCUtil();
	private Connection conn ;
	private PreparedStatement pstmt ;
	private ResultSet rs ;
	private int i = 0 ;
	
	public UserDao() {
		conn = jdbcUtil.getConnection();
	}
	
	//登入
	public String isLogin(String username ,String password){
		String sql = "select * from admin where username='"+username+"'";
		System.out.println("sql:"+sql);
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			
			//判斷使用者名稱是否正確
			rs.last(); //將結果集 移動到最後一行 ;判斷是否有資料
			if(rs.getRow() == 0){ //無資料
				return "username is not exits";
			}else{ 
				//有資料,rs結果集移動到第一個
				rs.beforeFirst();
				//判斷密碼是否正確
				while(rs.next()){
					if(password.equals(rs.getString("password"))){
						return "success" ;
					}
				}
			}
			
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				rs.close();
				pstmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
		
		
		return "password Error";
	}
	
    /*
        註冊
    */
	//註冊 ;插入資料
	public int isRegister(String username ,String password){
		String sql = "insert into admin(id,username,password) value(null,?,?)";
		int executeUpdate = 0 ;
		try {
			pstmt = conn.prepareStatement(sql);
			pstmt.setString(1, username);
			pstmt.setString(2, password);
			//執行插入更新;返回int型別,表示更新的行數(受影響的行數);無資料更新或者插入返回0
			executeUpdate = pstmt.executeUpdate(); 
			System.out.println("executeUpdate:"+executeUpdate);
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				pstmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		
		
		return executeUpdate;
	}
	
	//判斷是否有該使用者
	public String isUsernameExist(String username){
		String sql = "select * from admin where username='"+username+"'";
		System.out.println("sql:"+sql);
	
		try {
			pstmt = conn.prepareStatement(sql);
			rs = pstmt.executeQuery();
			rs.last(); //將結果集 移動到最後一行 ;判斷是否有資料
			if(rs.getRow() == 0){
				return "noExist";
			}
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}finally{
			try {
				rs.close();
				pstmt.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return "exist";
	}
		
}

3. servlet類(LoginServlet.java)

servlet 兩種配置方式:一是web.xml配置方式;二是註解方式(@WebServlet)如下

但需要注意的是使用註解方式: web.xml檔案中metadata-complete="false";即 <web-app metadata-complete="false" >

//註解方式配置servlet路徑
/*@WebServlet("/login/loginServlet")*/
public class LoginServlet{
	private UserDao userDao ;
     
        public LoginServlet() {
            super();
            userDao = new UserDao();
        }

	
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		//1. 獲取表單資訊
		String username = request.getParameter("username");
		String password = request.getParameter("password");
		System.out.println("username:"+username);
		System.out.println("password:"+password);
		
		//2. 呼叫userDao,並與資料庫資訊進行判斷,返回判斷結果
		String isLogin = userDao.isLogin(username, password);
		System.out.println("是否登入:"+isLogin);
		
		//3. 是否登入成功並 轉發或者重定向頁面
		if("success".equals(isLogin)){ //登入成功
			//帳號密碼正確
			/*request.setAttribute("username", username);
			request.setAttribute("password", password);*/
			
			//將使用者資訊儲存到session域中
			HttpSession session = request.getSession();
			session.setAttribute("username", username);
			session.setAttribute("password", password);
			request.getRequestDispatcher("/success.jsp").forward(request, response);
		}else{ //登入失敗
			System.out.println("錯誤原因:"+isLogin);
			//重定向登入介面
			response.sendRedirect(request.getContextPath()+"/index.jsp");
		}
		
		
		
		//搭建環境測試;使用固定帳號密碼實現重定向
		/*if("asdf".equals(username) && "asdf".equals(password)){
			System.out.println("帳號密碼正確");
			//轉發 success介面
			request.setAttribute("username", username);
			request.setAttribute("password", password);
			request.getRequestDispatcher("/success.jsp").forward(request, response);
		}else{
			System.out.println("帳號或密碼錯誤");
			//重定向登入介面
			response.sendRedirect(request.getContextPath()+"/index.jsp");
		}*/
		
		
	}
}

4. web.xml 配置servlet

<?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_3_0.xsd" id="WebApp_ID" version="3.0">
  <display-name>JavaWebTest</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>   
  </welcome-file-list>

  <servlet>
    <servlet-name>loginServlet</servlet-name>
    <servlet-class>com.space.servlet.LoginServlet</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>loginServlet</servlet-name>
    <url-pattern>/login/loginServlet</url-pattern>
  </servlet-mapping>
</web-app>

5. index.jsp登入頁面

 <!-- 第一種設定全域性路徑:
    		使用方式如: <form
    		action=" ${APP_PATH}/LoginServlet"  
    	等同於: ${pageContext.request.contextPath}
    	
    -->
    <% pageContext.setAttribute("APP_PATH", request.getContextPath()); %>

    <!-- 第二種設定全域性路徑:
		<\%=request.getContextPath() %>
	 -->
	<form id="form" action="<%=request.getContextPath() %>/login/loginServlet" method="POST">
		username:<input type="text" name="username"/><br>
		password:<input type="password" name="password" /><br>
		<input type="submit" value="登入"/><button type="button" id="ajaxBtn">後臺登入</button><br>
		<button type="button" id="btnRegister">註冊</button>
	</form>

6. success.jsp登入成功頁面

<body>
	<h1>登入成功</h1>
	登入使用者名稱:"${username}" <br>
	登入密碼:"${password }"
</body>

 

具體專案程式碼訪問 GitHub:連結