1. 程式人生 > >javaWeb前後臺互動(二)

javaWeb前後臺互動(二)

一、MVC思想

責任分離思想.

M:Model,資料模型物件.(JavaBean)

V:View,檢視介面.(JSP,Panel,Window)

C:Controller,控制器(Servlet)

本次程式碼採用:Tomcat7.57  JDK 1.8  Eelipse編寫  資料庫:Mysql

二、專案結構(MVC模式)

自己建立動態專案,然後再建好包。

1、編寫工具類(JdbcUtil)

package util;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import java.util.Properties;

//  連線資料庫
public class JdbcUtil {
	private static Properties p = new Properties();
	static {
		try {
			ClassLoader loader = Thread.currentThread().getContextClassLoader();
			// 從classpath的跟路徑去尋找db.properties
			InputStream inStream = loader.getResourceAsStream("db.properties");
			p.load(inStream); // 載入
		} catch (IOException e) {
			throw new RuntimeException("載入classpath路徑下的db.properties檔案失敗", e);
		}
		// 1載入註冊驅動
		try {
			Class.forName(p.getProperty("DriverName"));
			System.out.println("載入資料驅動正常");
		} catch (Exception e) {
			throw new RuntimeException("資料庫驅動載入失敗", e);
		}
	}
	// 返回建立好的Connection物件,用靜態的這種方式應該把構造器私有化起來
	public static Connection getConn() {
		try {
			System.out.println("連線資料庫正常");
			// 2獲取連線物件
			return DriverManager.getConnection(p.getProperty("url"), p.getProperty("username"),
					p.getProperty("password"));
		} catch (Exception e) {
			e.printStackTrace();
		}
		throw new RuntimeException("資料庫連線異常");
	}
	// 5):釋放資源
	public static void close(Connection conn, Statement st, ResultSet re) {
		try {
			if (re != null) {
				re.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			try {
				if (st != null) {
					st.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
			try {
				if (conn != null) {
					conn.close();
				}
			} catch (Exception e) {
				e.printStackTrace();
			}
		}
	}
	// 防止先建立物件,然後再呼叫方法。不讓外界建立,直接用類名呼叫
	private JdbcUtil() {
		}

}

2、domain(model)層

package domain;

/**
 *   使用者
 * @author
 *
 */
public class User {
	private int id;
	private String username;
	private String password;
	public User() {
		super();
	}
	
	public User(String username, String password) {
		super();
		this.username = username;
		this.password = password;
	}

	public User(int id, String username, String password) {
		super();
		this.id = id;
		this.username = username;
		this.password = password;
	}

	public int getId() {
		return id;
	}
	public void setId(int id) {
		this.id = id;
	}
	public String getUsername() {
		return username;
	}
	public void setUsername(String username) {
		this.username = username;
	}
	public String getPassword() {
		return password;
	}
	public void setPassword(String password) {
		this.password = password;
	}
	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
	}
}

3、寫dao層

介面層:

package dao;

import domain.User;

/**
 *  登入
 * @author 
 *
 */
public  interface  IUserDao {
	/**
	 * 使用者登入 
	 * @param username
	 * @param password
	 * @return
	 */
	public  User loginUser(String username,String password);
}

實現層:

package dao.impl;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import dao.IUserDao;
import domain.User;
import util.JdbcUtil;

public class UserDaoImpl implements IUserDao {
	//  登入
	@Override
	public User loginUser(String username, String password) {
		String sql = "SELECT * FROM t_user WHERE username=? AND password=?";
		Connection conn = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		 try {
			conn = JdbcUtil.getConn();
			ps = conn.prepareStatement(sql);
			ps.setString(1, username);
			ps.setString(2, password);
			rs = ps.executeQuery();
			if (rs.next()) {
				User user = new User();
				user.setUsername(rs.getString("username"));
				user.setPassword(rs.getString("password"));
				return user;
			}
		} catch (SQLException e) {
			e.printStackTrace();
		}
		return null;
	}
}

4、service介面和實現層

介面:

package service;

import domain.User;

public interface IUserService {
	/**
	 * 登入
	 * @param username
	 * @param password
	 * @return
	 */
	public  User loginUser(String username,String password);
}

實現層:

package service.impl;

import dao.IUserDao;
import dao.impl.UserDaoImpl;
import domain.User;
import service.IUserService;

public class UserServiceImpl implements IUserService{
	private IUserDao dao = new UserDaoImpl();
	@Override
	public User loginUser(String username, String password) {
		
		return dao.loginUser(username, password);
	}
}

5、controller層

package controller;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import domain.User;
import service.IUserService;
import service.impl.UserServiceImpl;

public class UserServlet  extends HttpServlet{
	private static final long serialVersionUID = 1L;
	private IUserService userService = new UserServiceImpl();
	
	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		String userName = req.getParameter("username");
		String password = req.getParameter("password");
		
		User user = userService.loginUser(userName, password);
		if (user != null) {
			resp.sendRedirect("login_success.jsp");
		}else {
			resp.sendRedirect("login_fail.jsp");
		}
	}
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		this.doPost(req, resp);
	}
}

6、這個時候記得建立resource

#key=value

DriverName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/javaweb
username=root
password=root

7、建立三個JSP(view層)

我只貼login.jsp程式碼,登入成功和失敗頁面裡面都是一句話,僅僅為做跳轉看效果。

其實完全用把結果存放到session裡面,在login.jsp裡面寫el表示式接受資訊也可以看出效果,但因為是初學者,還是多寫幾個頁面看的直觀。

<%@ 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="UserServlet" method="post">
		使用者名稱:<input type="text" class="inputName" name="username"  placeholder="使用者名稱"><br />
		 
		 密  碼:<input type="password" name="password" placeholder="密碼"><br />
		<button type="submit" >登入</button>
	</form>
</body>
</html>

資料庫就不放了,裡面就id,username,password三個欄位。

效果圖:

登入成功:

登入失敗:

三、總結

  寫到這裡按照MVC模式進行互動已完成,

原始碼:JavaWeb原始碼 。本想著0積分的,但是沒有0積分選項,有積分想下載就下載,不想下載評論區留言或私信,我發你郵箱。

如果你完全複製我的程式碼,還報錯,這個時候很有可能是環境問題,因為我都是測試了好幾遍完全正確才截圖的,有問題歡迎留言討論。

如果有不同看法,或者是文中寫錯的地方,麻煩大佬留言指正文章錯誤,謝謝!!!