문제

I wanted to pass the value retrieved on a java class to a page.I am using DAO classes. I have retrieved the values from the database and stored them on String variables.Now I want to set them to the text boxes in my view.jsp page.I am new to this area,can anyone help me out??

View.jsp is as

<%@ 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>

and My Activity ViewDAO.java is as

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

    }
}

Thanks...

도움이 되었습니까?

해결책 2

You need to call the DAO method from your servlet like below:

    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"));

}

your DAO method should be like the below:

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

Hope this will help you.

다른 팁

If you are using a front controller[spring mvc] then you can pass the data by doing, model.addAttribute("variable_name ", data); and in the jsp you can access it by doing this ${variable_name};

if you are using simple jsp and servelt, then make one ViewController.java.

You can two methods one for handling GET and other for 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>

The Servlet decides which page must be loaded. So whatever you get from the DAO must go to the Servlet and through that, to the jsp. You can use a bean class to send values from DAO to Servlet. Like this,

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

}

And you can make the following changes in DAO after getting the query results in the String. Add these

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

You can pass this object d to the servlet and retrieve the values using the getter methods of the bean. Also, the DAO must be called from the Servlet. And now on the Servlet side.

On the Servlet you can put your code in the get or post method depending on your need. It may be like

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
}

}
}

Based on d returned by the DAO you may redirect to any page you want.

Something like that

Observe this import dao.UserDao,bean.*,

  • dao is the package
  • UserDao is the class
  • bean is the method you want or is could an attribute from dao

remember that

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 or model

package bean;

// classe para as tables

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

dao

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

Another Example this import import="dao.*"% makes available any methods from package dao, Bellow you see how to get the result of the method countid() in the dao.

<%@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 ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top