如何使用servlets和java正确显示Mysql表?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18629900/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to properly display Mysql tables using servlets and java?
提问by hana
I am newbie here. I have an assignment that requires to connect mysql, servlet and java (because i want to separate java code and html code. Previously, i combined the codes to make it easier and was rejected) So, basically, in mySql i write this,
我是这里的新手。我有一个任务需要连接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');
and i create loginDisp.java in the servlet using eclipse. This is my command
我使用 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();
}
}
When i execute, it is well displayed. Hence, i started to make the Login.jsp as i want to make a text.box for user to insert username and password. This is my code
当我执行时,它显示得很好。因此,我开始制作 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>
and I get the data from mySQL displayed. I add another log.java in servlet because i thought when we need a data fetched from jsp to databased and displayed when be called. This is code in log.java
我从显示的 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);
}
}
The username and password inserted in login.jsp does not inserted automatically in mySQL, hence when i try to executed loginDisp.java , it will display only the data i inserted manually in mySQL.
在 login.jsp 中插入的用户名和密码不会自动插入到 mySQL 中,因此当我尝试执行 loginDisp.java 时,它只会显示我在 mySQL 中手动插入的数据。
采纳答案by Suresh Atta
You entered a wrong action in form.
您在表单中输入了错误的操作。
Since form's action attribute takes the path of the servlet you should give the relavent mapping specified in web.xml
由于表单的 action 属性采用 servlet 的路径,因此您应该提供指定的相关映射 web.xml
action="loginDisplay.java"
should be action="/loginDisplay"
应该 action="/loginDisplay"
<form name="form1" method="post" action="loginDisplay.java" onsubmit="return validateForm()">
It should be
它应该是
<form name="form1" method="post" action="/loginDisplay" onsubmit="return validateForm()">
If /loginDisplay
is not the exact mapping in your web.xml check the web.xml file and see the mapping for loginDisplay and give that path as action.
如果/loginDisplay
不是您的 web.xml 中的确切映射,请检查 web.xml 文件并查看 loginDisplay 的映射并将该路径作为操作提供。
回答by Shivam
You can not use the java file name as action this is defined in the web.xml file and there is servlet mapping and you can use
您不能使用 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>
and now you can use the action = "loginDisplay"
in the action tag and by using this
现在你可以action = "loginDisplay"
在动作标签中使用
I hope you did not face the problem of 404 error
.
我希望你没有遇到404 error
.
回答by Elorry
Create a new package (called dao or model) where you put your logic to access to the DB.
创建一个新包(称为 dao 或模型),在其中放置访问数据库的逻辑。
Then create a Java Bean Object where store the results of your DB and instanciate your class of the logic in the servlet, then access to the properties of the Bean and show it in the WEB.
然后创建一个 Java Bean 对象,其中存储您的 DB 的结果并在 servlet 中实例化您的逻辑类,然后访问 Bean 的属性并将其显示在 WEB 中。
package model: class DaoAccess (methods to connect with DB) class Login (properties of the table with getXXX and setXXX of each one)
包模型: class DaoAccess(与DB连接的方法) class Login(表的属性分别带有getXXX和setXXX)
package Servlet. class loginDisplay:
封装 Servlet。类登录显示:
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();
}
}