🍁用户登录
🔥流程说明:
用户填写用户名密码,提交到LoginServlet,在LoginServlet使用 MyBatis查询数据库,验证用户名密码是否正确,如果正确,响应“登录成功”,如果错误,响应“登录失败”,准备环境,写静态页面到webapp目录下,创建servlet数据库,创建tb_user表,创建User实体类,导入MyBatis坐标,MySQL驱动坐标,创建mybatis-config.xml核心配置文件,UserMapper.xml映射文件,UserMapper接口。
🔥SQL表
数据库使名称为mybatis,表名为tb_user。
自己添加几条数据即可。
🔥表单页面
写在webapp包下:
🔥login.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<meta charset="utf-8" />
<title>Register</title>
<link rel="stylesheet" type="text/css" href="./css/register.css"/>
</head>
<body>
<form action="/loginServlet" method="get">
<p class="head">登陆</p>
<input id="user" name="username" type="text" placeholder="用户名:"><br>
<input id="paws" name="password" type="password" placeholder="密 码:"><br>
<input id="sub" type="submit" value="登陆"/>
</form>
<script src="./js/register.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
🔥 js包下的register.js
var from = document.querySelector('form');
console.log(from);
window.addEventListener('load',function(){
from.className=('show'+' from')
})
🔥css包下的register.css
*{
margin: 0;
padding: 0;
border: 0px;
}
body{
background-color: #87CEEB;
}
form{
position: absolute;
left: 50%;
top: 50%;
margin-left: -300px;
margin-top: -280px;
width: 600px;
height: 400px;
background-color: #87CEEB;
border: 1px solid;
border-radius: 10px;
box-shadow: 0px 0px 5px 5px rgba(0,0,0,.3);
transition: all 1s;
opacity: 0;
}
.show{
opacity: 1;
transform:translateY(80px)
}
.head{
width: 100%;
font-family: "隶书";
text-align: center;
font-size: 24px;
color: #ffffff;
margin-top: 50px;
letter-spacing: 5px;
}
#user{
position: absolute;
top: 40%;
left: 50%;
margin-left: -100px;
width: 200px;
height: 20px;
outline: none;
background-color: transparent;
border-bottom: 1px solid;
}
#paws{
position: absolute;
top: 50%;
left: 50%;
margin-left: -100px;
width: 200px;
height: 20px;
outline: none;
background-color: transparent;
border-bottom: 1px solid;
}
#sub{
position: absolute;
top: 60%;
left: 50%;
margin-left: -60px;
width: 120px;
height: 35px;
background-color: orange;
border-radius: 8px;
}
#sub:hover{
cursor: pointer;
background-color: #87CEEB;
}
🔥User实体类
User实体类在com.jkj.pojo下:
🔥user
package com.jkj.pojo;
public class User {
private Integer id;
private String username;
private String password;
public User() {
}
public User(Integer id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Integer getId() {
return id;
}
public void setId(Integer 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) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
🔥导入MyBatis坐标、MySQL驱动坐标
mybatis-config.xml核心配置文件放入到resources目录下。
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>Test</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<build>
<plugins>
<plugin>
<groupId>org.apache.tomcat.maven</groupId>
<artifactId>tomcat7-maven-plugin</artifactId>
<version>2.2</version>
</plugin>
</plugins>
</build>
<dependencies>
<!--mysql driver-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.16</version>
</dependency>
<!--mybatis-->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.6</version>
</dependency>
<!--junit-->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
<scope>provided</scope>
</dependency>
</dependencies>
</project>
🔥mybatis-config.xml核心配置文件
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.jkj.pojo"/>
</typeAliases>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/mybatis?useSSL=false&useServerPrepStates=true"/>
<property name="username" value="root"/>
<property name="password" value="root"/>
</dataSource>
</environment>
</environments>
<mappers>
<package name="com.jkj.mapper"/>
</mappers>
</configuration>
🔥创建UserMapper接口
package com.jkj.mapper;
import com.jkj.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
//根据用户名和密码查询用户对象
User select(@Param("username") String username,@Param("password") String password);
}
注意:此步骤要先连接数据库。具体可以参考:在IDEA中连接数据库详细步骤
🔥UserMapper.xml
resources目录下建立com.jkj.mapper包映射,注意创建目录使用 /。
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jkj.mapper.UserMapper">
<select id="select" resultType="User">
select * from tb_user where username=#{username} and password=#{password}
</select>
</mapper>
🔥LoginServlet
创建在web包下:
package com.jkj.web;
import com.jkj.mapper.UserMapper;
import com.jkj.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
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;
import java.io.InputStream;
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//获取用户名和密码
String username = req.getParameter("username");
String password = req.getParameter("password");
//2.调用MyBatis完成查询
//2.1获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.2获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//2.3获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//2.4调用方法
User user = userMapper.select(username, password);
//2.5释放资源
sqlSession.close();
//获取字符输出流,并设置content type
resp.setContentType("text/html;charset=utf-8");
//判断user是否为空
if (user !=null){
resp.getWriter().write("登录成功!");
}
else {
resp.getWriter().write("登录失败!");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}
🔥.运行结果:
🔥登录页面
🔥登录成功页面
🍁注册功能
🔥流程说明
- 用户填写用户名、密码等信息、点击注册按钮,提交到RegisterServlet。
- 在RegisterServlet中使用MyBatis 保存数据。
- 保存前,需要判断用户名是否已经存在,如存在跳转到登录页面,不存在就去注册。
🔥resgister表单
写在webapp包下:
🔥register.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<title>Register</title>
<link rel="stylesheet" type="text/css" href="./css/register.css"/>
</head>
<body>
<form action="/registerServlet" method="post">
<p class="head">注册</p>
<input id="user" name="username" type="text" placeholder="用户名:"><br>
<input id="paws" name="password" type="password" placeholder="密 码:"><br>
<input id="sub" type="submit" value="注册"/>
</form>
<script src="./js/register.js" type="text/javascript" charset="utf-8"></script>
</body>
</html>
🔥UserMapper.java
package com.jkj.mapper;
import com.jkj.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
//根据用户名和密码查询用户对象
User select(@Param("username") String username,@Param("password") String password);
//根据用户名查找对象
User selectByUserName(String username);
//添加用户
void add(User user);
}
🔥UserMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.jkj.mapper.UserMapper">
<!--登录-->
<select id="select" resultType="User">
select * from tb_user where username=#{username} and password=#{password}
</select>
<!--注册-->
<select id="selectByUserName" resultType="User">
select * from tb_user where username=#{username}
</select>
<insert id="add">
insert into tb_user values (null ,username=#{username},password=#{password})
</insert>
</mapper>
🔥RegisterServlet.java
在com.jkj.web包下创建RegisterServlet.java
package com.jkj.web;
import com.jkj.mapper.UserMapper;
import com.jkj.pojo.User;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
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;
import java.io.InputStream;
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收参数
String username = req.getParameter("username");
String password = req.getParameter("password");
//封装对象
User user=new User();
user.setUsername(username);
user.setPassword(password);
//2.调用MyBatis完成查询
//2.1获取SqlSessionFactory对象
String resource = "mybatis-config.xml";
InputStream inputStream = Resources.getResourceAsStream(resource);
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.2获取SqlSession对象
SqlSession sqlSession = sqlSessionFactory.openSession();
//2.3获取Mapper
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//调用方法
User u = userMapper.selectByUserName(username);
//设置utf-8编码格式以及识别html标签
resp.setContentType("text/html;charset=utf-8");
//判断u是否为空
if (u ==null){
//为空,添加用户信息
userMapper.add(user);
//提交事务
sqlSession.commit();
//释放资源
sqlSession.close();
//注册成功,后续可以跳转到首页
resp.getWriter().write("注册成功!");
}
else {
//用户已存在,跳转到登录页面
req.getRequestDispatcher("/login.jsp").forward(req,resp);
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
this.doGet(req, resp);
}
}