当前位置:首页 » 《随便一记》 » 正文

Java-Web前后端交互实现登陆注册(附源码)

17 人参与  2023年05月04日 17:05  分类 : 《随便一记》  评论

点击全文阅读


1.完成用户登录功能。

2.完成注册功能。

3.主体利用Maven导入java中的jar包,使用Servlet实现前后端交互,使用mybatis以及注解,mysql进行数据保存,Tomcat服务器进行开发。

效果图

项目结构

代码

mapper(相对应注解)

package com.itheima.mapper;import com.itheima.pojo.User;import org.apache.ibatis.annotations.Insert;import org.apache.ibatis.annotations.Param;import org.apache.ibatis.annotations.Select;public interface UserMapper {    /**     * 用户登陆根据用户和密码来查询用户对象     * @param username     * @param password     * @return     */    @Select("select * from tb_user where username=#{username} and password = #{password}")    User select(@Param("username") String username, @Param("password")String password);    /**     * 根据用户名来查询用户是否存在     * @param usernmae     * @return     */    @Select("select * from tb_user where username=#{username}")    User selectByUsername(String usernmae);    /**     * 判断完是否存在后不存在再进行注册添加用户     * @param user     */    @Insert("insert into tb_user values(null,#{username},#{password})")    void add(User user);}

pojo(实体类)

package com.itheima.pojo;public class User {    private Integer id;    private String username;    private String 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 + '\'' +                '}';    }}

3.util(工具类)

package com.itheima.util;import org.apache.ibatis.io.Resources;import org.apache.ibatis.session.SqlSessionFactory;import org.apache.ibatis.session.SqlSessionFactoryBuilder;import java.io.IOException;import java.io.InputStream;/** * * 工具类避免资源浪费多次加载 */public class SqlSessionFactoryUtils {    private static SqlSessionFactory sqlSessionFactory;    static {        String resource = "mybatis-config.xml";        InputStream inputStream = null;        try {            inputStream = Resources.getResourceAsStream(resource);        } catch (IOException e) {            e.printStackTrace();        }        sqlSessionFactory = new SqlSessionFactoryBuilder().build(inputStream);    }    public static SqlSessionFactory getSqlSessionFactory() {        return sqlSessionFactory;    }}

4.web(Servlet)

1.loginServlet

package com.itheima.web;import com.itheima.mapper.UserMapper;import com.itheima.pojo.User;import com.itheima.util.SqlSessionFactoryUtils;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.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;import java.io.InputStream;import java.io.PrintWriter;@WebServlet("/loginServlet")public class loginServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        // 1.接收用户名和密码        String username = request.getParameter("username");        String password = request.getParameter("password");        //2. 调用Mybatis完成查询        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();        //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        response.setContentType("text/html;charset=utf-8");        PrintWriter writer = response.getWriter();        //3.判断user是否为null        if (user!=null){            //登陆成功            writer.write("登陆成功");        }        else {            //登陆失败            writer.write("登陆失败");        }    }    @Override    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        this.doGet(request, response);    }}

2.registerServlet

package com.itheima.web;import com.itheima.mapper.UserMapper;import com.itheima.pojo.User;import com.itheima.util.SqlSessionFactoryUtils;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.*;import javax.servlet.http.*;import javax.servlet.annotation.*;import java.io.IOException;import java.io.InputStream;@WebServlet("/registerServlet")public class registerServlet extends HttpServlet {    @Override    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        //1.接受用户数据        String username = request.getParameter("username");        String password = request.getParameter("password");        // 封装用户对象        User user = new User();        user.setUsername(username);        user.setPassword(password);        // 调用Mapper,根据用户名来查询是否        SqlSessionFactory sqlSessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();        //2.2获取SqlSession对象        SqlSession sqlSession =sqlSessionFactory.openSession();        //2.3获取Mapper        UserMapper userMapper = sqlSession.getMapper(UserMapper.class);        //2.4 调用方法        User u = userMapper.selectByUsername(username);        if (u == null){            // 用户名不存在            userMapper.add(user);            // 提交事务            sqlSession.commit();            response.setContentType("text/html;charset=utf-8");            response.getWriter().write("注册成功");        }        else{            // 用户名不存在            response.setContentType("text/html;charset=utf-8");            response.getWriter().write("用户已存在,注册失败");        }        // 释放资源        sqlSession.close();    }    @Override    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {        this.doGet(request, response);    }}

5.html

1.login.html

<!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="/Tomcat-demo1/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>

2.register.html

<!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="/Tomcat-demo1/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>

总结

此登陆注册界面使用Maven,Servlet,Mybatis,Mysql,Tomcat技术以及结合了html,css界面设置实现了前后端交互,将前端界面输入的数据传入到后端java中进行处理并将数据保存在mysql数据库之中,是个很不错的练手小项目,新入门小伙伴可以一起尝试。

基本代码如上所示,以上均为手敲,如需所有代码请私信我,谢谢!!!


点击全文阅读


本文链接:http://zhangshiyu.com/post/60755.html

<< 上一篇 下一篇 >>

  • 评论(0)
  • 赞助本站

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

关于我们 | 我要投稿 | 免责申明

Copyright © 2020-2022 ZhangShiYu.com Rights Reserved.豫ICP备2022013469号-1