簡體   English   中英

使用 DAO 從 Java 類向 jsp 頁面傳遞值

[英]passing value to a jsp page from a java class using DAO

我想將在 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();
    }       

    }
}

謝謝...

如果您使用的是前端控制器[spring mvc],則可以通過執行model.addAttribute(“ variable_name”,data);來傳遞數據。 在jsp中,您可以通過執行此$ {variable_name}來訪問它;

如果您使用的是簡單的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>

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;
  }

}

在字符串中獲取查詢結果后,可以在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 ,您可以重定向到所需的任何頁面。

您需要像下面這樣從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;
    }
}

希望這會幫助你。

類似的東西

觀察這個導入 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>

豆子或模型

包豆;

// 將 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;  
    }  
    
    
}

另一個例子這個 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>

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM