用户登录:
1、数据库创建:用户表 users
2、前台页面:
登录页面login.jsp
主界面index.jsp
3、后台开发
前面说的差不多了从后台开始:
在前面讲了分层后,将mabits集成到列表目录下
第一步:在entity包下创建用户实体类user.java
package com.example.loginpj.entity;
//用户实体类
public class user {
private Integer userid;
private String username;
private String userpwd;
public Integer getUserid() {
return userid;
}
public String getUsername() {
return username;
}
public String getUserpwd() {
return userpwd;
}
public void setUserid(Integer userid) {
this.userid = userid;
}
public void setUsername(String username) {
this.username = username;
}
public void setUserpwd(String userpwd) {
this.userpwd = userpwd;
}
}
第二步:在mapper包下创建usermapper.java和usermapper.xml的映射文件
usermapper.java
package com.example.loginpj.mapper;
import com.example.loginpj.entity.user;
import org.apache.ibatis.annotations.Mapper;
//用户接口类
@Mapper
public interface usermapper {
public user queryUserByName(String username);
public user addUserByName(String username);
public user addUserByPwd(String userpwd);
}
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.example.loginpj.mapper.usermapper">
<select id="queryUserByName" parameterType="String"
resultType="com.example.loginpj.entity.user">
select * from users where username= #{username};
</select>
<insert id="addUserByName" parameterType="String">
insert into users(username) values(#{username})
</insert>
<insert id="addUserByPwd" parameterType="String">
insert into users(userpwd) values(#{userpwd})
</insert>
</mapper>
第三步:配置mabits的配置文件放到src的更目录上
mysql.proprietaries
driverClass=com.mysql.cj.jdbc.Driver
username=root
password=12345678
url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=UTC
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>
<properties resource="mysql.properties"/>
<environments default="development">
<environment id="development">
<transactionManager type="JDBC"/>
<dataSource type="POOLED">
<property name="driver" value="com.mysql.cj.jdbc.Driver"/>
<property name="url" value="jdbc:mysql://localhost:3306/test?serverTimezone=UTC"/>
<property name="username" value="root"/>
<property name="password" value="12345678"/>
</dataSource>
</environment>
</environments>
<mappers>
<!--扫描mapper-->
<package name="com.example.loginpj.mapper"/>
</mappers>
</configuration>
第四步:获取对象,GetSqlSession.java,在util包下
package com.example.loginpj.util;
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.annotation.Resource;
//import javax.annotation.Resources;
import java.io.IOException;
import java.io.InputStream;
public class GetSqlSession {
public static SqlSession createSqlSession(){
SqlSessionFactory sqlSessionFactory = null;
InputStream input =null;
SqlSession session =null;
try{
String resource = "mybatis-config.xml";
input = Resources.getResourceAsStream(resource);
sqlSessionFactory =new SqlSessionFactoryBuilder().build(input);
session =sqlSessionFactory.openSession();
return session;
}catch (IOException e){
e.printStackTrace();
return null;
}
}
public static void main(String[] args) {
System.out.println(createSqlSession());
}
}
第五步:到这里我们的环境就配置好了,现在我们开始做一个简单的查询功能
创建一个测试类test.java
package com.example.loginpj.test;
import com.example.loginpj.util.GetSqlSession;
import org.apache.ibatis.session.SqlSession;
import com.example.loginpj.entity.user;
import com.example.loginpj.mapper.usermapper;
public class test {
public static void main(String[] args) {
//获取sqlsession对象
SqlSession session= GetSqlSession.createSqlSession();
//得到对应的mapper
usermapper usermapper =session.getMapper(com.example.loginpj.mapper.usermapper.class);
//调用对象,返回用户对象
user user = usermapper.queryUserByName("zhangfei");
System.out.println(user);
// user user= usermapper.addUserByName("zhangsan");
// System.out.println(user);
}
}
如果test可以执行出结果我们就可以进行下一步了
第六步:后台登录功能的实现
1、接收客户端的请求(接收参数:用户名、密码)
2、进行非空判断。。。。在前一章写过思路了,就不多赘述了
在entity包下创建消息模型对象messagamodel.java
package com.example.loginpj.entity.vo;
//消息模型 对象,做数据响应的
//状态码 1=成功,0=失败
//回显数据 object对象
public class MessageModel {
private Integer code =1;//状态码
private String msg="成功";
private Object object;
public Integer getCode() {
return code;
}
public String getMsg() {
return msg;
}
public Object getObject() {
return object;
}
public void setCode(Integer code) {
this.code = code;
}
public void setMsg(String msg) {
this.msg = msg;
}
public void setObject(Object object) {
this.object = object;
}
}
第七步:分别在contriller层和service层创建userservice,java和userservlet.java
记得注解
userservlet.java
详解request.getRequestDispatcher().forward(request,response)和response.sendRedirect()的用法和区别
(setAttribute这个方法,在JSP对象中的session和request都有这个方法,这个方法作用就是保存数据,然后还可以用getAttribute方法来获取出来。)
package com.example.loginpj.controller;
import com.example.loginpj.entity.vo.MessageModel;
import com.example.loginpj.service.userservice;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
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.io.IOException;
import java.lang.reflect.Member;
import java.security.MessageDigest;
@WebServlet("/login")
public class userservlet extends HttpServlet
{
// 实例化userservice对象
private userservice userservice =new userservice();
//用户登录
@Override
protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//接收用户请求
String uname=req.getParameter("uname");
String upwd=req.getParameter("upwd");
//调用service层的方法,返回消息模型对象
MessageModel messageModel = userservice.userlogin(uname,upwd);
if(messageModel.getCode()==1){
req.getSession().setAttribute("user",messageModel.getObject());
resp.sendRedirect("index.jsp");
}else{
req.setAttribute("messageModel",messageModel);
req.getRequestDispatcher("login.jsp").forward(req,resp);
}
}
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)//request和response进行一些处理
throws IOException, ServletException {
//一个用来向服务器提供客户端请求信息的对象.
HttpServletRequest req = (HttpServletRequest) request;//将ServleRequest 转换为HttpServicequest
HttpServletResponse resp = ( HttpServletResponse) response;
String uri=req.getRequestURI();//获取地址uri 返回的是一个字符串,内容为整个访问的url的path内容
uri = uri.substring(1);//将第一个‘/’截掉
uri = uri.substring(uri.indexOf('/')+1);//去掉路径的项目名称
if("login".equals(uri)||"login.jsp".equals(uri)){
chain.doFilter(req,resp);
//如果请求是login,则不执行处理,放行代码
return;
}
HttpSession session = req.getSession();//获取session对象
String uname=(String)session.getAttribute("uname");
if(uname!=null&&!"".equals(uname)){
chain.doFilter(req,resp);//求转发给过滤器链下一个filter , 如果没有filter那就是你请求的资源
return;
}
//如果uname不为空,则用户登录
// resp.sendRedirect("login.jsp");//用户没有登录,则重定向到login.jsp页面
}
}
userservlet.java
package com.example.loginpj.service;
import com.example.loginpj.entity.user;
import com.example.loginpj.entity.vo.MessageModel;
import com.example.loginpj.mapper.usermapper;
import com.example.loginpj.util.GetSqlSession;
import com.example.loginpj.util.StringUtil;
import org.apache.ibatis.session.SqlSession;
//业务逻辑
public class userservice {
public MessageModel userlogin(String uname, String upwd) {
MessageModel messageModel=new MessageModel();
user u=new user();
u.setUsername(uname);
u.setUserpwd(upwd);
messageModel.setObject(u);
if(StringUtil.isEmpty(uname)||StringUtil.isEmpty(upwd)){
messageModel.setCode(0);
messageModel.setMsg("用户姓名和密码不能为空。。");
}
SqlSession session= GetSqlSession.createSqlSession();
usermapper usermapper = session.getMapper(usermapper.class);
user user=usermapper.queryUserByName(uname);
if(user ==null){
messageModel.setCode(0);
messageModel.setMsg("用户不存在。。");
return messageModel;
}
if(!upwd.equals(user.getUserpwd())){
messageModel.setCode(0);
messageModel.setMsg("用户密码错误。。");
return messageModel;
}
messageModel.setObject(upwd);
return messageModel;
}
}
第八部:创建一个判断字符串是否为空的工具类StringUtil.java
package com.example.loginpj.util;
//字符串工具类
public class StringUtil {
// 判断字符串是否为空
public static boolean isEmpty(String str){
if(str==null||"".equals(str.trim())){
return true;
}
else
{
return false;
}
}
}
第九部:
当我们判断做完以后,在login.jsp上做补充,如果输入错误,要有消息提示和回显数据。用¥{}介个;
<%--
Created by IntelliJ IDEA.
User: 向阳
Date: 2022/10/31
Time: 15:23
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>用户登录</title>
</head>
<body>
<div style="text-align: center">
<form action="/login" method="post" id="loginform">
姓名:<input type="text" name="uname" id="uname" value="${messageModel.object.username}" ><br>
密码:<input type="password" name="upwd" id="upwd" value="${messageModel.object.userpwd}"><br>
<span id="msg" style="font-size: 12px">${messageModel.msg}</span><br>
<button type="button" id="loginBtn">登录</button>
<br>
<a href="register.jsp">注册</a>
</form>
</div>
</body>
<%--引入jquery的js文件--%>
<script type="text/javascript" src="js/jquery.js"></script>
<script type="text/javascript">
<%-- 登录表单验证:
1、登录按钮的点击事件
2、获取用户名字和密码
3、判断姓名是否为空
如果为空,用span标签提示用户,return
4、判断密码是否为空
5、都不为空就提交表单
首页 index.jsp--%>
$("#loginBtn").click(function (){
var uname=$("#uname").val();
var upwd=$("#upwd").val();
if(isempty(uname)){
$("#msg").html("用户姓名不可为空!");
return;
}
if(isempty(upwd)){
$("#msg").html("用户密码不可为空!");
return;
}
$("#loginform").submit();
});
//判断字符串是否为空
function isempty(str){
if(str==null||str.trim()=="")
return true;
else
return false;
}
</script>
</html>
最后的实现:
用户登录javaweb的实现
代码:
代码