web 專案中報錯解決,java.io.FileNotFoundException: druid.properties (系統找不到指定的檔案);【spring工廠解耦開發】
使用 Tomcat9.0 , spring5.0框架原始工廠類解耦,druid-1.0.9jar版本,JDK9,MSQL8版本資料庫 模擬web頁面登入案例時候出現druid.properties檔案找不到的報錯資訊,詳情如下【案例程式碼貼最後】;
按照正常來講,配置檔案放在src 目錄下面,然後copy相對路徑就行,可阿里就是反人類;
執行報錯,web瀏覽器空指標,IDEA中:
解決辦法,只能copy全路徑來解決報錯了;
再次執行,跑起來了溜溜的;
專案結構如下:
① 先 jar 包【在lib 中】,以及配置檔案【在src下】;
② 寫 案例頁面 log.html;
③ 開發 utils 工具類【包括獲取 jdbcTemplate 的,以及 獲取 bean 的 BeanFactory】,本次測試使用了c3p0,和 druid 兩種方式進行了測試;
④開發 bean【和資料庫中 table 對應】 , dao層,daoImpl層 ,service層,serviceImpl層【需要解耦】,servlet 中【解耦】
⑤進行測試【Spring的xml 配置完成登入案例 的 CRUD寫過在bolg中自己看】
配置檔案,按照專案結構來【不做一 一說明】:
tUserDao=com.baidu.daoImpl.TUserDaoImpl tUserService=com.baidu.serviceImpl.TUserServiceImpl
<?xml version="1.0" encoding="UTF-8" ?> <c3p0-config> <!-- 預設配置,c3p0框架預設載入這段預設配置 --> <default-config> <!-- 配置JDBC 四個基本屬性 --> <property name="driverClass">com.mysql.cj.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/reba?serverTimezone=UTC&characterEncoding=utf-8&useSSL=false</property> <property name="user">root</property> <property name="password">root</property> </default-config> <!-- 可以自定義配置,為這段配置起一個名字,c3p0指定名稱載入配置 --> <named-config name="hello"> <property name="driverClass">com.mysql.cj.jdbc.Driver</property> <property name="jdbcUrl">jdbc:mysql://localhost:3306/reba?serverTimezone=UTC&characterEncoding=utf-8&useSSL=false</property> <property name="user">root</property> <property name="password">root</property> </named-config> </c3p0-config>
driverClass=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://localhost:3306/reba?serverTimezone=UTC&characterEncoding=UTF-8&useSSL=false
username=root
password=root
filters=stat
initialSize=2
maxActive=300
maxWait=60000
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000
validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
poolPreparedStatements=false
maxPoolPreparedStatementPerConnectionSize=200
jdbc.driverClass=com.mysql.cj.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/reba?serverTimezone=UTC&characterEncoding=UTF-8&useSSL=false
jdbc.username=root
jdbc.password=root
實體bean類和資料庫對應即可,資料庫table如下【 id int , userName varchar , password varchar】:
頁面 form 表單中 action 為servlet的 urlParttens;
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<!-- 上述3個meta標籤*必須*放在最前面,任何其他內容都*必須*跟隨其後! -->
<!-- viewport:視口,支援響應式佈局。
width: 初始寬度與裝置的寬度相同
initial-scale:初始的縮放比,1:1
-->
<!-- 1. 匯入bootstrap中的css樣式檔案 -->
<!-- 2. 匯入jQuery框架 -->
<!-- 3. 匯入bootstrap的js檔案 -->
<!-- 4. 匯入jQuery框架 外掛 -->
<title>Bootstrap 101 Template</title>
<link href="config/css/bootstrap.min.css" rel="stylesheet">
<script src="config/jquery-3.3.1.min.js"></script>
<script src="config/js/bootstrap.min.js"></script>
</head>
<body>
<div class="container " style="width: 300px">
<div class="row" style="text-align: center " >
<!--action 指定瀏覽器的url-->
<form action="/log" method="post" class="form-group ">
<input type="text" placeholder="請輸入使用者名稱" name="userName" class="form-control"><br/>
<input type="text" placeholder="請輸入密碼" name="password" class="form-control"><br/>
<input type="submit" value="登入" class="btn btn-sm btn-primary btn-block">
</form>
</div>
</div>
</body>
</html>
效果:
開發 utils 工具類;
beans工廠類;
package com.baidu.utils;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.ResourceBundle;
/**
* @auther SyntacticSugar
* @data 2018/9/29 0029下午 10:50
*/
public class BeanFactory {
private static ResourceBundle rb = ResourceBundle.getBundle("beans");
private static HashMap<String, Object> map = new HashMap<>();
static {
try {
Enumeration<String> keys = rb.getKeys();
while (keys.hasMoreElements()) {
String key = keys.nextElement();
String value = rb.getString(key); //從beans.properties中獲取value全路徑
Object o = Class.forName(value).getDeclaredConstructor().newInstance();
map.put(key, o);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 獲取 bean
* @param beanName
* @return
*/
public static Object getBeans(String beanName) {
return map.get(beanName);
}
}
連線資料,獲取template ;
package com.baidu.utils;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.jdbc.core.JdbcTemplate;
import javax.sql.DataSource;
import java.io.FileReader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.util.Properties;
/**
* @auther SyntacticSugar
* @data 2018/9/29 0029下午 10:22
*/
public class JdbcUtils {
private static JdbcTemplate template;
private static Connection conn;
private static PreparedStatement statement;
private static ResultSet res;
/**
* 獲取 template
*/
public static JdbcTemplate getJdbcTemplate() {
try { //druid
Properties p = new Properties();
p.load(new FileReader("druid.properties")); // 報錯載入不了檔案
DataSource dataSource = DruidDataSourceFactory.createDataSource(p);
//c3p0 連線資料庫,獲取jdbcTemplate
// ComboPooledDataSource dataSource = new ComboPooledDataSource();
template = new JdbcTemplate(dataSource);
} catch (Exception e) {
e.printStackTrace();
}
return template;
}
/**
* 釋放資源
* @param res
* @param statement
* @param conn
*/
public static void release(ResultSet res, PreparedStatement statement, Connection conn) {
try {
if (res != null) {
res.close();
}
if (statement != null) {
statement.close();
}
if (conn != null) {
conn.close();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
dao 層;
package com.baidu.dao;
import com.baidu.Beans.TUser;
import java.util.List;
/**
* @auther SyntacticSugar
* @data 2018/9/29 0029下午 10:17
*/
public interface TUserDao {
//通過userName password 查詢
List<TUser> findTUserByNameAndPsw(String userName,String password);
}
dao現實類;
package com.baidu.daoImpl;
import com.baidu.Beans.TUser;
import com.baidu.dao.TUserDao;
import com.baidu.utils.JdbcUtils;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import java.util.List;
/**
* @auther SyntacticSugar
* @data 2018/9/29 0029下午 10:43
*/
public class TUserDaoImpl implements TUserDao {
@Override
public List<TUser> findTUserByNameAndPsw(String userName, String password) {
JdbcTemplate template = JdbcUtils.getJdbcTemplate();
String sql="select * from t_user where userName=? and password=?";
List<TUser> list = template.query(sql, new BeanPropertyRowMapper<TUser>(TUser.class), userName, password);
return list;
}
}
service層;
package com.baidu.service;
import com.baidu.Beans.TUser;
import java.util.List;
public interface TUserService {
List<TUser> login(String userName, String password);
}
service實現類;
package com.baidu.serviceImpl;
import com.baidu.Beans.TUser;
import com.baidu.daoImpl.TUserDaoImpl;
import com.baidu.service.TUserService;
import com.baidu.utils.BeanFactory;
import java.util.List;
/**
* @auther SyntacticSugar
* @data 2018/9/29 0029下午 10:47
*/
public class TUserServiceImpl implements TUserService {
@Override
public List<TUser> login(String userName, String password) {
TUserDaoImpl tUserDao = (TUserDaoImpl) BeanFactory.getBeans("tUserDao");
// TUserDaoImpl tUserDao = new TUserDaoImpl();
List<TUser> list = tUserDao.findTUserByNameAndPsw(userName, password);
//對list進行處理 ,返回TUser
// try {
// TUser tUser = list.get(0);
// } catch (Exception e) {
// System.out.println("登入失敗");//若需要在網頁顯示,該方法不適合
// }
return list;
}
}
servlet ,登入成功跳轉至百度,否則就在頁面實現沒有登陸成功;
package com.baidu.session;
import com.baidu.Beans.TUser;
import com.baidu.serviceImpl.TUserServiceImpl;
import com.baidu.utils.BeanFactory;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;
@WebServlet(name = "Log", urlPatterns = "/log")
public class Log extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);//
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
//
String userName = request.getParameter("userName");
String password = request.getParameter("password");
//呼叫serviceImpl
TUserServiceImpl o = (TUserServiceImpl) BeanFactory.getBeans("tUserService");
// TUserServiceImpl o = new TUserServiceImpl();
List<TUser> list = o.login(userName, password);
//
if (list!=null&&list.size()>0) { //登陸成功,重定向至百度
System.out.println("ok");
response.sendRedirect("http://www.baidu.com");
}else { //失敗,轉發至jsp
System.out.println("登入失敗");
request.setAttribute("info","登入失敗" );
request.getRequestDispatcher("log.html").forward(request,response );
}
}
}