我有一个问题,我有一个非常简单的scriplet代码来从数据库中检索数据,然后在图表上绘制它。我应该考虑将该代码更改为servlet吗? 这是代码:
<%
int sum=0;
int all=0;
int userID=-1;
int EcimNum=0;
int CommNum=0;
int AppNum=0;
int InstNum=0;
String connectionURL = "jdbc:mysql://localhost:3306/imf_jsp";
Connection connection = null;
PreparedStatement st;
ResultSet rs = null;
Class.forName("com.mysql.jdbc.Driver").newInstance();
connection = DriverManager.getConnection(connectionURL, "root", "");
if(!connection.isClosed())
{
st = connection.prepareStatement("SELECT * FROM user WHERE signum = ?"); //Find user with given username & pass
st.setString(1, session.getAttribute("username").toString());//Bind param (Should prevent SQL Injection? Not sure but it is working in PHP with PDO)
st.execute();//statemant execution
rs = st.getResultSet();
if(rs.next()){
userID = rs.getInt("id");//If not then check in LDAP
}
}
st = connection.prepareStatement("SELECT COUNT(*) FROM model INNER JOIN user ON model.user_id=user.id WHERE model_type='ECIM' AND user.id = ?" );
st.setInt(1, userID);
st.execute();
rs = st.getResultSet();
if(rs.next()){
EcimNum = rs.getInt("COUNT(*)");//If not then check in LDAP
System.out.println(EcimNum);
sum+=EcimNum;
}
st = connection.prepareStatement("SELECT COUNT(*) FROM model INNER JOIN user ON model.user_id=user.id WHERE model_type='Common' AND user.id = ?");
st.setInt(1, userID);
st.execute();
rs = st.getResultSet();
if(rs.next()){
CommNum = rs.getInt("COUNT(*)");//If not then check in LDAP
System.out.println(CommNum);
sum+=CommNum;
}
st = connection.prepareStatement("SELECT COUNT(*) FROM model INNER JOIN user ON model.user_id=user.id WHERE model_type='Application' AND user.id = ?");
st.setInt(1, userID);
st.execute();
rs = st.getResultSet();
if(rs.next()){
AppNum = rs.getInt("COUNT(*)");//If not then check in LDAP
System.out.println(AppNum);
sum+=AppNum;
}
st = connection.prepareStatement("SELECT COUNT(*) FROM model INNER JOIN user ON model.user_id=user.id WHERE model_type='Instance' AND user.id = ?");
st.setInt(1, userID);
st.execute();
rs = st.getResultSet();
if(rs.next()){
InstNum = rs.getInt("COUNT(*)");//If not then check in LDAP
System.out.println(InstNum);
sum+=InstNum;
}
st = connection.prepareStatement("SELECT COUNT(*) FROM model ");
st.execute();
rs = st.getResultSet();
if(rs.next()){
all = rs.getInt("COUNT(*)");//If not then check in LDAP
System.out.println(all);
}
%>
<p>User Name: ${username} <br>Number Of Models Upladed: <% out.print(sum); %></br>Procentage of total:<%out.print((sum*100)/all); %>%</p>
这个问题有什么更好的解决方案?单页面做的唯一事情就是为单个用户获取数据。但是在未来我正在计划管理版本,管理员将能够看到所有用户的统计数据。告诉我你怎么看?
答案 0 :(得分:0)
是的,您已经做出正确的决定将您的逻辑移动到servlet。 Scriptlet很糟糕,业务逻辑不应该紧密耦合到表示层。在两种情况下(查看单个用户数据/许多用户数据),您可以执行业务逻辑,一旦在servlet代码中有数据,就可以将它们设置为POJO对象的集合,如ArrayList<User>
实例中的您可以设置User
个对象。准备好集合后,可以按request.setAttribute(#LIST_OBJ);
进行设置,然后将其发送回响应中。要迭代列表,可以使用JSTL在JSP中显示它们