如何使用servlets和java正确显示Mysql表?

时间:2013-09-05 07:08:00

标签: java mysql jsp servlets

我是新手。我有一个需要连接mysql,servlet和java的任务(因为我想分开java代码和html代码。以前,我结合代码使它更容易被拒绝) 所以,基本上,在mySql中我写这个,

create table login2 (username varchar (30), password varchar(30), designation varchar(10));
insert into login2 values('lala','123','A');

我使用eclipse在servlet中创建loginDisp.java。这是我的命令

 package Servlet;

import java.io.*;
import java.util.*;
import javax.sql.*;
import javax.servlet.*;
import javax.servlet.http.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class loginDisp extends HttpServlet {
  public void service(HttpServletRequest request,
  HttpServletResponse response)
  throws IOException, ServletException{
    //  String username=request.getParameter("Username");
     // String password=request.getParameter("Password");

  response.setContentType("text/html");
  PrintWriter out = response.getWriter();
  out.println("<html>");
  out.println("<head><title>Servlet JDBC</title></head>");
  out.println("<body>");
  out.println("<h1>Servlet JDBC</h1>");
  out.println("</body></html>");  
  // connecting to database
  Connection con = null;  
  Statement stmt = null;
  ResultSet rs = null;
  try {
  Class.forName("com.mysql.jdbc.Driver");
  con =DriverManager.getConnection 
  ("url/tablename","uname","pssword");
  stmt = con.createStatement();
  rs = stmt.executeQuery("SELECT * FROM login2");
  // displaying records
  while(rs.next()){
  out.print(rs.getObject(1).toString());
  out.print("\t\t\t");
  out.print(rs.getObject(2).toString());
  out.print("<br>");
  }

  } catch (SQLException e) {
 throw new ServletException("Servlet Could not display records.", e);
  } catch (ClassNotFoundException e) {
  throw new ServletException("JDBC Driver not found.", e);
  } finally {
  try {
  if(rs != null) {
  rs.close();
  rs = null;
  }
  if(stmt != null) {
  stmt.close();
  stmt = null;
  }
  if(con != null) {
  con.close();
  con = null;
  }
  } catch (SQLException e) {}
  }
  out.close();
  }
  }

执行时,显示效果很好。因此,我开始制作Login.jsp,因为我想创建一个text.box供用户插入用户名和密码。这是我的代码

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

<body>
<center>
    <div class="wrapper">
    <br>
    <br>
    <h2>Doctor</h2>

    <form name="form1" method="post" action="loginDisp" > <!-- onsubmit="return validateForm()" -->
        <table width="326" border="1" align="center">
        <center> <tr>
                <th width="138" scope="row">Username</th>
                <td width="142"><input type="text" name="Username"></td>

            </tr>
            </center>


            <tr>
                <th height="31" style="width: 162px;"><span class="style2">Password</span>
                </th>

                <td width="142"><input type="password" name="Password"></td>
            </tr>

            <tr>


            </tr>
        </table>
        <p align="center">
                    <input type="submit" name="Submit" value="Submit">
                </p> ${message}
    </form>
    </div>
    </center>

</body>

</body>
</html>

我从mySQL中显示数据。我在servlet中添加了另一个log.java,因为我想当我们需要从jsp获取数据到数据库并在被调用时显示。这是log.java中的代码

package Servlet;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class log extends HttpServlet {
  protected void processRequest(HttpServletRequest request, HttpServletResponse response)
    throws ServletException, IOException {

 //Get username and password from the JSP page


String username=request.getParameter("Username");
String password=request.getParameter("Password");

//Print the above got values in console

System.out.println("The username is" +username);

System.out.println("\nand the password is" +password);
    }
}

在login.jsp中插入的用户名和密码不会自动插入mySQL中,因此当我尝试执行loginDisp.java时,它只显示我在mySQL中手动插入的数据。

3 个答案:

答案 0 :(得分:3)

您不能将java文件名用作web.xml文件中定义的操作,并且有servlet映射,您可以使用

  <servlet>
    <servlet-name>log</servlet-name>
    <servlet-class>loginDisplay</servlet-class>
  </servlet>
  <servlet-mapping>
    <servlet-name>log</servlet-name>
    <url-pattern>/loginDisplay</url-pattern>
  </servlet-mapping>

现在您可以在操作代码中使用action = "loginDisplay"并使用此

我希望你没有遇到404 error的问题。

答案 1 :(得分:1)

您在表单中输入了错误的操作。

由于form的action属性采用servlet的路径,你应该给出web.xml中指定的relavent映射

action="loginDisplay.java"  

应为action="/loginDisplay"

<form name="form1" method="post" action="loginDisplay.java" onsubmit="return validateForm()">

应该是

<form name="form1" method="post" action="/loginDisplay" onsubmit="return validateForm()">

如果/loginDisplay不是web.xml中的确切映射,请检查web.xml文件并查看loginDisplay的映射并将该路径作为操作。

A quick example

答案 2 :(得分:0)

创建一个新包(称为dao或model),您可以在其中放置逻辑以访问数据库。

然后创建一个Java Bean对象,用于存储数据库的结果,并在servlet中实现逻辑类,然后访问Bean的属性并在WEB中显示它。

包装模型: DaoAccess类(与DB连接的方法) class Login(带有getXXX的表的属性和每个的setXXX)

包Servlet。 class loginDisplay:

    public class loginDisplay extends HttpServlet {
    public void service(HttpServletRequest request, HttpServletResponse response)
            throws IOException, ServletException {
        response.setContentType("text/html");
        PrintWriter out = response.getWriter();
        out.println("<html>");
        out.println("<head><title>Servlet JDBC</title></head>");
        out.println("<body>");
        out.println("<h1>loginDisplay</h1>");
        out.println("</body></html>");
        // connecting to database
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        DaoAccess dao = new DaoAccess();

        List<Login> list = dao.readAll();

        for(Login obj: list){
            out.write(obj.getName());
            out.write(obj.getPassword());
        }
        out.close();
    }
}