ssm-03-spring-mvc-02-simple-login

该博客介绍了如何使用Spring MVC搭建一个简单的登录功能。首先,通过创建Hello World.jsp和controller进行初步设置。接着,接入Mysql和Mybatis,建立数据表,编写mapper、service、实现类和controller。最后,添加前端页面,包括登录页和主页,通过配置静态资源servlet,完成登录功能的展示。
摘要由CSDN通过智能技术生成

ssm-03-spring-mvc-02-simple-login

尝试使用spring mvc来实现简单的登录功能,pom依赖这里不一一列出来。

搭建Hello World.jsp:

  1. 新建maven工程:

  2. 一直点击下一步就行,此后功能文件夹结构只有一个 webapp文件夹。
  3. 配置smart tomcat:

  4. 要注意配置时,部署目录是项目所在的webapp目录。
  5. 运行空项目,验证tomcat配置:
  6. 在浏览器中输入:http://localhost:8080/index.jsp,成功呈现下图结果:

搭建Hello World controller:

  1. 创建java、resources和test目录并分别标记为Sources、Resources、Tests:
  2. resources目录下创建Spring配置文件:applicationContext.xml
  3. <?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"
                   xmlns:mvc="http://www.springframework.org/schema/mvc"
                   xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           https://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!--自动扫描spring注解的组件,避免臃肿的bean配置-->
        <!--注解组件包括:@Component, @Repository, @Service, @Controller, @RestController, @ControllerAdvice, @Configuration-->
        <!--base-package:包含有注解组件的包名-->
        <context:component-scan base-package="com.zx.demo"/>
        <!--注解驱动,spring mvc专属配置,主要注册了dispatcher所需的RequestMappingHandlerMapping和RequestMappingHandlerAdapter-->
        <mvc:annotation-driven/>
    </beans>
  4. java目录下新建Controller:
  5. package com.zx.demo;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.ResponseBody;
    //@Controller配置声明的组件会被Spring自动装配
    @Controller
    public class TestController {
        //@RequestMapping注解对应:RequestMappingHandlerMapping
        @RequestMapping("/hello")
        //@ResponseBody注解表示可以直接向前端返回java对象
        @ResponseBody
        public String test() {
            //返回字符串
            return "Hello world test.";
        }
    }
  6. 部署并运行tomcat,浏览器中输入:http://localhost:8080/hello,成功后展示如下:

接入Mysql和Mybatis

  1. 创建数据表并插入一条测试数据:
  2. 编写mapper
  3. UserMapper.java:
    package com.zx.demo.dao;
    import org.apache.ibatis.annotations.Param;
    import java.util.Map;
    public interface UserMapper {
        Map<Object, Object> login(@Param("loginName") String loginName, @Param("loginPwd") String loginPwd);
    }
    
    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.zx.demo.dao.UserMapper">
        <select id="login" resultType="map">
            SELECT * FROM `user` WHERE login_name = #{loginName} AND login_pwd = #{loginPwd} LIMIT 1;
        </select>
    </mapper>
  4. 配置数据源和Mybatis
  5. <!--配置数据源-->
    <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
        <property name="url" value="jdbc:mysql://xxx.xx/mydb"/>
        <property name="username" value="test"/>
        <property name="password" value="testxxx"/>
        <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
    </bean>
    <!--配置Mybatis-sqlSession-->
    <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="mapperLocations" value="classpath*:**/*Mapper.xml"/>
    </bean>
    <!--配置mapper-->
    <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
        <property name="mapperInterface" value="com.zx.demo.dao.UserMapper"/>
        <property name="sqlSessionFactory" ref="sqlSession"/>
    </bean>
  6. 编写service和实现类
  7. UserService.java:
    package com.zx.demo.service;
    import java.util.Map;
    public interface UserService {
        Map<Object, Object> login(String loginName, String loginPwd);
    }
    
    UserService.java:
    package com.zx.demo.service;
    import com.zx.demo.dao.UserMapper;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Service;
    import java.util.Map;
    @Service
    public class UserServiceImpl implements UserService {
        @Autowired
        UserMapper userMapper;
        @Override
        public Map<Object, Object> login(String loginName, String loginPwd) {
            return userMapper.login(loginName, loginPwd);
        }
    }
    
  8. 编写controller
  9. UserController.java
    package com.zx.demo.controller;
    import com.zx.demo.service.UserService;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestParam;
    import org.springframework.web.bind.annotation.RestController;
    import java.util.Map;
    @RestController
    public class UserController {
        @Autowired
        UserService userService;
        @RequestMapping("/login")
        public String login(@RequestParam("loginName") String loginName, @RequestParam("password") String loginPwd) {
            System.out.println("loginName:" + loginName + "\tloginPwd:" + loginPwd);
            Map<Object, Object> user = userService.login(loginName, loginPwd);
            if (user != null) {
                return user.get("id").toString();
            } else {
                return "-1";
            }
        }
    }
    
  10. 部署并运行tomcat,浏览器中输入:http://localhost:8080/simple-login/login?loginName=test&password=123456,成功后展示如下:
  11. 部署前,将项目Context Path设置为simple-login

加入简单的前端页面

下述几个html页面,都在webapp目录下创建
  1. 编写简单登录页
  2. login.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>Title</title>
        <script type="text/javascript" src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
        <script>
        $(document).ready(function(){
            $("#btnLogin").click(function(){
                var loginName = $("#loginName").val();
                var password = $("#password").val();
                $.post("/simple-login/login",
                {
                    loginName:loginName,
                    password:password,
                },
                function(data,status){
                    if(status == "success" && data == 1){
                        window.location.href="/simple-login/homepage.html";
                    }else{
                        alert("登录失败");
                    }
                })
            })
        });
        </script>
    </head>
    <body>
    <h1>登录</h1>
    登录名:<input id="loginName" type="text"/><br/><br/>
    密    码:<input id="password" type="password"/><br/><br/>
    <button id="btnLogin">登录</button>
    </body>
    </html>
  3. 编写简单主页
  4. homepage.html
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>主页</title>
    </head>
    <body>
    <h1 style="text-align: center">主页</h1>
    </body>
    </html>
  5. Spring配置文件中,加上静态资源servlet配置
  6. <!--配置后,静态资源将会走容器默认servlet,否则会出现404-->
    <mvc:default-servlet-handler/>
    完整Spring配置:
    <?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"
                   xmlns:mvc="http://www.springframework.org/schema/mvc"
                   xsi:schemaLocation="http://www.springframework.org/schema/beans
           http://www.springframework.org/schema/beans/spring-beans.xsd
           http://www.springframework.org/schema/context
           https://www.springframework.org/schema/context/spring-context.xsd
           http://www.springframework.org/schema/mvc
           https://www.springframework.org/schema/mvc/spring-mvc.xsd">
        <!--自动扫描spring注解的组件,避免臃肿的bean配置-->
        <!--注解组件包括:@Component, @Repository, @Service, @Controller, @RestController, @ControllerAdvice, @Configuration-->
        <!--base-package:包含有注解组件的包名-->
        <context:component-scan base-package="com.zx.demo"/>
        <!--注解驱动,spring mvc专属配置,主要注册了dispatcher所需的RequestMappingHandlerMapping和RequestMappingHandlerAdapter-->
        <mvc:annotation-driven/>
        <!--配置后,静态资源将会走容器默认servlet,否则会出现404-->
        <mvc:default-servlet-handler/>
        <!--配置数据源-->
        <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
            <property name="url" value="jdbc:mysql://xxx.xx/mydb"/>
            <property name="username" value="test"/>
            <property name="password" value="testxxx"/>
            <property name="driverClassName" value="com.mysql.jdbc.Driver"/>
        </bean>
        <!--配置Mybatis-sqlSession-->
        <bean id="sqlSession" class="org.mybatis.spring.SqlSessionFactoryBean">
            <property name="dataSource" ref="dataSource"/>
            <property name="mapperLocations" value="classpath*:**/*Mapper.xml"/>
        </bean>
        <!--配置mapper-->
        <bean id="userMapper" class="org.mybatis.spring.mapper.MapperFactoryBean">
            <property name="mapperInterface" value="com.zx.demo.dao.UserMapper"/>
            <property name="sqlSessionFactory" ref="sqlSession"/>
        </bean>
    </beans>
  7. 部署并运行tomcat,浏览器中输入:http://localhost:8080/simple-login/login.html,成功后展示如下:

  8. 输入错误的用户名和密码-页面会提示登录失败:

    输入正确的用户名和密码-页面会跳转到主页:

这样,一个简单的hello world式登录功能即完成。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值