JAVAweb项目详解(一):使用ajax和servlet与数据库交互,实现前后端登录跳转

本博客只供参考,如果有什么不懂的,务必把技术的每一个地方都落实。打好基础才能使用更好的处理使用框架后的一些处理不了的细节问题。博主自己敲的项目,为了积累一定的经验,以及提高自己的代码速度和问题的处理能力。


效果:

JAVAweb项目详解(一):使用ajax和servlet与数据库交互,实现前后端登录跳转_第1张图片

点击登录后进入——》

JAVAweb项目详解(一):使用ajax和servlet与数据库交互,实现前后端登录跳转_第2张图片

跳转到这个页面。

现在我们将讲述如何实现功能。


一、ajax向后端发送请求




优点:ajax传输其实是一种典型的部分传输的类型之一,使用ajax可以局部性的进行数据更新啊,能够根据数据库时刻更新局部值,也不会打破框架的方式。

缺点:就是代码量多,一旦请求的数据过多时,就会相当的难处理。


二、Servlet处理前台请求和链接数据库

原理:

1.接收前台的参数变量

2.后台写好数据库的链接和类及方法

3.定义sql语句字符串,调用数据库的方法,方法传的参数应该是String类型

4.得到的一堆的字符串返回给前台,此时应该也传入一个code码值,给前台识别

5.前台接收字符串,拆分后用数组接收,其中得到的值就是数据库的数据了


附代码:

 

Servlet

package com.web;

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 javax.servlet.http.HttpSession;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * Servlet implementation class Search
 */
@WebServlet("/Search")
public class Search extends HttpServlet {
	private static final long serialVersionUID = 1L;
       
    /**
     * @see HttpServlet#HttpServlet()
     */
    public Search() {
        super();
        // TODO Auto-generated constructor stub
    }

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub

	}

	/**
	 * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse response)
	 */
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// TODO Auto-generated method stub
		//response.getWriter().append("Served at: ").append(request.getContextPath());
		response.setCharacterEncoding("utf-8");
		response.setContentType("application/json;charset=utf-8");
		String account = request.getParameter("account");
		String password = request.getParameter("password");//获得前端的请求账号密码,变成参数


		List< Map > maplist = new ArrayList<>();
		String sqlget = "select * from login where account='" + account +"'and password="+ password ;
		System.out.println(sqlget);
		maplist = mysqlUtil.show(sqlget, MysqlConfig.login);				
		HttpSession session = request.getSession();	   
		String rep = "";
		if( maplist.size() > 0 ) {
			      		 rep = "{\"code\":\"200\",\"message\":\"你好访问成功了\",\"data\":[";		 
						 rep += "[" +"\""+maplist.get(0).get("id")+"\","+"\""+maplist.get(0).get("account") + "\"," + maplist.get(0).get("password") + "]";
						 rep += "]}";
					//	System.out.println(maplist.get(0).get("account"));
			 session.setAttribute("account",maplist.get(0).get("account"));
			//	System.out.println("sessionId:"+session.getId()+"account"+ session.getAttribute("account"));
		}else {
			rep = "{\"code\":\"999999\",\"message\":\"对不起,没有相匹配的数据\"}";
		}
		
		
		System.out.println(rep);
		response.getWriter().write(rep);


	}

}

Mysql链接

package com.web;

import java.sql.Connection;
import java.sql.DriverManager;

public class DBConnection {
		String driver = "com.mysql.jdbc.Driver";
	    String url= "jdbc:mysql://localhost:3306/car?useUnicode=true&characterEncoding=utf-8";
	    String user = "root";
	    String password = "";
	    
	    public Connection conn;

	    public DBConnection() {

	        try {
	            Class.forName(driver);
	            conn = (Connection) DriverManager.getConnection(url, user, password);// 杩炵画鏁版嵁搴�
	            
	            if(!conn.isClosed())
	                System.out.println("Succeeded connecting to the Database!"); 
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }
	    
	    public void close() {
	        try {
	            this.conn.close();
	        } catch (Exception e) {
	            e.printStackTrace();
	        }
	    }

}

Mysql的一些数组属性的定义

package com.web;

public class MysqlConfig {
	



	public final static String [] login = {"account","password"};
	

}

Mysql的方法定义

package com.web;

import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class mysqlUtil {

	public static void main(String[] args) {
		List< Map > maplist = new ArrayList<>();
		String sqlget = "select * from books";
		String[] params = { "bookId" ,"bookname","booktype","bookauthor"};
		maplist = show(sqlget, params);
		for(int i = 0; i < maplist.size(); i++) {
			String outstr = "id:" + maplist.get(i).get("bookId") + "||bookname:" + maplist.get(i).get("bookname");
			System.out.println(outstr);
		}

		
	}
	public static int add(String sql) {
        int i=0;
        DBConnection db = new DBConnection();
        try {        
            PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
            preStmt.executeUpdate();
            //Statement statement = (Statement) db.conn.createStatement();
            //statement.executeUpdate(sql);
            
            preStmt.close();
            db.close();//关闭连接 
            i = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return i;//返回影响的行数,1为执行成功;
    }
    //
	
	
	public static int add1(String sql) {
	    int i = 0 ;
        DBConnection db = new DBConnection();
        try {        
            PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
            preStmt.executeUpdate();
            //Statement statement = (Statement) db.conn.createStatement();
            //statement.executeUpdate(sql);
            
            preStmt.close();
            db.close();//关闭连接 ;
            i = 1;
        } catch (Exception e) {
            e.printStackTrace();
        }

		return i ;
    }
    public static void show(){
         String sql ="select * from books";
         DBConnection db = new DBConnection();
         
         System.out.println("-----------------");
         System.out.println("大家看一下我的图书");
         System.out.println("-----------------");
         
         try {
            Statement stmt = (Statement) db.conn.createStatement();
            ResultSet rs = (ResultSet) stmt.executeQuery(sql);
            while(rs.next()){
               
            	  String bookId = rs.getString("bookId");
            	String bookname = rs.getString("bookname");
                String booktype = rs.getString("booktype");
                String bookauthor = rs.getString("bookauthor");
                System.out.println(bookId +"\t"+ bookname +"\t"+ booktype+"\t"+bookauthor);
            }
            rs.close();
            db.close();//
        } catch (SQLException e) {
            e.printStackTrace();
        } 
    }
    public static String show1(String a){
        String sql ="select * from student where a=" + a;
        DBConnection db = new DBConnection(); 
        try {
           Statement stmt = (Statement) db.conn.createStatement();
           ResultSet rs = (ResultSet) stmt.executeQuery(sql);
           while(rs.next()){
              
           	  String brand = rs.getString("brand");
           	  String model = rs.getString("model");
               int Mileage = rs.getInt("Mileage");
               String ED = rs.getString("ED"); 
               String py = rs.getString("py"); 
               String dop = rs.getString("dop"); 
               String sqlgelr = "\""+brand+","+model+","+Mileage+","+ED+","+py+","+dop+"\"";
               return sqlgelr;
           }
           rs.close();
           db.close();//
       } catch (SQLException e) {
           e.printStackTrace();
       }
		return "123" ; 
   }
   
    public static int update(String sql) {
        int i =0;
        DBConnection db = new DBConnection();
        try {
            PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(sql);
            preStmt.executeUpdate();
            preStmt.close();
            db.close();
            i = 1;
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return i;
    }
    

    public static List< Map > show(String sql, String[] params){
        // String sql ="select * from employee";
    	
    	
    	List< Map > listmap = new ArrayList<>();
    	
         DBConnection db = new DBConnection();
         ResultSet rs = null;
         try {
            Statement stmt = (Statement) db.conn.createStatement();
            rs = (ResultSet) stmt.executeQuery(sql);
            while(rs.next()){
            	
            	Map map = new HashMap();
            	for(int i = 0; i < params.length; i++) {
            		
            		map.put(params[i], rs.getString(params[i]));
            	}
            	listmap.add(map);
            }
            rs.close();
            db.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
		return listmap;   
    }

    
  
    public static int del(String delstr) {
        int i=0;
        DBConnection db = new DBConnection();
        try {    
            PreparedStatement preStmt = (PreparedStatement) db.conn.prepareStatement(delstr);
            preStmt.executeUpdate();
            
            preStmt.close();
            db.close();
            i = 1;
        } catch (SQLException e){
            e.printStackTrace();
        }
        return i;
    }

}
	
	


谢谢大家

你可能感兴趣的:(JAVAweb项目详解(一):使用ajax和servlet与数据库交互,实现前后端登录跳转)