为了账号安全,请及时绑定邮箱和手机立即绑定

在jsp中将Java和HTML分开?

在jsp中将Java和HTML分开?

慕的地8271018 2021-03-31 19:15:29
我想将Java代码(在servlet中)与html代码分开。此代码显示了jsp中mySql表的数据。不使用脚本的最佳实践是什么?谢谢你的帮助。<%   String id = request.getParameter("userId");   String driverName = "com.mysql.jdbc.Driver";   String connectionUrl = "jdbc:mysql://localhost/";   String dbName = "db";   String userId = "root";   String password = "root";   try {   Class.forName(driverName);   } catch (ClassNotFoundException e) {   e.printStackTrace();   }   Connection connection = null;   Statement statement = null;   ResultSet resultSet = null;%><table>   <td style="border:none"><a href="index.jsp" class="LinkButton">home</a> <br></td>   <tr>      <th>id</th>      <th>Data</th>      .....   </tr>   <%      try{       connection = DriverManager.getConnection(connectionUrl+dbName, userId, password);      statement=connection.createStatement();      String sql ="SELECT * FROM table";      resultSet = statement.executeQuery(sql);      while(resultSet.next()){   %>   <tr>      <td><%=resultSet.getString("id") %></td>      <td><%=resultSet.getString("Data") %></td>      ...   </tr>   <%       }      } catch (Exception e) {      e.printStackTrace();      }   %></table>
查看完整描述

3 回答

?
当年话下

TA贡献1890条经验 获得超9个赞

使用Get方法和servlet。您可以在servlet中编写所有Java代码,如下所示:


public void doGet (HttpServletRequest request, HttpServletResponse response) 

  throws IOException, ServletException {

    String driverName = "com.mysql.jdbc.Driver";

    String connectionUrl = "jdbc:mysql://localhost/";

    String dbName = "db";

    String userId = "root";

    String password = "root";


    try {

       Class.forName(driverName);

     } catch (ClassNotFoundException e) {

          e.printStackTrace();

    }


    Connection connection = null;

    Statement statement = null;

    ResultSet resultSet = null; 

    try{ 

    connection = DriverManager.getConnection(connectionUrl+dbName, userId, password);

    statement=connection.createStatement();

    String sql ="SELECT * FROM table";

    resultSet = statement.executeQuery(sql);

    // Now convert this result set into a class having field id and data..

    // like MyClass{ String id; String data;}

    // make a list of List<MyClass>list = new ArrayList<>();

    request.setAttribute("list",list); 

    this.getServletContext().getRequestDispatcher("/jsp/yourPageName.jsp").

   include(request, response);

 }

现在,使用在您的jsp文件中获取名为“ list”的此属性request.getAttribute("list");。将其输入列表。并对其进行迭代并进行相应的打印。


查看完整回答
反对 回复 2021-04-14
?
Smart猫小萌

TA贡献1911条经验 获得超7个赞

即使没有Scriptlet或JSTL,也无法循环While,即使您可以将数据库获取作业放入servlet中也是如此。

如果要删除任何服务器端脚本,则需要将体系结构分为两层。

  1. 服务器端:servlet或JSP获取数据库并生成JSON或CSV

  2. 客户端:html用AJAX调用服务器端以获取加载时的纯数据,然后使用javascript循环

并且您不使用数据库连接池,而是直接建立数据库连接。挺贵的 如果忘记关闭连接,则可能会耗尽资源。非常危险。


查看完整回答
反对 回复 2021-04-14
  • 3 回答
  • 0 关注
  • 216 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信