如何从oracle db中检索特定字段然后将其传递给jsp?

时间:2015-11-22 21:01:49

标签: java database class jsp

我想通过" name"将f.jsp形成为类s.java然后在s.java类中我需要从数据库中检索接收到的名称的年龄并将年龄发送到另一个jsp文件。 有人有想为此编写代码吗?

f.jsp

String name = (String) request.getAttribute("myname"); //get name from servlet 
Student s= new Student();
String grade = s.getStudentGrade(name);

s.java

 public String getStudentGrade(String name)
{
   Connection con = null;
    PreparedStatement s = null;
    String g;
    try {
        con = DBconn.getConnection();
        String query = "SELECT grade FROM REGISTRATION where Username="+name;
        s = con.prepareStatement(query);
        s.setString(1,""+this.getgrade());
        ResultSet result = s.executeQuery();
        while( result.next())
        {
         g=result.getString("grade");

        }
          return g;


    } 
    catch(Exception e) { e.printStackTrace(); return null; }
}

当我运行此代码时总是返回null..can任何人帮助我 提示:我的Db是 用户名密码等级 阿里1234 3 我需要getStudentGraed()接收名称,然后检索该名称的等级

2 个答案:

答案 0 :(得分:0)

对于PreparedStatement,您必须使用通配符吗?而不是与查询连接..

1: - 你必须扩展HttpServlet。

2: - 你必须定义@WebServlet注释,或者你必须在web.xml文件中声明你的servlet。

@WebServlet("/getGrade")  
public class getStudentGrade extends HttpServlet {

private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    Connection con = null;
    PreparedStatement s = null;
    String g;
    try {
       con = DBconn.getConnection();
       String query = "SELECT grade FROM REGISTRATION where Username=?";
       s = con.prepareStatement(query);
       s.setString(1, name);
       ResultSet result = s.executeQuery();
       while( result.next()){
         g=result.getString("grade");
       }
       req.setAttribute("grade",g);
       req.getRequestDispatcher(your Jsp Page path).forward(req,resp);

 }

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp)
        throws ServletException, IOException {
    doGet(req,resp);
}

}

在JSP页面中,你可以像

那样得到它
     <p>Grade : ${grade}</p>

答案 1 :(得分:0)

据我所知,你需要从jsp访问java类。我想以下示例将对您有所帮助。

public class Student {

private String name;

public String getGrade() {
    String grade = null;

    con = DBconn.getConnection();
    String query = "SELECT grade FROM REGISTRATION where Username=?";
    s = con.prepareStatement(query);
    s.setString(1,this.name);
    ResultSet result = s.executeQuery();
    while( result.next()){
     grade=result.getString("grade");}
    return grade;
}

public void setName(String name) {
    this.name = name;
}

}

在您的servlet中:

   <%
     package_name.Student c = new package_name.Student();
        c.setName("John");
        request.setAttribute("attribute", c);

    %>

在jsp中访问:

 ${requestScope["attribute"].grade}