1. 程式人生 > >登陸頁面jsp+servlet

登陸頁面jsp+servlet

雖然登陸介面很簡單,但是自己老是忘記,所以寫下,以後看的時候能夠比較清楚的理解。

1.寫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>
</body>
</html>

說明:(1)action後面跟著的就是這個頁面要驗證的servlet類的位置

          (2)name=“username” name=“password”相當於一個標識在servlet中就是通過name值來對資料進行操作的

          (3)${msg }表示獲取內建物件中賦值給msg變數的值

2.寫對應的servlet,這裡的servlet的名字與login.jsp中action後面跟著的名字必須一致。

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("/success.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);
			}
		}	
	}
}

說明:(1)首先獲取資料庫的連線

         (2)request.setAttribute("msg", "成功登陸!");意思就是把成功登陸這句話當作一個變數賦值給內建物件msg,這個內建物件可以通過jsp頁面直接呼叫。

         (3)在(2)的程式碼後面必須跟上request.getRequestDispatcher("/success.jsp").forward(request, response);表明我們所設定的內建物件值傳給哪個jsp頁面。

3.成功登陸跳轉頁面success.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>

4.配置檔案web.xml

 <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>

說明:(1)切記這裡的<url-pattern>的值必須要與login.jsp頁面的action後面跟的值的地址一致,否則一直會有報錯的。

          (2)<servlet-class>後面跟的是包名+類名

5.頁面效果展示

使用者名稱或者密碼錯誤,會提示使用者名稱或者密碼錯誤


正確登陸會跳轉到success.jsp


Tips:這裡只需要一個架包 mysql-connector-java-5.1.7-bin.jar即可。