写JavaWeb的准备工作:
首先准备好数据库和Myeclipse,这里以mysql为例,再下载好SQL的图形化操作界面SQLyog,在数据库中建张表 。
详细步骤:
在Myeclipse 中新建一个Web工程:
在src下建三个包ServletPackge,ModelPackage,TestPackage.
分别存放即将要创建的Servlet,和通过java连接数据库对数据库进行基本操作的java程序和测试程序。
导jar包:
将mysql-connector-java-5.0.3-bin .jar包导入到 WEN-INF下的lib文件夹,右击build path将包添加到Referenced Libraries下呈奶瓶状。
在ModelPackage中写入:
代码:add.java主要是向是数据库中添加数据
package Mod;
import java.sql.DriverManager;
import java.sql.SQLException;
public class add {
public static void main(String[] args) {
final String driver ="com.mysql.jdbc.Driver";
final String url ="jdbc:mysql://localhost:3306/students";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
try {
java.sql.Connection conn = DriverManager.getConnection(url,"root","1234");
String sql ="insert into student(name) value=(?)";
java.sql.PreparedStatement pst =conn.prepareStatement(sql);
pst.setString(1, "benben");
System.out.println("完成");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
DBOperator.java主要是对数据库的连接操作:
package Mod;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
public class DBOperator {
private static final String driver ="com.mysql.jdbc.Driver";
private static final String url ="jdbc:mysql://localhost:3306/students";
static{
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static Connection getConnection() {
Connection conn =null;
try {
conn =(Connection) DriverManager.getConnection(url,"root","1234");
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return conn;
}
public static void close(ResultSet rs, Statement st, Connection conn)
{
try
{
if(rs != null)
{
rs.close();
}
if(st != null)
{
st.close();
}
if(conn != null)
{
conn.close();
}
}catch(Exception ex)
{
ex.printStackTrace();
}
}
public static void close(Statement st, Connection conn)
{
close(null,st,conn);
}
}
student.java存储学生的id,name,tel信息与数据库中相对应:
package Mod;
public class student {
private int id;
private String name;
private int tel;
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public int getTel() {
return tel;
}
public void setTel(int tel) {
this.tel = tel;
}
}
StudentManger.java这是一个接口 写入两个方法分别对应登录时使用的checkLogin和注册时用的add方法。
public interface StudentManger {
public boolean add(student S);
public boolean checkLogin(int tel, String name);
}
StudentMangerImpl 是上面接口的实现方法:
package Mod;
import java.sql.SQLException;
//import com.mysql.jdbc.ResultSet;
public class StudentMangerImpl implements StudentManger {
public boolean add(student S) {
boolean flag = false;
java.sql.Connection conn = null;
java.sql.PreparedStatement pst = null;
conn = DBOperator.getConnection();
String sql = "insert into student(name,tel) value(?,?) ";
try {
pst = conn.prepareStatement(sql);
pst.setString(1, S.getName());
pst.setInt(2, S.getTel());
int rows=pst.executeUpdate();
if(rows>0){
flag=true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return flag;
}
@Override
public boolean checkLogin(int tel, String name) {
boolean flag=false;
//student S = new student();
java.sql.Connection conn = null;
java.sql.Statement st =null;
java.sql.ResultSet rs = null;
try {
conn=DBOperator.getConnection();
String sql = "select * from student where tel="+tel;
st=conn.createStatement();
rs = st.executeQuery(sql);
while(rs.next()){
if(rs.getString("name").equals(name));
flag =true;
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
DBOperator.close(rs, st, conn);
}
return flag;
}
}
在TestPackage中写:
ConnectionTest.java对是否成功连接数据库进行测试:
import Mod.DBOperator;
public class ConnectionTest {
public static void main(String[] args) {
java.sql.Connection conn = DBOperator.getConnection();
if (conn != null) {
System.out.println("连接成功!");
}
}
}
在testStudent:
package Test;
import java.sql.DriverManager;
import java.sql.SQLException;
import Mod.DBOperator;
import Mod.StudentMangerImpl;
import Mod.student;
public class testStudent {
public static void main(String[] args) {
final String driver ="com.mysql.jdbc.Driver";
final String url ="jdbc:mysql://localhost:3306/students";
try {
Class.forName(driver);
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
DBOperator d= new DBOperator();
try {
java.sql.Connection conn = DriverManager.getConnection(url,"root","1234");
if(conn!=null){
System.out.println("链接成功");
}
else{
System.out.println("链接失败");
}
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
StudentMangerImpl N = new StudentMangerImpl();
student B =new student();
B.setId(6);
B.setName("yang");
B.setTel(5);
if(N.add(B)){
System.out.println("添加成功");
}
else{
System.out.println("添加失败");
}
StudentMangerImpl S = new StudentMangerImpl() ;
if(S.checkLogin(5, "yang")){
System.out.println("成功");
}
else{
System.out.println("失败");
}
}
}
JSP的创建:
在WebRoot下创建index.jsp,load.jsp,zhuce.jsp分别是一个跳转,一个登录界面和注册成功界面
index.jsp代码:
点击跳转
load.jsp代码:
在中添加
function reLoadCode(){
var t =new Date().getTime();
document.getElementById("imagecode").src="ImageServlet?t"+t;
}
在中写:
<h1>用户管理系统h1>
<form action="denglu" method="post">
学 号:<input name="id" type="text"><br/>
<p>p>
姓 名: <input name="name" type="text"><br/>
<p>p>
电 话: <input name="tel" type="text"><br/>
<p>p>
验证码:<input name="checkcode" type="text">
<p>p>
<img alt="验证码" src="ImageServlet" id = "imagecode">
<a href="javaScript:reLoadCode()">看不清a><br/>
<input type="submit" value="登录"> <a href ="Main.jsp">新用户a>
form>
center>
在注册页面写:
<form action="zhuce" method="post">
学 号:<input name="id" type="text"><br/>
<p>p>
姓 名: <input name="name" type="text"><br/>
<p>p>
电 话: <input name="tel" type="text"><br/> <p>p>
<input type="submit" value="注册">
form>
center>
其中action=”??”要与创建的servlet的URL地址相匹配:
每一个action 的值都要匹配一个一个servlet。
写Servlet:
load.java:
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Mod.StudentManger;
import Mod.StudentMangerImpl;
public class denglu extends HttpServlet {
/**
* Constructor of the object.
*/
public denglu() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* 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 {
doPost(request,response);
}
/**
* The doPost method of the servlet.
*
* 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 {
request.setCharacterEncoding("GB18030");
response.setCharacterEncoding("GB18030");
int tel = Integer.parseInt(request.getParameter("tel"));
String name = request.getParameter("name");
String checkcode = request.getParameter("checkcode");
String piccode = (String) request.getSession().getAttribute("piccode");
Mod.student S = new Mod.student();
StudentManger M = new StudentMangerImpl();
boolean flag ;
flag=M.checkLogin(tel, name);
if(flag==true&&checkcode.equalsIgnoreCase(piccode)){
response.sendRedirect("index.jsp");
}
else{
response.setContentType("textml");
PrintWriter out = response.getWriter();
out.print("失败!");
}
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
zhuce.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Mod.StudentManger;
import Mod.StudentMangerImpl;
import Mod.student;
public class zhuce extends HttpServlet {
/**
* Constructor of the object.
*/
public zhuce() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* 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 {
doPost(request,response);
}
/**
* The doPost method of the servlet.
*
* 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 {
request.setCharacterEncoding("GB18030");
response.setCharacterEncoding("GB18030");
StudentManger S = new StudentMangerImpl();
student M = new student();
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
int tel =Integer.parseInt(request.getParameter("tel"));
M.setId(id);
M.setName(name);
M.setTel(tel);
boolean flag = S.add(M);
if(flag ==true){
response.sendRedirect("load.jsp");
}
else{
response.setContentType("textml");
PrintWriter out = response.getWriter();
out.print("失败!");
}
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
ImageServlet.java
import java.io.IOException;
import java.io.PrintWriter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import Mod.StudentManger;
import Mod.StudentMangerImpl;
import Mod.student;
public class zhuce extends HttpServlet {
/**
* Constructor of the object.
*/
public zhuce() {
super();
}
/**
* Destruction of the servlet.
*/
public void destroy() {
super.destroy(); // Just puts "destroy" string in log
// Put your code here
}
/**
* The doGet method of the servlet.
*
* 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 {
doPost(request,response);
}
/**
* The doPost method of the servlet.
*
* 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 {
request.setCharacterEncoding("GB18030");
response.setCharacterEncoding("GB18030");
StudentManger S = new StudentMangerImpl();
student M = new student();
int id = Integer.parseInt(request.getParameter("id"));
String name = request.getParameter("name");
int tel =Integer.parseInt(request.getParameter("tel"));
M.setId(id);
M.setName(name);
M.setTel(tel);
boolean flag = S.add(M);
if(flag ==true){
response.sendRedirect("load.jsp");
}
else{
response.setContentType("textml");
PrintWriter out = response.getWriter();
out.print("失败!");
}
}
/**
* Initialization of the servlet.
*
* @throws ServletException if an error occurs
*/
public void init() throws ServletException {
// Put your code here
}
}
工作已经全部完成。