技术框架说明
前端技术:
- HTML:用于创建网页结构和内容的标记语言
- CSS:用于美化和样式化网页的样式表语言。
- JavaScript:用于实现网页的交互和动态效果
后端技术:
- Java:作为主要的后端编程语言,用于编写服务器端的逻辑代码
- Servlet: Java Web 技术,用于处理客户端请求和生成响应。
- MyBatis:Java的持久层框架,用于数据库操作和对象关系映射
- 数据库:用于存储和管理数据的技术,可以是关系型数据库(如MySQL、Oracle) 或非关系型数据库 (如MongoDB)。
登录案例
1.需求分析
需求分析
- 用户在登录页面输入用户名和密码,提交请求给LoginServlet
- 在LoginServlet中接收请求和数据[用户名和密码]
- 在LoginServlt中通过Mybatis实现调用UserMapper来根据用户名和密码查询数据库表
- 将查询的结果封装到User对象中进行返回
- 在LoginServlet中判断返回的User对象是否为null
- 如果为nul,说明根据用户名和密码没有查询到用户,则登录失败,返回"登录失败"数据给前端
- 如果不为null,则说明用户存在并且密码正确,则登录成功,返回"登录成功"数据给前端
2.环境准备
2.1 前端页面
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<link href="css/login.css" rel="stylesheet">
</head>
<body>
<div id="loginDiv">
<form action="" id="form">
<h1 id="loginMsg">LOGIN IN</h1>
<p>Username:<input id="username" name="username" type="text"></p>
<p>Password:<input id="password" name="password" type="password"></p>
<div id="subDiv">
<input type="submit" class="button" value="login up">
<input type="reset" class="button" value="reset">
<a href="register.html">没有账号?点击注册</a>
</div>
</form>
</div>
</body>
</html>
2.2 创建数据表及对应的实体类
创建数据库以及tb_user表 ,创建User实体类
-- 创建用户表
CREATE TABLE tb_user(
id int primary key auto_increment,
username varchar(20) unique,
password varchar(32)
);
-- 添加数据
INSERT INTO tb_user(username,password) values('zhangsan','123'),('lisi','234');
SELECT * FROM tb_user;
创建用户表
package com.itheima.pojo;
//用户实体类
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) {
this.password = password;
}
@Override
public String toString() {
return "User{" +
"id=" + id +
", username='" + username + '\'' +
", password='" + password + '\'' +
'}';
}
}
2.3 导入mybatis坐标,MySQL坐标
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.5</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.32</version>
</dependency>
2.4 配置文件及接口
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.itheima.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:///db1?useSSL=false&useServerPrepStmts=true"/>
<property name="username" value="root"/>
<property name="password" value="123456"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描mapper-->
<package name="com.itheima.mapper"/>
</mappers>
</configuration>
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.itheima.mapper.UserMapper">
</mapper>
UserMapper接口
package com.itheima.mapper;
public interface UserMapper {
}
3. 用户名密码校验
输入用户名和密码再到数据库中进行查询
步骤:
- 编写接口:Mapper接口
- 编写sql语句:sql映射文件
- 执行方法,测试
方法1:XML 或注解方式配置 SQL 查询语句
public interface UserMapper {
//使用 @Param 注解来指定参数的名称
User selectByNaPa(@Param("username") String username,@Param("password") String password);
}
<?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">
<!--
namespace:名称空间
-->
<mapper namespace="com.itheima.mapper.UserMapper">
<select id="selectByNaPa" resultType="com.itheima.pojo.User">
SELECT * FROM tb_user WHERE username = #{username} AND password = #{password};
</select>
</mapper>
package com.itheima;
import com.itheima.mapper.UserMapper;
import com.itheima.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 java.io.IOException;
import java.io.InputStream;
public class LodeTest1 {
public static void main(String[] args) throws IOException {
//1.传入参数
String un = "zhangsan";
String pw = "123";
//2.加载核心文件,获取SqlSessionFactory
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3. 获取对应的sqlsession,执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
//4. 执行sql
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectByNaPa(un, pw);
System.out.println(user);
//5.释放资源
sqlSession.close();
}
}
方法2:使用 @Select 注解来声明一个查询方法
代码片段使用注解方式,将 SQL 查询语句直接写在方法上,不需要额外的 XML 配置文件。
package com.itheima.mapper;
import com.itheima.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
@Select("select * from tb_user where username = #{username} and password = #{password}}}")
User selectByNaPa(@Param("username") String username, @Param("password") String password);
}
使用标签
package com.itheima.mapper;
import com.itheima.pojo.User;
import org.apache.ibatis.annotations.Param;
import org.apache.ibatis.annotations.Select;
public interface UserMapper {
@Select("select * from tb_user where username = #{username} and password = #{password}}}")
User selectByNaPa(@Param("username") String username, @Param("password") String password);
}
4. 前端配置
将会在用户提交时将数据发送到 “/loginServlet” 的服务器端处理程序,并使用 POST 方法发送数据
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>login</title>
<link href="css/login.css" rel="stylesheet">
</head>
<body>
<div id="loginDiv">
<form action="/loginServlet" method="post" id="form">
<h1 id="loginMsg">LOGIN IN</h1>
<p>Username:<input id="username" name="username" type="text"></p>
<p>Password:<input id="password" name="password" type="password"></p>
<div id="subDiv">
<input type="submit" class="button" value="login up">
<input type="reset" class="button" value="reset">
<a href="register.html">没有账号?点击注册</a>
</div>
</form>
</div>
</body>
</html>
5.Servlet编写
@WebServlet("/loginServlet")
public class LoginServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
//1. 接受用户名和密码
String username = req.getParameter("username");
String password = req.getParameter("password");
//2.调用mybatis完成查询
//2.1获取sqlsessionFactory
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.2 获取sqlsession
SqlSession sqlSession = sqlSessionFactory.openSession();
//2.3 执行sql
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
User user = userMapper.selectByNaPa(username, password);
System.out.println(user);
//2.4 释放资源
sqlSession.close();
//获取响应数据
resp.setContentType("text/html;charset = utf-8");
PrintWriter writer = resp.getWriter();
//3. 判断user是否为null
if (user != null){
//登录成功
writer.write("登录成功");
}else {
//失败
writer.write("登录失败");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
this.doGet(req, resp);
}
}
注册案例
1.需求分析
需求分析
- 用户在注册页面输入用户名和密码,提交请求给RegisterServlet
- 在RegisterServlet中接收请求和数据[用户名和密码]
- 在RegisterServlet中通过Mybatis实现调用UserMapper来根据用户名查询数据库表
- 将查询的结果封装到User对象中进行返回
- 在RegisterServlet中判断返回的User对象是否为null
- 如果为nul,说明根据用户名可用,则调用UserMapper来实现添加用户
- 如果不为null,则说明用户不可以,返回"用户名已存在"数据给前端
2.配置用户接口
//添加用户
@Insert("insert into tb_user values(null,#{username},#{password})")
void add(User user);
3. 测试添加用户
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 java.io.IOException;
import java.io.InputStream;
import java.util.List;
public class InsertTest {
public static void main(String[] args) throws IOException {
//1.传入参数
String un = "tudou";
String pw = "000";
User user1 = new User();
user1.setUsername(un);
user1.setPassword(pw);
//2.加载核心文件,获取SqlSessionFactory
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//3. 获取对应的sqlsession,执行sql
SqlSession sqlSession = sqlSessionFactory.openSession();
//4. 执行sql
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
userMapper.add(user1);
sqlSession.commit();
//查看全部看是否添加成功‘
List<User> users = userMapper.selectAll();
System.out.println(users);
//5.释放资源
sqlSession.close();
}
}
4. 前端配置
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>欢迎注册</title>
<link href="css/register.css" rel="stylesheet">
</head>
<body>
<div class="form-div">
<div class="reg-content">
<h1>欢迎注册</h1>
<span>已有帐号?</span> <a href="login.html">登录</a>
</div>
<form id="reg-form" action="/registerServlet" method="post">
<table>
<tr>
<td>用户名</td>
<td class="inputs">
<input name="username" type="text" id="username">
<br>
<span id="username_err" class="err_msg" style="display: none">用户名不太受欢迎</span>
</td>
</tr>
<tr>
<td>密码</td>
<td class="inputs">
<input name="password" type="password" id="password">
<br>
<span id="password_err" class="err_msg" style="display: none">密码格式有误</span>
</td>
</tr>
</table>
<div class="buttons">
<input value="注 册" type="submit" id="reg_btn">
</div>
<br class="clear">
</form>
</div>
</body>
</html>
5. servlet编写
package com.itheima.web;
import com.itheima.mapper.UserMapper;
import com.itheima.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;
import java.io.PrintWriter;
@WebServlet("/registerServlet")
public class RegisterServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doGet(req, resp);
//1. 接受用户名和密码
String username = req.getParameter("username");
String password = req.getParameter("password");
User user1 = new User();
user1.setUsername(username);
user1.setPassword(password);
//2.调用mybatis完成查询
//2.1获取sqlsessionFactory
InputStream inputStream = Resources.getResourceAsStream("mybatis-config.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);
//2.2 获取sqlsession
SqlSession sqlSession = sqlSessionFactory.openSession();
//2.3 执行sql
UserMapper userMapper = sqlSession.getMapper(UserMapper.class);
//2.4 调用方法
User u = userMapper.selectByUsername(username);
//3. 判断用户对象释放为null
if( u == null){
// 用户名不存在,添加用户
userMapper.add(user1);
// 提交事务
sqlSession.commit();
// 释放资源
sqlSession.close();
}else {
// 用户名存在,给出提示信息
resp.setContentType("text/html;charset=utf-8");
resp.getWriter().write("用户名已存在");
}
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
// super.doPost(req, resp);
this.doGet(req, resp);
}
}
注册用户
文章来源:https://www.toymoban.com/news/detail-654007.html
输入已经存在的用户进行注册> > 文章来源地址https://www.toymoban.com/news/detail-654007.html
到了这里,关于案例:用户登录/注册的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!