前端页面(login.jsp)
<%--
Created by IntelliJ IDEA.
User: Administrator
Date: 2019/8/12
Time: 15:39
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登录</title>
</head>
<body>
<form method="post" action="LoginServlet">
用户名:<input type="text" name="sname"><br>
密码:<input type="password" name="spwd"><br>
<input type="submit" value="注册">
</form>
</body>
</html>
javabean封装数据转换为Loginstudent 类型
package dao;
public class Loginstudent {
public String name;
public String pwd;
public Loginstudent(){
}
public Loginstudent(String name, String pwd) {
this.name = name;
this.pwd = pwd;
}
public String getName() {
return name;
}
public String getPwd() {
return pwd;
}
public void setName(String name) {
this.name = name;
}
public void setPwd(String pwd) {
this.pwd = pwd;
}
}
数据库处理
package dao;
import java.sql.*;
public class Login {
public void stulogin(Loginstudent stu){
final String URL="jdbc:sqlserver://localhost:1433;DatabaseName=student";
final String USERNAME="sa";
String PWD = "909911" ;
try {
//加载驱动创建连接
Class.forName("com.microsoft.sqlserver.jdbc.SQLServerDriver");
Connection connection = DriverManager.getConnection(URL ,USERNAME,PWD);
String sql="select count (*) from login where name = ? and pwd= ?";
PreparedStatement preparedStatement = connection.prepareStatement(sql);
preparedStatement.setString(1,stu.getName());
preparedStatement.setString(2,stu.getPwd());
ResultSet resultSet = preparedStatement.executeQuery();
if (resultSet.next()){
System.out.println("登陆成功");
}
}
catch (ClassNotFoundException e) {
e.printStackTrace();
}
catch ( Exception e) {
e.printStackTrace();
}
}
}
servlet连接前后端
package Servlet;
import dao.Login;
import dao.Loginstudent;
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 java.io.IOException;
@WebServlet( "/LoginServlet")
public class LoginServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//处理编码
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
response.setContentType("text/html;charset=UTF-8");
//获取前端的数据
String sname = request.getParameter("sname");
String spwd = request.getParameter("spwd");
//javaBean封装
Loginstudent loginstudent=new Loginstudent();
loginstudent.setName(sname);
loginstudent.setPwd(spwd);
//调用数据库执行
Login login = new Login();
login.stulogin(loginstudent);
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
完美。