html、java、mysql数据交互
此⽂⽤于java学习,在此⼩记。
在此之前有写过⼀些⼩的Java Demo,由于时间隔得⽐较长故⽽淡忘了,重新拾起。
环境的安装
开发环境:Win7(x64)+MyEclipse 2014+Mysql5.5.34+Navicat
MyEclipse 2014的安装和破解⽹上有很多资料,可⾃⾏查,这⾥不再过多叙述。我这⾥安装的是myeclipse-pro-2014-GA-offline-installer-windows,破解⽂件⽤的是Myeclipse-2014-破解⽂件。顺便安装了⼀个webstrom,编辑jsp,xml,html⾮常⽅便。
Mysql的安装⽹上也有许多⽂档,最新版本的安装与之前的有⼀些差异,这个个⼈爱好。Mysql5.5.34,顺便安装了⼀个数据库管理⼯具Navicat。
数据库的建⽴
mysql数据库安装以后,在系统环境中添加相应的路径,具体查看相关的资料。运⾏,使⽤命令mysql -h localhost -u username -p password,显⽰mysql的版本后表⽰mysql的环境安装成功。
如图,点击连接测试,如果配置正常,则返回成功。
创建数据库test_db,创建表fruits
填充数据
建⽴WebProject⼯程
在MyEclipse下建⽴Web Project⼯程,默认有index.jsp和l(WEB-INF下)两个⽂件,新建两个package,com.add以及com.query,在这两个package下分别新建Servlet,相应的配置会⾃动添加到l中,
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="/2001/XMLSchema-instance"
xmlns="java.sun/xml/ns/javaee"
xsi:schemaLocation="java.sun/xml/ns/javaee
java.sun/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the description of my J2EE component</display-name>
<servlet-name>addServlet</servlet-name>
<servlet-class>com.add.addServlet</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>SearchEmployee</servlet-name>
<servlet-class>com.query.SearchEmployee</servlet-class>
</servlet>
<servlet>
<description>This is the description of my J2EE component</description>
<display-name>This is the display name of my J2EE component</display-name>
<servlet-name>DeptList</servlet-name>
<servlet-class>com.query.DeptList</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>addServlet</servlet-name>
<url-pattern>/servlet/addServlet</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>SearchEmployee</servlet-name>
<url-pattern>/servlet/SearchEmployee</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>DeptList</servlet-name>
<url-pattern>/servlet/DeptList</url-pattern>
</servlet-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
</web-app>
然后添加相应的实现功能,
数据库添加数据:addServlet.java
package com.add;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import wset.serial.SerialException;
public class addServlet extends HttpServlet{
/**
* Constructor of the object.
*/
public addServlet(){
super();
}
/**
* DEstruction of the servlet
*/
public void destory(){
super.destroy();
}
/**
*
*/
public void doGet(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
//        try{
response.setContentType("text/html;charset=gb2312");
PrintWriter out = Writer();
this.doPost(request, response);
out.flush();
out.close();
//            String f_id,f_name,tmp_id,tmp_price;
//            int s_id;
//            float f_price;
//
//            f_id = Parameter("f_id");
//            f_name = Parameter("f_name");
//
//            tmp_id = Parameter("s_id");
//            tmp_price = Parameter("f_price");
//
//            s_id = Integer.parseInt(tmp_id);
//            f_price = Float.parseFloat(tmp_price);
//        }
//        catch(Exception ex){
//            ex.printStackTrace();
/
/        }
}
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException,IOException{
System.out.println("到了Servlet");
response.setContentType("text/html;charset=gb2312");
request.setCharacterEncoding("gb2312");
PrintWriter out = Writer();
String f_id = Parameter("f_id");
String str_id = Parameter("s_id");
String f_name = Parameter("f_name");
String str_price = Parameter("f_price");
int s_id = Integer.parseInt(str_id);
float f_price = Float.parseFloat(str_price);
Connection  conn = null;
PreparedStatement pstmt = null;
try{
Class.forName("sql.jdbc.Driver");
System.out.println("创建驱动成功!");
//连接数据库
conn = Connection("jdbc:mysql://localhost:3306/test_db","root",                    "123456");
System.out.println("连接数据库成功!");
//插⼊数据的SQL语句
String sql = "INSERT INTO fruits(f_id,s_id,f_name,f_price) VALUES(?,?,?,?)";
pstmt = conn.prepareStatement(sql);
//设置插⼊数据的顺序
pstmt.setString(1, f_id);
pstmt.setInt(2,s_id);
pstmt.setString(3, f_name);
pstmt.setFloat(4, f_price);
int result = uteUpdate();
//判断执⾏结果
if(1 == result){
out.println("插⼊数据成功!");
}else{
out.println("插⼊数据库失败!请重新插⼊!");
}
}catch(ClassNotFoundException e)
{
e.printStackTrace();
}catch(SQLException ex){
ex.printStackTrace();
}
}
public void init() throws ServletException{
}
private String convertToChinese(String source)
{
String s = "";
try{
s = new Bytes("ISO8859_1"));
}
catch(java.io.UnsupportedEncodingException ex)
{
ex.printStackTrace();
}
return s;
}
}
相对应的html⽂件:add.html
<!DOCTYPE html>
<html>
<head>
<title>简单的⽔果表单</title>
<meta http-equiv="keywords" content="keyword1,keyword2,keyword3">
<meta http-equiv="descripttion" content="this is my page">
<meta http-equiv="content-type" content="text/html; charset=GB2312">
</head>
<body>
<form action="localhost:8080/JavaServlet/servlet/addServlet" method="post"> <table border="0" cellpadding="3">
<tr>
<td>⽔果简称代号:</td>
<td><input type="text" name="f_id"></td>
</tr>
<tr>
<td>⽔果编号:</td>
<td><input type="text" name="s_id"></td>
</tr>
<tr>
<td>⽔果名称:</td>
<td><input type="text" name="f_name"></td>
<tr>
<td>⽔果价格:</td>
<td><input type="text" name="f_price"></td>
</tr>
<tr>
<td align="center" colspan="2">
<input type="submit" value="提交">
<input type="reset" value="重置">
</td>
</tr>
</table>
</form>
</body>
</html>
查SearchEmployee.java
package com.query;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class SearchEmployee extends HttpServlet {
/**
* Constructor of the object.
*/
public SearchEmployee() {
html实现用户注册登录代码super();
}
/**
* Destruction of the servlet. <br>
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/
**
* The doGet method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to get.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
response.setCharacterEncoding("gb2312");
PrintWriter out = Writer();
String f_name = Parameter("f_name");
Connection conn = null;
PreparedStatement pstmt = null;
ResultSet rs = null;
try{
Class.forName("sql.jdbc.Driver");
System.out.println("创建驱动成功!");
}catch(Exception e){
System.out.println("Class Not found");
}
//连接数据库
conn = Connection("jdbc:mysql://localhost:3306/test_db","root",                    "123456");
System.out.println("连接数据库成功!");
String sql = "SELECT * FROM fruits WHERE f_name = ?";
pstmt = conn.prepareStatement(sql);
pstmt.setString(1, f_name);
rs = uteQuery();
}catch(SQLException ex){
ex.printStackTrace();
}
try{
()){
out.println("⽔果简称代号:"+rs.getString(1)+"    </br>");
out.println("⽔果编号:"+rs.getString(2)+"    </br>");
out.println("⽔果名称:"+rs.getString(3)+"    </br>");
out.println("⽔果价格:"+rs.getString(4)+"    </br>");
}
}catch(SQLException e){
e.printStackTrace();
}
out.flush();
out.close();
}
/**
* The doPost method of the servlet. <br>
*
* This method is called when a form has its tag value method equals to post.
*
* @param request the request send by the client to the server
* @param response the response send by the server to the client
* @throws ServletException if an error occurred
* @throws IOException if an error occurred
*/
public void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
response.setContentType("text/html;charset=gb2312");
request.setCharacterEncoding("gb2312");
PrintWriter out = Writer();
this.doGet(request, response);
out.flush();
out.close();
}
/**
* Initialization of the servlet. <br>
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
查询功能DeptList.java
package com.query;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。