1. 程式人生 > 其它 >ssm-03-spring-mvc-02-simple-login

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

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式登入功能即完成。