我是创建Java Rest Web服务的新手,如果我做对了,我会感到困惑。我想要的是为我的所有方法的每次调用建立一个连接。通过参数发送连接是最佳实践吗?如果能的话,请赐教我并提供一些建议/示例代码。
感谢您的帮助。
@GET
@Path("BasicInfo/{id}")
// Method to get basic information
private BasicInfo getBasicInfo(@PathParam("id") String pid)
{
Connection con = null;
PreparedStatement ps = null;
List<BasicInfo> info = new ArrayList<>();
try {
String qry = "SELECT firstname, municipal_id FROM user_tbl WHERE id = ?";
String username = "test";
String password = "test";
con = DB.getConnection(username, password);
ps = con.prepareStatement(qry);
ps.setString(1, pid);
ResultSet rs = ps.executeQuery();
while (rs.next()) {
String firstname = rs.getString("firstname");
String municipal_id = rs.getString("municipal_id");
String municipal_name = Fx.getMunicipalInfo(con, municipal_id);
BasicInfo bInfo = new BasicInfo();
bInfo.setFirstname( firstname );
bInfo.setMunicipality_name( municipal_name );
info.add(bInfo);
}
} catch(SQLException | NullPointerException e) {
//logger.log(Level.SEVERE, "Error : ", e.getMessage());
} finally {
try {
if (ps != null) { ps.close(); }
if (con != null) { con.close(); }
} catch(SQLException sqlex) {}
}
return details;
}
// functions
public class Fx {
public String getMunicipalInfo(Connection con, String pmunicipalId)
{
//Connection con = null;
PreparedStatement ps = null;
String municipalityName = "";
try {
String qry = "SELECT municipal_name FROM municipality WHERE id = ?";
//con = DB.getConnection();
ps = con.prepareStatement(qry);
ps.setString(1, pmunicipalId);
ResultSet rs = ps.executeQuery();
if (rs.next()) {
municipalityName = rs.getString("municipal_name ");
}
} catch(SQLException | NullPointerException e) {
//logger.log(Level.SEVERE, "Error : ", e.getMessage());
} finally {
try {
if (ps != null) { ps.close(); }
//if (con != null) { con.close(); }
} catch(SQLException sqlex) {}
}
return municipalityName ;
}
}
// getter and setter
public class BasicInfo {
private String firstname;
private String municipality_name;
public String getFirstname() {
return firstname;
}
public void setFirstname(String firstname) {
this.firstname = firstname;
}
public String getMunicipality_name() {
return municipality_name;
}
public void setMunicipality_name(String municipality_name) {
this.municipality_name = municipality_name;
}
}
// Class for database connection
public class DB {
private static final Logger logger = Logger.getLogger("DB");
public static Connection getConnection(String username, String password)
{
Connection connection = null;
try {
Context initcontext = new InitialContext();
Context envcontext = (Context) initcontext.lookup("java:/comp/env");
DataSource ds = (DataSource) envcontext.lookup("jndi/ds");
connection = ds.getConnection(username, password);
} catch (Exception e) {
logger.log(Level.SEVERE, "Error {0}", e.getMessage());
}
return connection;
}
}