Following the submission of data Part -jquery ajax Benpian submitted to the database query using ajax

  Part talked about how to use jquery ajax to submit data to the background, the background to receive and returned to ajax. https://www.cnblogs.com/tiezhuxiong/p/11943328.html

      Today, we transmit the data to a database query to do it. Man of few words said on the tutorial.

      First, let's establish a database:

 

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');

 

  

 

 

 

       Database to get the next step, into eclipse edit java code, the students, to keep up, to keep up.

  Today, based on the last of three built a foundation last package, and import a mysql ancestral jar package:

 

 

 

     

      We first create a package named User in po java class (class name casually set their own, as long as they can recognize just fine), and set the three fields in the class to create three fields get, set method:

 

 

 

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({
	        type: 'POST', 
	        URL: '$ {} pageContext.request.contextPath / login', 
	        // where / login annotation corresponding to the class LoginServlet = urlPatterns "/ login" 
	        Data: { 'the userName': the userName, 'password ': password}, 
	        Traditional: to true, 
	        the async: to false,       
	       dataType:' text ', 
	        success: function (Data) {// event successful 
	        	Alert (Data); 
	        }, 
	        error: function (Data) {// event of failure 
	        	Alert (Data); 
	        } 
	    });    
} 
</ Script> 
</ body> 
</ HTML>

  All set! Try running up the code.

 

 

 

 

The tutorial is over, thank you watch, if there are questions, welcome message comment section oh ~

 

 

Guess you like

Origin www.cnblogs.com/tiezhuxiong/p/11954117.html