今天本來一直風和日麗的在學習RxJava2框架關(guān)于線程調(diào)度的方法咏删,涉及到一個登錄注冊的簡單Demo。我就準備搭建一個本地的服務器用來測試问词,感覺很簡單這一下手整整忙叨了一個下午督函。哎,瞬間霧霾陰天了激挪,JavaServlet那點技術(shù)全部忘光......好開心(博主已瘋)奏黑□烁龋總之進過一下午的折騰,這個本地測試服務器總算搭建成功了,能夠測試登錄和注冊兩個功能值纱。GitHub地址有興趣的朋友可以自行下載啊。
一鸭廷、準備工作
- MySQL的下載+安裝
- Navicat的下載+安裝
- Tomcat的下載象颖,我這里下載的是9.0的最新版,建議大家下載解壓版的安裝包
- json解析的架包豺瘤,我這里下載的是Gson
- mysql-connector的架包
二吆倦、配置環(huán)境
-
1、Tomcat的安裝測試
打開解壓包下的D:\apache-tomcat-9.0.0.M18\bin坐求,找到startup.bat文件并運行
startup.bat
此時出現(xiàn)如圖所示的提示就代表服務器開啟成功蚕泽。
使用瀏覽器或者Postman輸入localhost:8080,如果出現(xiàn)Tomcat的首頁就代表服務器配置沒有問題桥嗤。
2须妻、新建Dynamic Web Project
鍵入Project name,這里首次新建的話要配置一下RunTime泛领。點擊New Runtime...
選擇自己的Tomcat版本荒吏,我這里選擇9.0,點擊下一步
配置一下本地的Tomcat地址點擊Finish按鈕配置就完成了师逸。
新建好后的Dynamic Web Project項目應該是這樣嬸的
然后在你的WebContent文件夾下新建一個index.html的文件司倚,即是我們的默認歡迎頁了啊豆混。
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>welcome to TestServer</h1>
</body>
</html>
接下來我們再將我們的Servlet加入到我們的Tomcat服務器中
點擊添加---Next---Add---Finish,步驟的話也很簡答动知,大家看圖操作就好了皿伺。
點擊完成后我們還需要配置我們的Tomcat服務器,雙擊服務器打開配置文件
修改如下兩個位置盒粮,切記如果修改的不對的話鸵鸥,只能刪除服務器再重新添加重新配置了。
配置完成后丹皱,我們就可以啟動我們的服務器了測試是否配置完畢了妒穴。(不要忘記關(guān)閉我們剛開始時打開的服務器啊,bin/shutdown.bat就可以關(guān)閉服務器了)
出現(xiàn)如下字樣就代表服務器已經(jīng)開啟了摊崭,稍后我們來測試一下讼油,同樣在瀏覽器中輸入localhost:8080/你的項目名稱
如果此時出現(xiàn)了你設置的index.html首頁就代表你的Tomcat服務器配置成功了啊。革命尚未成功通知仍需努力啊呢簸,騷年奔跑吧矮台。
- 3、配置jar包和配置JDBC
首先將Gson和MySql_Connector兩個jar包拷貝到WebContent/WEB-INF/lib文件夾下根时,然后將兩個jar包編譯到系統(tǒng)中瘦赫。
JDBC的配置連接就比較麻煩了,大家可以到GitHub上直接拷貝代碼來完成配置連接蛤迎。這里我簡單說明下配置的過程确虱。
首先在src文件夾下新建文件jdbc.properties,輸入以下內(nèi)容
sqlDriver=com.mysql.jdbc.Driver
sqlUrl=jdbc:mysql://localhost:3306/testserver?user=root&password=root
這里testserver的位置填寫你的數(shù)據(jù)庫名稱,user和password分別是你數(shù)據(jù)庫管理員的帳戶名和密碼替裆,默認都是root校辩。
這是我的包結(jié)構(gòu),這還是當初學習時唯一記得的分層(哭...)大家可以隨意發(fā)揮了啊扎唾,我就簡單介紹一下JDBC相關(guān)的工具類
PropertiesUtil用于讀取.properties文件的工具類,里面就一個方法用來讀取鍵值對的value值召川。
public class PropertiesUtil {
/**
* 通過Key取出對應值的方法
* @return
*/
public static String getValue(String key,String fileName) {
String value = null;
String path = PropertiesUtil.class.getResource("/").getPath();
Properties p = new Properties();
System.out.println("PropertiesUtil path:" + path);
try {
p.load(new FileInputStream(new File(path+"/"+fileName)));
value = p.getProperty(key);
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
return value;
}
}
JdbcUtils用于連接數(shù)據(jù)庫的工具類,兩個方法分別用來連接數(shù)據(jù)庫和關(guān)閉數(shù)據(jù)庫的連接。
public class JdbcUtils {
static {
// 加載數(shù)據(jù)庫驅(qū)動程序
try {
Class.forName(PropertiesUtil.getValue("sqlDriver","jdbc.properties"));
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection(){
try{
Connection connection = DriverManager.getConnection(
PropertiesUtil.getValue("sqlUrl","jdbc.properties"));
System.out.println("JdbcUtils*****connection="+connection);
return connection;
} catch (SQLException e){
e.printStackTrace();
}
return null;
}
public static void closeAll(ResultSet set, PreparedStatement statement, Connection connection){
try{
if(set!=null){
set.close();
}
if(statement!=null){
statement.close();
}
if(connection!=null){
connection.close();
}
}catch(SQLException e){
e.printStackTrace();
}
}
}
JDBC的配置就已經(jīng)完成了胸遇,下面我們來新建一個用于訪問服務器狀態(tài)的Servlet類荧呐。
三、Servlet的新建
在servlet包下新建一個ServerStatusServlet的Servlet纸镊,輸入完名稱后直接點擊Finish就可以了倍阐。
剛剛新建完成后,關(guān)于@WebServlet()注解要提一下逗威,這里輸入的“/getServerStatus”代表你請求地址時的具體請求方法名稱峰搪。稍后我們在測試的時候你就會了解到它的作用。
這里我將源碼直接貼出來凯旭,很簡答的源碼:
@WebServlet("/getServerStatus")
public class ServerStatusServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
/**
* @see HttpServlet#HttpServlet()
*/
public ServerStatusServlet() {
super();
// TODO Auto-generated constructor stub
}
/**
* @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
*/
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=utf-8");
Result result = new Result(true,I.MSG_SUCCESS);
JsonUtil.writeJsonToClient(result, response);
}
/**
* @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
*/
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
// TODO Auto-generated method stub
doGet(request, response);
}
}
JsonUtil工具類用于將結(jié)果寫入json格式返還給客戶端概耻。這里剛開始有點想復雜了也懶得改了使套,所以大家可以自行創(chuàng)建這個工具欄。
public class JsonUtil {
private static final Gson gson = new Gson();
public static <T> void writeJsonToClient(T bean, HttpServletResponse response) {
if (bean instanceof Result) {
writeResultToClient((Result)bean,response);
}
}
private static void writeResultToClient(Result result, HttpServletResponse response) {
PrintWriter pw = null;
try {
pw = response.getWriter();
pw.write(gson.toJson(result,Result.class));
pw.flush();
} catch (IOException e) {
e.printStackTrace();
} finally {
if (pw!=null) {
pw.close();
}
}
}
}
好完成上幾步我們就可以來測試服務器的狀態(tài)了鞠柄,在瀏覽器中輸入localhost:8080/Servlet/getServerStatus侦高。(這里的getServerStatus即是我們注解中的字符串)。好厌杜,如果你看到如下狀態(tài)奉呛,那么恭喜你說明你已經(jīng)簡單的創(chuàng)建和使用了JavaServlet。
四夯尽、Register功能的實現(xiàn)
這里我就帶領(lǐng)大家一起學習一下注冊功能的實現(xiàn)瞧壮,登錄功能原理跟它一樣,大家就可以自行查看代碼來學習了匙握。
- 新建RegisterServlet咆槽,因為注冊功能為了安全起見都是使用Post請求,所以我們只需要實現(xiàn)doPost方法即可圈纺。這里大家注意一下Post請求時獲取請求參數(shù)的方法罗晕。
- pojo/User:
package cn.xunuosi.test.pojo;
import java.io.Serializable;
public class User implements Serializable {
private static final long serialVersionUID = 1L;
private String username;
private String password;
public User() {
super();
}
public User(String userid, String password) {
super();
this.username = userid;
this.password = password;
}
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 [userid=" + username + ", password=" + password + "]";
}
}
- biz層的接口和實現(xiàn)類
ITestServerBiz接口
TestServerBiz實現(xiàn)類
public class TestServerBiz implements ITestServerBiz {
private ITestServerDao dao;
public TestServerBiz() {
dao = new TestServerDao();
}
@Override
public Result register(User user, HttpServletRequest request) {
Result res = new Result();
User u = dao.findUserByName(user.getUsername());
if (u == null) {
if (dao.addUser(user)) {
res.setResCode(I.MSG_SUCCESS);
res.setSuccess(true);
res.setRetData(user);
} else {
res.setSuccess(false);
}
} else {
res.setSuccess(false);
res.setResCode(I.MSG_ACCOUNT_REPEAT_ERROR);
}
return res;
}
}
- dao層的接口和實現(xiàn)類
ITestServerDao接口
TestServerDao實現(xiàn)類
ublic class TestServerDao implements ITestServerDao {
@Override
public boolean addUser(User user) {
PreparedStatement statement = null;
Connection connection = JdbcUtils.getConnection();
try {
String sql = "insert into " + I.User.TABLE_NAME + "(" + I.User.USER_NAME + "," + I.User.PASSWORD + ")values(?,?)";
System.out.println("addUser:"+sql);
statement = connection.prepareStatement(sql);
statement.setString(1, user.getUsername());
statement.setString(2, user.getPassword());
statement.executeUpdate();
return true;
} catch (SQLException e) {
e.printStackTrace();
return false;
} finally {
JdbcUtils.closeAll(null, statement, connection);
}
}
}
都是最基本的JDBC的操作,話說最基本的我也全部忘光了啊赠堵,哎,感謝Internet感謝GitHub感謝CCTV...
好了RegisterServlet已經(jīng)完成了法褥,接下來我們需要創(chuàng)建數(shù)據(jù)庫和數(shù)據(jù)表茫叭。
五、Navicat的使用
這個就很簡答了啊半等,首先新建一個MySQL的連接揍愁,輸入連接名,默認端口號就可以杀饵,輸入數(shù)據(jù)庫的用戶名和密碼莽囤。點擊連接測試,顯示連接成功即可切距。
在新建的連接上新建一個數(shù)據(jù)庫
在新建數(shù)據(jù)庫中新建一張表格t_testserver_user朽缎,設置如圖:
好了,數(shù)據(jù)庫的新建就這么愉快的完成了~下面我們測試我們的注冊功能是否好用啊谜悟,在Postman中輸入:localhost:8080/Servlet/register话肖,親不要忘了注冊時Post請求啊,Post請求葡幸,Post請求最筒,Post請求,重要的事情說三遍啊蔚叨。
出現(xiàn)如上所示就代筆服務器端已經(jīng)沒問題了床蜘,我們再來看看數(shù)據(jù)庫中的數(shù)據(jù)如何辙培。還有什么比功能實現(xiàn)的那一刻還要爽的事情嗎.....(單身狗的悲哀…-_-!)
好以上就是關(guān)于本地測試服務器的簡單搭建流程,寫的可能不是很好邢锯,但是重在參與啊扬蕊。大家可以下載源碼,來自行測試效果啊弹囚。希望在學習的路上能夠與大家不斷前行啊~