如何使用Java+servlet+jsp開發一個web登錄系統
- 2020 年 7 月 24 日
- AI
- javascript
最近在整理一些關於Java方面的知識,特別是開發方面的。關於Java開發,有很多技術可以進行研究。最早接觸到Java是做管理系統,當時讀研時,師兄教我們寫ssh(structs, spring, hibernate),之後上班後,在公司接觸到Spring-boot,可以很方便的開發各種資訊管理系統和API介面。本篇文章主要講解如何使用Java+servlet+jsp開發一個web登錄系統。
web登錄系統主要的流程是:首頁是登錄介面,有用戶名、密碼,用戶輸入的用戶名與密碼和指定的用戶名、密碼一致後,點擊登錄,成功後跳轉到指定的頁面,並顯示用戶名和密碼。
首先我們要設計一個登錄的介面。
login.html
<form action="servlet/login" method="post">
account:<input type="text" name="user"> <br> <br>
password:<input type="password" name="pwd"> <br> <br>
<input type="submit" value="login">
</form>
登錄介面主要是做一個表單,表單主要是由用戶名:account, 密碼:password組成,然後還有一個提交按鈕。最後,表單的數據要通過post方式進行提交,提交的地方是servlet/login,
然後我們開始寫login的servlet
login.java
package servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
/**
- Servlet implementation class login
*/
@WebServlet(“/login”)
public class login extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* **@see** HttpServlet#HttpServlet()
*/
public login() {
super();
// **TODO** Auto-generated constructor stub
}
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// 獲得初始化參數
String userName = this.getInitParameter("userName");
String password = this.getInitParameter("password");
// 從request接收表單數據
request.setCharacterEncoding("GBK");
String name = request.getParameter("user");
String pass = request.getParameter("pwd");
if (name.equals(userName) && pass.equals(password)) {
request.getRequestDispatcher("/welcome.jsp").forward(request, response);// 請求轉發跳轉
} else {
response.sendRedirect("/login_servlet/error.jsp");// 重定向跳轉
}
}
}
這樣我們可以通過:
String userName = this.getInitParameter(“userName”);
String password = this.getInitParameter(“password”);
獲取web.xml中指定的用戶名和密碼
通過:
String name = request.getParameter(“user”);
String pass = request.getParameter(“pwd”);
獲取表單傳來的用戶名和密碼,然後通過
if (name.equals(userName) && pass.equals(password))來進行對比,如果一致則跳轉到welcome.jsp頁面:
<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
<%
request.setCharacterEncoding(“utf-8”);
String name=request.getParameter(“user”);
%>
welcome,<%=name %>
同時獲取用戶名,並將用戶名顯示在頁面。
如果用戶名和密碼不一致,則跳轉到error.jsp頁面:
<%@ page language=”java” contentType=”text/html; charset=UTF-8″
pageEncoding=”UTF-8″%>
登錄失敗,請重新登錄
最後就是配置web.xml
<web-app version=”2.5″ xmlns=”//java.sun.com/xml/ns/javaee“
xmlns:xsi=”//www.w3.org/2001/XMLSchema-instance“
xsi:schemaLocation=*”//java.sun.com/xml/ns/javaee
//java.sun.com/xml/ns/javaee/web-app_2_5.xsd”>
最後通過tomcat啟動項目