Benpianは、AJAXを使用してデータベースクエリに提出されたデータパート-jquery AJAXの提出に続いて

  パートは、使用方法について話しましたjqueryのAJAXを背景に受け取るために、バックグラウンドにデータを提出するとAjaxに戻りました。https://www.cnblogs.com/tiezhuxiong/p/11943328.html

      今日、我々はそれを行うには、データベースのクエリにデータを送信します。いくつかの単語の男は、チュートリアルにしました。

      まずは、データベースを構築してみましょう:

 

CREATE TABLEの`user`(
   ` id`のint(11)NOT NULL AUTO_INCREMENT、
   `username` VARCHAR(255)のDEFAULT NULL、
   ` password` VARCHAR(255)のDEFAULT NULL、
   PRIMARY KEY( `id`) 

 

  

 

             

INSERT INTO `user`.`user`(` id`、 `username`、` password`)VALUES(NULL、 '铁柱兄'、 '666666')。

 

  

 

 

 

       データベースに追いつくために、追いつくために、学生、日食の編集Javaコードに、次のステップを取得します。

  今日では、3の最後に基づいて、最後のパッケージ基盤を構築し、mysqlの先祖のjarパッケージをインポートします。

 

 

 

     

      我々は最初のPO Javaクラスのユーザー(クラス名何気なく限り、彼らはうまく認識できるよう、自分自身を設定します)という名前のパッケージを作成し、そして、三つのフィールドが取得セットメソッドを作成するクラスに三つのフィールドを設定します。

 

 

 

package com.tiezhu.po;

public class User {
 private int id;//用户的唯一标识
 private String userName;//用户登录的账号(用户名)
 private String Password;//密码
public int getId() {
	return id;
}
public void setId(int id) {
	this.id = id;
}
public String getUserName() {
	return userName;
}
public void setUserName(String userName) {
	this.userName = userName;
}
public String getPassword() {
	return Password;
}
public void setPassword(String password) {
	Password = password;
}
 
}

 

  

 

 

 搞定User类之后,我们去serveice包里创建LoginServeice类,再去dao包里创建LoginDao类:

 

 

 

  回到我们上次创建的LoginServlet类里:

package com.tiezhu.action;

import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.tiezhu.po.User;
import com.tiezhu.service.LoginServeice;

@WebServlet(name="LoginServlet",urlPatterns="/login")
public class LoginServlet extends HttpServlet{

/**
*
*/
private static final long serialVersionUID = 1L;

@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
    // TODO Auto-generated method stub
    super.doGet(req, resp);
}

@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
      //处理编码格式
      req.setCharacterEncoding("UTF-8");
      resp.setContentType("html/text;charset=UTF-8");
      //接受前端传来的数据
      String userName=req.getParameter("userName");
      String password=req.getParameter("password");
      System.out.println("接收到前端传来的数据:userName="+userName+"password="+password);
      //new出user对象
      User user=new User();
      //new出loginservice对象
      LoginServeice loginservice=new LoginServeice();
      //在loginservice里创建login方法,并把user,userName和password塞进login方法里
      user=loginservice.login(userName,password);

      //对user进行判断有没有值
      if(user!=null){
      resp.getWriter().print("查询成功");System.out.println("1");
      }else{
      System.out.println("0");
      resp.getWriter().print("用户不存在");
            }

      }

}

  

 这时候第40行的user=loginservice.login(userName,password);中的login会报错,这是因为这个方法在loginservice中还不存在。

 把鼠标放到login上面,第一个提示工具就会自动给我们去创建这个方法了。

 

 

 

现在我们进入LoginServeic类里,继续我们的代码:

 

package com.tiezhu.service;

import org.apache.tomcat.jni.User;

import com.tiezhu.dao.LoginDao;

public class LoginServeice {

	public User login(String userName, String password) {
          User user=null; //new出dao对象 LoginDao dao=new LoginDao(); //在dao里创建login方法,并把userName和password塞进login方法里 user=dao.login(userName,password);//这个时候代码会走进dao层,等dao层里的login方法走完,回来再走return return user; } }

 

  这个时候user=dao.login(user,userName,password);里的login会报错,还是用同样的方法,鼠标放上去,根据提示,点击第一个提示,工具自动在dao里给我们创建好login方法。

    现在不急着去编写LoginDao类。我们先在dao包里创建一个BaseDao的java类。

 

 

 

package com.tiezhu.dao;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class baseDao {
	//mysql驱动包
	private static String driver="com.mysql.jdbc.Driver";
	//数据库地址,3306是端口号,user是数据库的库名
	private static String url="jdbc:mysql://localhost:3306/user";
	//数据库账号
	private static String user="root";
	//数据库密码
	private static String password="root";
	//sql连接
	Connection conn = null;
	
	/**
	 * 建立连接
	 */
	public Connection getConnection(){
		//如果conn为空,则去建立连接
		if(conn==null){
			try {
				//1.加载驱动
				Class.forName(driver);System.out.println("加载驱动成功");
				//2.建立连接
				conn=DriverManager.getConnection(url, user, password);System.out.println("建立连接中...");
			} catch (Exception e) {
				e.printStackTrace();
			}
			
		}
		System.out.println("连接数据库成功");
		return conn;
		
	}
	/**
	 * 关闭连接
	 */
	public void closeAll(Connection conn,PreparedStatement pstm,ResultSet rs){
		if(rs!=null){
			try {
				rs.close();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(pstm!=null){
			try {
				pstm.close();System.out.println("关闭pstm成功");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		if(conn!=null){
			try {
				conn.close();System.out.println("关闭conn成功");
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
	}
}

 

  友情提示:baseDao打的所有包必须是sql的不要去打其他的包,要不然就报错。

  现在我们去LoginDao里去:

 

 

 

package com.tiezhu.dao;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

import com.tiezhu.po.User;

 

public class LoginDao extends baseDao{

public User login( String userName, String password) {
    //这里定义了user,给后面用的
    User user=null;
    //1定义Connection
    Connection conn = null;
    //2.定义PreparedStatement
    PreparedStatement pstm = null;
    //3.查询需定义ResultSet
    ResultSet rs = null;

    try {
      conn=this.getConnection();
      String sql="select * from user where username='"+userName+"' and password='"+password+"'";
      pstm = conn.prepareStatement(sql);
      System.out.println(sql);
      rs=pstm.executeQuery();
      while (rs.next()) {
      //在这里new出了user,给下面要把从数据中查询出来的值set进user里面
      user=new User();
      //从数据库查询出来的set进user类
      user.setId(rs.getInt("id"));
      user.setUserName(rs.getString("username"));
      user.setPassword(rs.getString("password"));
      System.out.println(user.getUserName());
        }
    System.out.println("dao层走到尽头,把user送回service层");
      } catch (SQLException e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
      }finally {
      this.closeAll(rs,conn, pstm);//释放数据连接
    }
    //将user返回到service层里。
    return user;
   }

}

  JAVA类搞定!我们回到jsp界面,在这里我要跟大家道个歉,因为上次写的太快了,没注意jsp写错了,现在在这里纠正一下:

    上次的错误点,我把上传的userName加了引号,导致最后后台得到数据就是userName,而不是用户输入的值,也同时提醒一下大家以后写代码的时候细心一点哦(现在已经改回来了)

 

 

  这次我们的jsp中ajax有一些变动,代码贴出来:

 

 

 

 

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!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=UTF-8">
<script src="https://cdn.staticfile.org/jquery/2.1.1/jquery.min.js"></script>
<title>Insert title here</title>
</head>
<body>
<input type="text" id="userName"/>
<input type="text" id="password"/>
<a onclick="btnConfirm()">点我提交</a>
<script type="text/javascript">

function btnConfirm(){//a标签中的点击事件
	var userName=$("#userName").val();//通过id获取输入框中用户输入的值
	var password=$("#password").val();
	 $.ajax({
	        タイプ: 'POST'、
	        URL: '$ {} pageContext.request.contextPath /ログイン'、
	        // /ログイン注釈クラスに対応するがloginservlet = urlPatterns "/ログイン" 
	        データ:{ 'ユーザー名':ユーザー名、「パスワード':パスワード}、
	        伝統:真、と
	        非同期:falseに、       
	       データ型:'テキスト」、
	        成功:機能(データ){//イベントの成功
	        	アラート(データ); 
	        }、
	        エラー:失敗の機能(データ){//イベント
	        	アラート(データ); 
	        } 
	    });    
} 
</ SCRIPT> 
</ BODY> 
</ HTML>

  すべてのセット!コードを実行してみてください。

 

 

 

 

チュートリアルでは、質問がある場合は、見て感謝、終わって、歓迎のメッセージコメントセクションああ〜

 

 

おすすめ

転載: www.cnblogs.com/tiezhuxiong/p/11954117.html