【问题标题】:passing value to a jsp page from a java class using DAO使用DAO将值从java类传递给jsp页面
【发布时间】:2014-06-21 07:29:05
【问题描述】:

我想将在 java 类中检索到的值传递给页面。我正在使用 DAO 类。 我已经从数据库中检索了值并将它们存储在字符串变量中。现在我想将它们设置到我的 view.jsp 页面中的文本框。我是这个领域的新手,谁能帮帮我吗??

View.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
        pageEncoding="ISO-8859-1"%>
    <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
    <html>
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
    <title>Insert title here</title>
    </head>
    <body>

    <form action="process.jsp">
    Enter Name    <br/> <br> <input type="text" name="uname"  onclick="this.value=''"/><br/><br/>

    <input type="submit" value="view details"/><br/><br/>
    Email id:   <br/> <input type="text"  name="email"  id="email" > <br/><br/>
    password:   <br/> <input type="text"  name="passw"  id="passw"><br/><br/>

    </form>        
    </body>
    </html>

我的活动 ViewDAO.java

 public static void  view(user u) {
    Connection con=ConnectionProvider.getCon(); 
    String uname=u.getUname();
    try {
        PreparedStatement ps=con.prepareStatement("select email,pass from  S1.USER432 where name='"+uname+"'");
        ResultSet rs = ps.executeQuery();       

        while (rs.next()) {

            String email = rs.getString("EMAIL");
            String pass = rs.getString("PASS");

            }

    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       

    }
}

谢谢...

【问题讨论】:

  • 您可以通过传递 email 的值并传递给 servlet 并显示为 html 页面来做到这一点。
  • @Ajeesh 我正在尝试使用 DAO 来完成这项任务。不过谢谢...
  • 程序流程应该就像您从 view.jsp 获取值并将其传递给 servlet 然后从 servlet 您需要调用 ViewDAO.java 方法然后将值返回给 servlet 并显示值作为一个 html 页面。

标签: java jsp dao


【解决方案1】:

如果您使用的是前端控制器[spring mvc],那么您可以通过以下方式传递数据, model.addAttribute("variable_name", data); 在jsp中你可以通过这样做 ${variable_name};

【讨论】:

  • 我这里没有使用spring。无论如何,谢谢.. :)
【解决方案2】:

您需要从您的 servlet 中调用 DAO 方法,如下所示:

    public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

      // call DAO method to get the email and password
    HashMap<String,String> map=ViewDAO.getDetails();

    //from the map you will get the  email and password.then you need to set them in the attributes and get them in your jsp

     request.setAttribute("email", map.get("email"));
      request.setAttribute("password", map.get("password"));

}

您的 DAO 方法应如下所示:

public static HashMap<String,String>  getDetails(user u) {
    Connection con=ConnectionProvider.getCon(); 
    String uname=u.getUname();
    Map<String,String> map=new HashMap<>();
    try {
        PreparedStatement ps=con.prepareStatement("select email,pass from  S1.USER432 where name='"+uname+"'");
        ResultSet rs = ps.executeQuery();       

        while (rs.next()) {

            String email = rs.getString("EMAIL");
            String pass = rs.getString("PASS");

            }
       map.put("email",email);
       map.put("password",pass);


    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }       
    return map;
    }
}

希望这会对你有所帮助。

【讨论】:

    【解决方案3】:

    如果你使用的是简单的jsp和servelt,那就制作一个ViewController.java。

    您可以使用两种方法,一种用于处理 GET,另一种用于处理 POST

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
            try {
                String email = request.getParameter("email");
                String password = request.getParameter("password");
    
        request.setAttribute("email", email);
                request.setAttribute("password", password);
                            request.getRequestDispatcher("view.jsp").forward(request, response);
             }
            catch(Exception e){
    
    
            }
    

    View.jsp

    <%@ page language="java" contentType="text/html; charset=ISO-8859-1"
            pageEncoding="ISO-8859-1"%>
        <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
        <html>
        <head>
        <meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
        <title>Insert title here</title>
        </head>
        <body>
    
        <form action="process.jsp">
        Enter Name    <br/> <br> <input type="text" name="uname"  onclick="this.value=''"/><br/><br/>
    
        <input type="submit" value="view details"/><br/><br/>
        Email id:   <br/> <input type="text"  name="email"  id="email" value="<%=email%>" > <br/><br/>
        password:   <br/> <input type="text"  name="passw"  id="passw" value="<%=password%>"><br/><br/>
    
    
        </form>
    
        </body>
        </html>
    

    【讨论】:

    • 谢谢..我尝试了这段代码,它运行良好..但如果有人帮助我使用 DAO 做同样的事情,我将非常感激
    • @user3548232 DAO是一个普通的java类,所以你不能在那里设置参数来获取它们在你的jsp中。所以你需要借助servlet来做到这一点。
    • @Ganesh 你能举个例子吗?
    • @user3548232 我在答案中提供了示例。检查一下。
    【解决方案4】:

    Servlet 决定必须加载哪个页面。因此,无论您从 DAO 获得什么,都必须进入 Servlet,并通过它进入 jsp。您可以使用 bean 类将值从 DAO 发送到 Servlet。 像这样,

    public class Details{
      private String email;
      private String password;
    
      public void setEmail(String email){
        this.email = email;
    
      }
      public void setPassword(String password){
        this.password= password;
    
      }
      public String getEmail(){
         return this.email;
      }
      public String getPassword(){
         return this.password;
      }
    
    }
    

    并且在获取String中的查询结果后,可以在DAO中进行如下修改。添加这些

    Details d = new Details();
    d.setEmail(email);
    d.setPassword(pass);
    return d;
    

    您可以将此对象 d 传递给 servlet 并使用 bean 的 getter 方法检索值。此外,必须从 Servlet 调用 DAO。 现在在 Servlet 方面。

    在 Servlet 上,您可以根据需要将代码放入 get 或 post 方法中。可能是这样的

    public class ExampleServlet extends HttpServlet{
    
    protected void doPost(HttpServletRequest request,
            HttpServletResponse response) throws ServletException, IOException {
    
    String email = request.getParameter("email"); //got from the jsp where "email" is the name attribute of the input field
    Details d = new Details();
    d = ViewDao.view(user_object); //the bean sent by DAO. "user_object" is parameter that your DAO method is taking in your code
    
    if(d.getEmail()!=null){ //just an example
    
     // your code that redirects desired page
    }
    
    }
    }
    

    根据 DAO 返回的d,您可以重定向到您想要的任何页面。

    【讨论】:

      【解决方案5】:

      类似的东西

      观察这个导入 dao.UserDao,bean.*,

      • dao 是包
      • UserDao 是类
      • bean 是你想要的方法,或者是来自 dao 的属性

      记住

      jsp

      <body>  
        
      <%@page import="dao.UserDao,bean.*,java.util.*"%>  
      <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>  
        
      <h1>Users List</h1>  
        
      <%  
      List<User> list=UserDao.getAllRecords();  
      request.setAttribute("list",list);  
      %>  
       
      <div class="table-responsive">  
      <table class="table">  
          <thread class="bg-info">
              <th>Id</th><th>Name</th><th>Password</th><th>Edit</th><th>Delete</th>
          </thread>
              <c:forEach items="${list}" var="u">  
          <tr>
              <td>${u.getId()}</td><td>${u.getUsername()}</td><td>${u.getPassword()}</td> 
              <td><a href="editform.jsp?id=${u.getId()}">Edit</a></td>  
              <td><a href="deleteuser.jsp?id=${u.getId()}">Delete</a></td>
          </tr>  
              </c:forEach>  
      </table>  
      </div>
      <br/><a href="adduserform.jsp">Add New User</a>  
      
        <br>
        <br>
       <form action="index.jsp">
               <button type="submit">IndexUsers</button>
        </form>  
      </body>
      

      Bean 或模型

      包豆;

      // 类 para 为表格

      public class User {
      
          private int id;  
          private String username,password;
          
          public int getId() {
              return id;
          }
          public void setId(int id) {
              this.id = id;
          }
          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;
          } 
          
          
      }
      

      public class UserDao {
          public static Connection getConnection(){  
              Connection con=null;  
              try{  
                  Class.forName("com.mysql.cj.jdbc.Driver");  
                  con=DriverManager.getConnection("jdbc:mysql://localhost:3306/mysql_database","root","14570");  
              }catch(Exception e){System.out.println(e);}  
              return con;  
          }  
          public static int save(User u){  
              int status=0;  
              try{  
                  Connection con=getConnection();  
                  PreparedStatement ps=con.prepareStatement(  
          "insert into login(username,password) values(?,?)");  
                  ps.setString(1,u.getUsername());  
                  ps.setString(2,u.getPassword());  
                    
                  status=ps.executeUpdate();  
              }catch(Exception e){System.out.println(e);}  
              return status;  
          }  
          public static int update(User u){  
              int status=0;  
              try{  
                  Connection con=getConnection();  
                  PreparedStatement ps=con.prepareStatement(  
          "update login set username=?,password=? where id=?");  
                  ps.setString(1,u.getUsername());  
                  ps.setString(2,u.getPassword());  
                   
                  ps.setInt(3,u.getId());  
                  status=ps.executeUpdate();  
              }catch(Exception e){System.out.println(e);}  
              return status;  
          }  
          public static int delete(User u){  
              int status=0;  
              try{  
                  Connection con=getConnection();  
                  PreparedStatement ps=con.prepareStatement("delete from login where id=?");  
                  ps.setInt(1,u.getId());  
                  status=ps.executeUpdate();  
              }catch(Exception e){System.out.println(e);}  
            
              return status;  
          }  
          public static List<User> getAllRecords(){  
              List<User> list=new ArrayList<User>();  
                
              try{  
                  Connection con=getConnection();  
                  PreparedStatement ps=con.prepareStatement("select * from login");  
                  ResultSet rs=ps.executeQuery();  
                  while(rs.next()){  
                      User u=new User();  
                      u.setId(rs.getInt("id"));  
                      u.setUsername(rs.getString("username"));  
                      u.setPassword(rs.getString("password"));  
                       
                      list.add(u);  
                  }  
              }catch(Exception e){System.out.println(e);}  
              return list;  
          }  
          public static User getRecordById(int id){  
              User u=null;  
              try{  
                  Connection con=getConnection();  
                  PreparedStatement ps=con.prepareStatement("select * from login where id=?");  
                  ps.setInt(1,id);  
                  ResultSet rs=ps.executeQuery();  
                  while(rs.next()){  
                      u=new User();  
                      u.setId(rs.getInt("id"));  
                      u.setUsername(rs.getString("username"));  
                      u.setPassword(rs.getString("password"));  
                       
                  }  
              }catch(Exception e){System.out.println(e);}  
              return u;  
          }  
          
          
      }
      

      【讨论】:

        【解决方案6】:

        另一个示例,此 import import="dao.*"% 使包 dao 中的任何方法都可用,下面您将了解如何在 dao 中获取方法 countid() 的结果。

        <%@page import="dao.*"%>
        
        <%@page import="java.sql.DriverManager"%>
        <%@page import="java.sql.ResultSet"%>
        <%@page import="java.sql.Connection"%>
        <%@page contentType="text/html" pageEncoding="UTF-8"%>
        <% int id = 0; %>
        <%
        DaoEvento daoEvento = new DaoEvento();
        id = daoEvento.countId();
        %>
        
        <!DOCTYPE html>
        <html>
        <head>
                <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
                <title>JSP Page</title>
        </head>
            <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/css/bootstrap.min.css" integrity="sha384-zCbKRCUGaJDkqS1kPbPd7TveP5iyJE0EjAuZQTgFLD2ylzuqKfdKlfG/eSrtxUkn" crossorigin="anonymous">
        <body>
                <br><br>
                <form action="add_event_servletnew" method="POST">
        
                        <div class="form-group">
                         <td>
                            <font color='green' face = "Arial" size = "4">
                            <%= request.getParameter("message") %>
                            </font>
        
                            &nbsp; &nbsp;&nbsp; &nbsp; 
                            <a href="view_event.jsp">view</a>
                         <td>
                         </div>
        
        
                            <div class="form-group">
                                <label>id</label>
                                <input type="text" name="id" value="<%= id%>" readonly="readonly" class="form-control"/>
                            </div>
                            <div class="form-group">
                                <label>Title</label>
                                <input type="text" name="title" value="" class="form-control" />
                            </div>
                            <div class="form-group">
                                <label>Start</label>
                                <input type="date" name="start" value="" class="form-control"/>
                            </div>
                            <div class="form-group">
                                <label>End</label>
                                <input type="date" name="end" value="" class="form-control" />
                            </div>
                            <div class="form-group">
                                <td><input type="submit" value="submit" class="btn btn-success btn-block"/></td>
                            </div>
        
        
                </form>
        
        </body>
            <script src="https://cdn.jsdelivr.net/npm/jquery@3.5.1/dist/jquery.slim.min.js" integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj" crossorigin="anonymous"></script>
        <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.1/dist/js/bootstrap.bundle.min.js" integrity="sha384-fQybjgWLrvvRgtW6bFlB7jaZrFsaBXjsOMm/tB9LTS58ONXgqbR9W8oWht/amnpF" crossorigin="anonymous"></script>
        <script src="jquery.mask.min.js"> </script>
        </html>
        

        【讨论】:

          猜你喜欢
          • 2015-02-06
          • 2018-05-01
          • 1970-01-01
          • 2018-08-16
          • 2013-11-23
          • 2011-07-19
          • 1970-01-01
          • 2012-03-29
          • 1970-01-01
          相关资源
          最近更新 更多