效果
Maven 依赖
<dependency><groupId>javax.servlet</groupId><artifactId>javax.servlet-api</artifactId><version>3.1.0</version></dependency><dependency><groupId>mysql</groupId><artifactId>mysql-connector-java</artifactId><version>5.1.6</version></dependency><dependency><groupId>com.google.code.gson</groupId><artifactId>gson</artifactId><version>2.8.5</version></dependency><dependency><groupId>net.sf.json-lib</groupId><artifactId>json-lib</artifactId><version>2.4</version><classifier>jdk15</classifier></dependency>
创建数据库表
create table user(
id int NOT NULL AUTO_INCREMENT,
username char(255) NOT NULL,
password char(255) NOT NULL ,
PRIMARY KEY (id)
)ENGINE=InnoDB;
html代码
<!DOCTYPE html>
<html lang="en">
<head><meta charset="UTF-8"><title>登录</title><link rel="stylesheet" href="style.css">
</head>
<body>
<div class="main"><div><input type="text" id="username" placeholder="请输入账号"></div><div><input type="password" id="password" placeholder="请输入密码"></div><div>登录</div>
</div><script>var username = document.querySelector("#username")var password = document.querySelector("#password")var btn = document.querySelector(".main>div:nth-child(3)")var xmlHttpRequest = new XMLHttpRequest();var mainDiv = document.querySelector(".main");btn.addEventListener("click", function (ev) {if(document.querySelector(".pd")!=null){mainDiv.removeChild(document.querySelector(".pd"));}var json = {username: username.value,password: password.value,flag: false}//console.log(ev)xmlHttpRequest.open("POST", "/ajax/from", true)xmlHttpRequest.setRequestHeader("Content-type", "application/x-www-form-urlencoded");//将json对象转换成字符串传输至后台xmlHttpRequest.send(JSON.stringify(json));xmlHttpRequest.onreadystatechange = function () {if (xmlHttpRequest.status == 200 && xmlHttpRequest.readyState == 4) {var data = xmlHttpRequest.responseText;console.log(data);//将json字符串转换成对象var parse = JSON.parse(data);console.log(parse)if (parse.flag == true) {var div = document.createElement("div");div.className="pd"div.innerHTML = `<h3>用户登录成功,欢迎${parse.username}</h3>`mainDiv.appendChild(div);} else if (parse.flag == false) {var div = document.createElement("div");div.className="pd"div.innerHTML = "<h3>用户登录失败,账号或密码有误</h3>"mainDiv.appendChild(div);}}}})
</script>
</body>
</html>
Servlet代码
package com.dao;import com.domain.user;
import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.util.JDBCutil;import javax.servlet.ServletException;
import javax.servlet.ServletInputStream;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;@WebServlet(urlPatterns = "/from")
public class from extends HttpServlet {@Overrideprotected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {request.setCharacterEncoding("utf-8");response.setContentType("text/html;charset=utf-8");response.setCharacterEncoding("utf-8");final PrintWriter out = response.getWriter();final ServletInputStream inputStream = request.getInputStream();final BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "utf-8"));final StringBuilder stringBuilder = new StringBuilder();String len=null;while((len=reader.readLine())!=null){//System.out.println(len);stringBuilder.append(len);}String json=stringBuilder.toString().trim();//System.out.println("json= "+json);final GsonBuilder gsonBuilder = new GsonBuilder();final Gson gson = gsonBuilder.create();final user user = gson.fromJson(json, com.domain.user.class);System.out.println(user);final JDBCutil jdbCutil = new JDBCutil();if(jdbCutil.login(user)){user.setFlag(true);}System.out.println(gson.toJson(user));out.println(gson.toJson(user));out.close();}
}
User
package com.domain;public class user {private String username;private String password;private boolean flag;public boolean isFlag() {return flag;}@Overridepublic String toString() {return "user{" +"username='" + username + '\'' +", password='" + password + '\'' +", flag=" + flag +'}';}public void setFlag(boolean flag) {this.flag = flag;}public String getUsername() {return username;}public void setUsername(String username) {this.username = username;}public String getPassword() {return password;}public void setPassword(String password) {this.password = password;}}
JDBC
package com.util;import java.sql.*;public class JDBCutil {private Connection cn=null;private PreparedStatement st =null;private ResultSet set=null;private String url="jdbc:mysql://localhost:3306/zlfsql";private String user="root";private String password="feng10.10";public Connection getConection() {Connection c=null;try {Class.forName("com.mysql.jdbc.Driver");c=DriverManager.getConnection(url,user,password);}catch (SQLException | ClassNotFoundException e){e.printStackTrace();}return c;}public boolean login(com.domain.user ur){if(ur.getUsername()==null || ur.getPassword()==null || ur.getUsername().length()<1 || ur.getPassword().length()<1){return false;}cn = getConection();try{st=cn.prepareStatement("select * from user where username=? and password=? ");//System.out.println(ur.getUsername()+ " &&&"+ur.getPassword());st.setString(1,ur.getUsername());st.setString(2,ur.getPassword());set = st.executeQuery();return set.next();}catch (SQLException e){e.printStackTrace();}return false;}
}
主要是复习一下之前学过的知识。