Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

JNDI 实现注册更新 #22

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
Expand Up @@ -27,7 +27,7 @@ public class DatabaseUserRepository implements UserRepository {
private static Consumer<Throwable> COMMON_EXCEPTION_HANDLER = e -> logger.log(Level.SEVERE, e.getMessage());

public static final String INSERT_USER_DML_SQL =
"INSERT INTO users(name,password,email,phoneNumber) VALUES " +
"INSERT INTO USERS(name,password,email,phoneNumber) VALUES " +
"(?,?,?,?)";

public static final String QUERY_ALL_USERS_DML_SQL = "SELECT id,name,password,email,phoneNumber FROM users";
Expand All @@ -44,7 +44,9 @@ private Connection getConnection() {

@Override
public boolean save(User user) {
return false;
return executeUpdate(INSERT_USER_DML_SQL,result->{
return result==1?true:false;
} ,COMMON_EXCEPTION_HANDLER);
}

@Override
Expand Down Expand Up @@ -139,6 +141,44 @@ protected <T> T executeQuery(String sql, ThrowableFunction<ResultSet, T> functio
}


protected <T> T executeUpdate(String sql, ThrowableFunction<Integer, T> function,
Consumer<Throwable> exceptionHandler, Object... args) {
Connection connection =DBConnectionManager.getConnection();

try {
Statement statement = connection.createStatement();

// 执行查询语句(DML)
ResultSet resultSet = statement.executeQuery("SELECT id,name,password,email,phoneNumber FROM users");



PreparedStatement preparedStatement = connection.prepareStatement(sql);
for (int i = 0; i < args.length; i++) {
Object arg = args[i];
Class argType = arg.getClass();

Class wrapperType = wrapperToPrimitive(argType);

if (wrapperType == null) {
wrapperType = argType;
}

// Boolean -> boolean
String methodName = preparedStatementMethodMappings.get(argType);
Method method = PreparedStatement.class.getMethod(methodName, wrapperType);
method.invoke(preparedStatement, i + 1, args);
}
int result = preparedStatement.executeUpdate();
return function.apply(result);
} catch (Exception e){
exceptionHandler.accept(e);
} catch (Throwable e) {
exceptionHandler.accept(e);
}
return null;
}

private static String mapColumnLabel(String fieldName) {
return fieldName;
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

import org.geektimes.projects.user.domain.User;


import javax.annotation.Resource;
import javax.persistence.EntityManager;
import javax.sql.DataSource;
Expand Down Expand Up @@ -46,6 +47,42 @@ public EntityManager getEntityManager() {
return entityManager;
}


// public static Connection getConnection() {

// try {
// DriverManager.setLogWriter(new PrintWriter(System.out));
// String databaseURL = "jdbc:derby:my-user-platform;create=true";
// Class.forName("org.apache.derby.jdbc.EmbeddedDriver");
// Driver driver = DriverManager.getDriver(databaseURL);
// Connection connection = driver.connect(databaseURL, new Properties());
// return connection;
// } catch (ClassNotFoundException e) {
// e.printStackTrace();
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// }

// String databaseURL = "jdbc:derby:my-user-platform;create=true";
// try {
// Connection connection = DriverManager.getConnection(databaseURL);
// return connection;
// } catch (SQLException throwables) {
// throwables.printStackTrace();
// }
// try {
// Context initCtx = new InitialContext();
// Context envCtx = (Context) initCtx.lookup("java:comp/env");
// DataSource ds = (DataSource)envCtx.lookup("jdbc/UserPlatformDB");
// Connection conn = ds.getConnection();
// return conn;
// } catch (Exception e) {
// e.printStackTrace();
// }

// return null;


public Connection getConnection() {
// 依赖查找
Connection connection = null;
Expand All @@ -58,6 +95,7 @@ public Connection getConnection() {
logger.log(Level.INFO, "获取 JNDI 数据库连接成功!");
}
return connection;

}


Expand Down Expand Up @@ -107,7 +145,7 @@ public static void main(String[] args) throws Exception {
// Driver driver = DriverManager.getDriver("jdbc:derby:/db/user-platform;create=true");
// Connection connection = driver.connect("jdbc:derby:/db/user-platform;create=true", new Properties());

String databaseURL = "jdbc:derby:/db/user-platform;create=true";
String databaseURL = "jdbc:derby:my-user-platform;create=true";
Connection connection = DriverManager.getConnection(databaseURL);

Statement statement = connection.createStatement();
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
package org.geektimes.projects.user.web.controller;

import org.geektimes.projects.user.domain.User;
import org.geektimes.projects.user.repository.DatabaseUserRepository;
import org.geektimes.projects.user.sql.DBConnectionManager;
import org.geektimes.web.mvc.controller.PageController;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.GET;
import javax.ws.rs.POST;
import javax.ws.rs.Path;

/**
* @Author xialh
* @Date 2021/3/3 11:27 下午
*/
@Path("/register")
public class RegisterControler implements PageController {
@GET
@Path("/doRegister")
@Override
public String execute(HttpServletRequest request, HttpServletResponse response) throws Throwable {
String name =request.getParameter("uName");
String uPwd =request.getParameter("uPwd");
String uPhone =request.getParameter("uPhone");
String uEmail =request.getParameter("uEmail");
User user = new User();
user.setName(name);
user.setPassword(uPwd);
user.setEmail(uEmail);
user.setPhoneNumber(uPhone);
DatabaseUserRepository repository = new DatabaseUserRepository(new DBConnectionManager());
repository.save(user);

return "success.jsp";
}


}
Original file line number Diff line number Diff line change
@@ -1 +1,2 @@
org.geektimes.projects.user.web.controller.HelloWorldController
org.geektimes.projects.user.web.controller.HelloWorldController
org.geektimes.projects.user.web.controller.RegisterControler
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
<?xml version="1.0" encoding="UTF-8"?>
<Context>
<Resource name="jdbc/UserPlatformDB"
type="javax.sql.DataSource" auth="Container"
description="Derby database for User Platform"
maxActive="100" maxIdle="30" maxWait="10000"
username="" password=""
driverClassName="org.apache.derby.jdbc.EmbeddedDriver"
url="jdbc:derby:my-user-platform;create=true"/>

</Context>
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
metadata-complete="true" version="2.5">

<!-- ��ȷ����� Listener ��������λ -->
<!-- 请确保这个 Listener 放置在首位 -->
<listener>
<listener-class>org.geektimes.projects.user.web.listener.ComponentContextInitializerListener</listener-class>
</listener>
Expand Down Expand Up @@ -54,7 +54,7 @@
<filter-name>CharsetEncodingFilter</filter-name>
<filter-class>org.geektimes.projects.user.web.filter.CharsetEncodingFilter</filter-class>
<init-param>
<!-- Filter ���� = FilterConfig -->
<!-- Filter 配置 = FilterConfig -->
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
Expand Down Expand Up @@ -94,6 +94,7 @@
<welcome-file>/index.jsp</welcome-file>
</welcome-file-list>


<!-- <resource-ref>-->
<!-- <description>DB Connection</description>-->
<!-- &lt;!&ndash; JNDI javax.naming.Name &ndash;&gt;-->
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,36 @@
<body>
<div class="container-lg">
<!-- Content here -->
Hello,World 2021
<h3>用户注册</h3>
<form action="/user_web/register/doRegister" method="get"><table>
<!-- form创建表单,method:提交方式 -->
<!-- class="right" (选择表格的元素)-->
<tr>
<td class="right">用户名:</td>
<td><input type="text" name="uName"/></td>
</tr>
<tr>
<td class="right">密码:</td>
<td><input type="password" name="uPwd"/>
</td>
</tr>
<%-- <tr>--%>
<%-- <td class="right">确认密码:</td>--%>
<%-- <td> <input type="password" name="uRepwd"/></td>--%>
<%-- </tr>--%>
<%-- <tr>--%>
<%-- <td class="right">性别:</td>--%>
<%-- <td>--%>
<%-- <input type="radio" name="uSex" value="男" checked="checked"/>男 <!-- checked="checked"默认选择项 -->--%>
<%-- <input type="radio" name="uSex" value="女" /> 女--%>
<%-- </td>--%>
<%-- </tr>--%>
<tr><td class="right">手机号码:</td><td><input type="text" name="uPhone"/></td></tr>
<tr><td class="right">电子邮箱:</td><td><input type="text" name="uEmail"/></td></tr>
<tr><td></td><td><input type="submit" value="注册"/><input type="reset" value="重置"></td> </tr>

</table>
</form>

</div>
</body>
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
<head>
<jsp:directive.include
file="/WEB-INF/jsp/prelude/include-head-meta.jspf" />
<title>My Home Page</title>
</head>
<body>
<div class="container-lg">
<!-- Content here -->
<h3>注册成功!</h3>

</div>
</body>