使用Spring框架实现用户登录

Java
314
0
0
2023-02-05
标签   Spring

本文实例为大家分享了用Spring框架实现用户登录的具体代码,供大家参考,具体内容如下

流程:用户登录需求

登录页面login.jsp>>输入用户名username和密码password,如果用户名和密码在数据库中能找到,则实现登录成功界面hello.jsp,不成功则跳转到失败页面error.jsp

1.创建项目架构

(1)创建Maven项目

Add Maven Property >> Name:archetypeCatalog >> value:internal

(2)添加本地数据仓库

(3)创建项目目录

1)groupId:指代公司名 >> com.zzx >> artifactId:指代项目名 >> spring_login

2)在项目根目录底下创建文件夹target;

3)在src >> main >> java 设置为Sources Root; src >> main >> resources 设置为Resources Root;

4)加载Pom.xml文件架包,一般此文件在实际研发中都是直接由架构师来完成的操作。一般需要注意架包版本的一致性,文件版本。

5)关于数据库设计:tb_user

uid(用户编号),username(用户名),password(用户密码),tid(用户类型)。

resources >> db.properties

model、entity >> bean >> User

Spring核心配置文件applicationContext.xml

2.以下为具体代码:

Spring核心配置文件 applicationContext.xml

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:context="http://www.springframework.org/schema/context"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
       http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 1.加载db.properties取到有效参数 -->
    <context:property-placeholder location="classpath:db.properties" />
    <!-- 2.加载数据源 -->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="driverClassName" value="${driverClass}" /> <!-- EL表达式,JSTL -->
        <property name="url" value="${url}" />
        <property name="username" value="${user}" />
        <property name="password" value="${password}" />
    </bean>
    <!-- 3.创建jdbcTemplate对象 -->
    <bean id="jdbcTemplate" class="org.springframework.jdbc.core.JdbcTemplate">
        <property name="dataSource" ref="dataSource" />
    </bean>

    <!-- 4.开启注解作用 -->
    <context:component-scan base-package="com.zzx" />
    <bean id="userDao" class="com.zzx.dao.impl.UserDaoImpl" />
    <bean id="userService" class="com.zzx.service.impl.UserServiceImpl" />

</beans>

连接数据库 db.properties

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/db_java1ssm?useSSL=true&characterEncoding=utf-8
user=root
password=123456 

webapp下配置web.xml文件

<!DOCTYPE web-app PUBLIC
        "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
        "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
    <display-name>Archetype Created Web Application</display-name>

    <!-- 1.配置applicationContext.xml -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath*:applicationContext.xml</param-value>
    </context-param>

    <!-- 2.监听器 -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>


</web-app>

jsp页面

<%--login.jsp--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>用户登录</title>
</head>
<body>
<div id="content" align="center">
        <h3>用户登录</h3>
        <hr>

        <form action="loginServlet.do" method="post">

        <table border="1" cellpadding="0" cellspacing="0" width="300px">
            <tr>
                <td><label for="username">用户名:</label></td>
                <td><input type="text" id="username" name="username"/></td>
            </tr>
            <tr>
                <td><label for="password">用户密码:</label></td>
                <td><input type="text" id="password" name="password"/></td>
            </tr>
            <tr>
                <td colspan="2"> <input type="submit" name="submit" id="submit" value="登录"/></td>
            </tr>
        </table>

    </form>
</div>
</body>
</html>

<%--hello.jsp--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>登录成功页面</title>
</head>
<body>

<font>欢迎您,${user.username}</font>

</body>
</html>

<%--error.jsp--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<html>
<head>
    <title>登录失败页面</title>
</head>
<body>

<font>登录失败!请你重新登录!</font>

</body>
</html>

bean层User类

public class User {
    private int uid;
    private String username;
    private String password;
    private int tid;

    public int getUid() {
        return uid;
    }

    public void setUid(int uid) {
        this.uid = uid;
    }

    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;
    }

    public int getTid() {
        return tid;
    }

    public void setTid(int tid) {
        this.tid = tid;
    }

    public User() {
    }

    public User(int uid, String username, String password, int tid) {
        this.uid = uid;
        this.username = username;
        this.password = password;
        this.tid = tid;
    }

    public User(String username, String password, int tid) {
        this.username = username;
        this.password = password;
        this.tid = tid;
    }

    @Override
    public String toString() {
        return "User{" +
                "uid=" + uid +
                ", username='" + username + '\'' +
                ", password='" + password + '\'' +
                ", tid=" + tid +
                '}';
    }
}

dao层UserDao

@Component
public interface UserDao {
    //用户登录
    User doLogin(String username,String password);
}

UserDaoImpl

@Component
public class UserDaoImpl implements UserDao {

    @Autowired
    private JdbcTemplate jdbcTemplate;
    public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
        this.jdbcTemplate = jdbcTemplate;
    }
    @Override
    public User doLogin(String username, String password) {
        String sql = "select * from tb_user where username=? and password=?";

        BeanPropertyRowMapper<User> mapper = new BeanPropertyRowMapper<>(User.class);
        User user = null;
        user = jdbcTemplate.queryForObject(sql, mapper, username, password);

        return user;
    }
}

service层UserService

@Service

public interface UserService {

    //用户登录
    User doLogin(String username, String password);
}

UserServiceImpl

@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserDao userDao ;

    public void setUserDao(UserDao userDao) {
        this.userDao = userDao;
    }

    @Override
    public User doLogin(String username, String password) {
        return userDao.doLogin(username,password);
    }
}

LoginServlet

@WebServlet("*.do")
public class LoginServlet extends javax.servlet.http.HttpServlet {
    private static final long serialVersionUID =1L;

    // 报错是因为这个里面少tomcat - 加载tomcat
    protected void doPost(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {

        // 中文乱码问题 : 国际标准化
        request.setCharacterEncoding("utf-8");
        response.setContentType("text/html;charset=UTF-8");

        // applicationContext.xml
        ApplicationContext ioc = WebApplicationContextUtils.getWebApplicationContext(getServletContext());
        // 获取用户名
        String username = request.getParameter("username");
        String password = request.getParameter("password");

        UserService userService = (UserService) ioc.getBean("userService");

        User user = userService.doLogin(username, password);
        request.setAttribute("user",user);

        if(user==null){
            // 失败
            request.getRequestDispatcher("error.jsp").forward(request,response);
        }else{
            request.getRequestDispatcher("hello.jsp").forward(request,response);
        }
    }

    protected void doGet(javax.servlet.http.HttpServletRequest request, javax.servlet.http.HttpServletResponse response) throws javax.servlet.ServletException, IOException {
        this.doPost(request,response);
    }
}

最后配置一下Tomcat服务器运行

下面是我的运行截图