1. 程式人生 > >JavaWeb開發基礎:Servlet登入小例項

JavaWeb開發基礎:Servlet登入小例項

Servlet主要步驟

建立Servlet類

package com.login.servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class LoginServlet extends HttpServlet{
	@Override
	public void init() throws ServletException {
		super.init();
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String forward = null;
		if(username.equals("haha") && password.equals("1234")){
			forward = "/jsp/success.jsp";
		}else{
			forward = "/jsp/error.jsp";
		}
		//請求轉發
		RequestDispatcher rd = req.getRequestDispatcher(forward);
		rd.forward(req, resp);
	}

	@Override
	public void destroy() {
		super.destroy();
	}
	
}

Servlet類要繼承HttpServlet,重寫doGet和doPost方法

String username = req.getParameter("username");
String password = req.getParameter("password");

上面的程式碼用於獲取表單頁面傳過來的引數

forward = "/jsp/success.jsp";
RequestDispatcher rd= req.getRequestDispatcher(forward);
rd.forward(req, resp);

上面的程式碼用於請求轉發,跳轉到success頁面進行處理,實現跳轉的方法還有重定向

resp.sendRedirect(req.getContextPath()+forward);

請求轉發和重定向的區別:

請求轉發只請求一次,所以success頁面能獲得username的值,重定向請求兩次,所以success頁面username的值為null;請求轉發只能在同一應用中跳轉,重定向能跳轉到不同應用中的頁面

在web.xml中配置Servlet

<servlet>
       <servlet-name>LoginServlet</servlet-name>
       <servlet-class>com.login.servlet.LoginServlet</servlet-class>
</servlet>

<servlet-mapping>
       <servlet-name>LoginServlet</servlet-name>
       <url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>

兩個<servlet-name>中的值要一樣,<servlet-class>是servlet類完整的包路徑,<url-pattern>為訪問servlet的入口

建立jsp頁面

login.jsp

<form action="<%=request.getContextPath()%>/LoginServlet" method="post">
      使用者名稱:<input name="username" type="text"/><br/>
      密 碼:<input name="password" type="text"/><br/>
      <input type="submit" value="提交"/>
      <input type="reset" value="重置"/>
</form>

action="<%=request.getContextPath()%>/LoginServlet"與<url-pattern>的路徑一致,就可以呼叫相應的servlet

加上JDBC,完成業務邏輯

編寫業務邏輯處理類

package com.login.service;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import com.login.dao.UserDao;
import com.login.dao.impl.UserDaoImpl;
import com.login.entity.UserEntity;
import com.login.util.ConnectionFactory;

public class CheckUserService {
	public boolean Check(UserEntity user){
		Connection conn = null;
		ResultSet rs = null;
		try {
			conn = ConnectionFactory.getInstance().getConnection();
			conn.setAutoCommit(false);
			UserDao userDao = new UserDaoImpl();
			rs = userDao.select(conn, user);
			conn.commit();
			if(rs.next()){
				return true;
			}
		} catch (SQLException e) {
			e.printStackTrace();
			try {
				conn.rollback();
			} catch (SQLException e1) {
				e1.printStackTrace();
			}
		}finally{
			try {
				rs.close();
				conn.close();
			} catch (SQLException e) {
				e.printStackTrace();
			}
		}
	return false;
	}
}

Check方法傳入使用者名稱和密碼引數,呼叫Dao物件查詢資料庫中是否存在滿足要求的記錄,返回相應的bool值

編寫CheckLoginServlet類

package com.login.servlet;

import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.login.entity.UserEntity;
import com.login.service.CheckUserService;

public class CheckLoginServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private CheckUserService cku = new CheckUserService();
       
    public CheckLoginServlet() {
        super();
    }

	protected void doGet(HttpServletRequest req, HttpServletResponse resp)
			throws ServletException, IOException {
		doPost(req, resp);
	}

	protected void doPost(HttpServletRequest req, HttpServletResponse resp) 
			throws ServletException, IOException {
		UserEntity user = new UserEntity();
		String username = req.getParameter("username");
		String password = req.getParameter("password");
		String forward = null;
		if(username.equals("")|| password.equals("")){
			//請求轉發
			forward = "/jsp/error.jsp";
			req.setAttribute("msg", "使用者名稱或密碼為空!");
		}else{
			user.setName(username);
			user.setPassword(password);
			boolean check = cku.Check(user);
			if(check){
				//請求轉發
				forward = "/jsp/success.jsp";
			}else{
				//請求轉發
				forward = "/jsp/error.jsp";
				req.setAttribute("msg", "使用者名稱或密碼錯誤!");
				
				System.out.println("====="+username+"---"+password);
			}
		}
		RequestDispatcher rd = req.getRequestDispatcher(forward);
		rd.forward(req, resp);
	}
}

CheckLoginServlet的doPost方法呼叫CheckUserService的check方法,通過返回的值判斷使用者名稱和密碼是否正確,進行相應的跳轉

在web.xml中配置相應的servlet,修改login.jsp頁面完成登入程式