1. 程式人生 > 資料庫 >spring 整合Web基於註解的開發使用maven管理的模擬登入的未連線資料庫小案例

spring 整合Web基於註解的開發使用maven管理的模擬登入的未連線資料庫小案例

spring整合web

本專案中使用到的註解介紹:
一:@Repositor 此註解表示Dao層元件 在Dao層實現類上面新增用於訪問資料庫,目的是將Dao的實現類新增到IOC容器中交給IOC容器管理。
二:@Service 此註解表示Service(業務)層元件,在class類上新增表示是一個業務類執行一些業務邏輯等, 目的是將Service層的實現類新增到IOC容器中,是@Component註解的一種具體形式。
三:@WebServlet 用於將一個類宣告為 Servlet,該註解將會在部署時被容器處理,容器將根據具體的屬性配置將相應的類部署為 Servlet。該註解具有下表給出的一些常用屬性(以下所有屬性均為可選屬性,但是 vlaue 或者 urlPatterns 通常是必需的,且二者不能共存,如果同時指定,通常是忽略 value 的取值)。

下面是一個簡單的示例

@WebServlet("/login")
public class UserServlet extends HttpServlet {

    private UserService userService;

    @Override
    protected void doGet(HttpServletRequest req,HttpServletResponse resp) throws ServletException,IOException {
    
    }

    @Override
    protected void doPost(HttpServletRequest req,IOException {
        
    }
}

如此配置之後,就可以不必在 web.xml 中配置相應的 和 元素了,容器會在部署時根據指定的屬性將該類釋出為 Servlet。它的等價的 web.xml 配置形式如下:

<servlet>
    <servlet-name>SimpleServlet</servlet-name>
    <servlet-class>com.mybatis.servlet.UserServlet</servlet-class>
</servlet>
<servlet-mapping>
    <servlet-name>SimpleServlet</servlet-name>
    <url-pattern>/login</url-pattern>
</servlet-mapping>

第一步新增jar包

<dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
        </dependency>
        <dependency>
            <groupId>javax.servlet.jsp</groupId>
            <artifactId>javax.servlet.jsp-api</artifactId>
        </dependency>
        <!-- https://mvnrepository.com/artifact/javax.servlet.jsp.jstl/jstl -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!--ioc01-core-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-core</artifactId>
        </dependency>
        <!--ioc01-bean-->
        <!-- https://mvnrepository.com/artifact/org.springframework/spring-beans -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-beans</artifactId>
        </dependency>
        <!--ioc01-context-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
        </dependency>
        <!--ioc01-expression-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-expression</artifactId>
        </dependency>
        <!--Aop依賴-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aop</artifactId>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
        </dependency>
        <!--cglib技術-->
        <dependency>
            <groupId>cglib</groupId>
            <artifactId>cglib</artifactId>
        </dependency>
        <!--spring-web-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-web</artifactId>
        </dependency>

第二b步初始化web容器

:將Ioc容器的初始化交給Web容器管理,在WEB-INF下面的web.xml檔案中配置

 <!--初始化spring容器-->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:spring.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>

配置依賴注入 Dao->Service->action,關於spring配置檔案,當未指定contextConfigLocation引數時,預設會自動讀取/WEB-INF/applicationContexr.xml檔案 ,配置spring.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">
    <!--掃包-->
    <context:component-scan base-package="com.mybatis.dao.impl"/>
    <context:component-scan base-package="com.mybatis.service.impl"/>

    <!--ioc容器工具類-->
    <bean class="com.mybatis.util.SpringBeanUtil"/>

</beans>

專案的包結構如圖:
在這裡插入圖片描述
配置實體類:

package com.mybatis.entity;

/**
 * package_name:com.mybatis.entity
 *
 * @author:徐亞遠 Date:2020/2/21 15:30
 * 專案名:springDemo01
 * Description:TODO
 * Version: 1.0
 **/

public class User {
    private String username;
    private String password;


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

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

配置dao介面:

package com.mybatis.dao;

import com.mybatis.entity.User;

/**
 * package_name:com.mybatis.dao
 *
 * @author:徐亞遠 Date:2020/2/21 15:28
 * 專案名:springDemo01
 * Description:TODO
 * Version: 1.0
 **/
public interface UserDao {
    User login(String username,String password);
}

配置dao介面的實現類,

package com.mybatis.dao.impl;

import com.mybatis.dao.UserDao;
import com.mybatis.entity.User;
import org.springframework.stereotype.Repository;

/**
 * package_name:com.mybatis.dao.impl
 *
 * @author:徐亞遠 Date:2020/2/21 15:28
 * 專案名:springDemo01
 * Description:TODO
 * Version: 1.0
 **/
@Repository("userDao")
public class UserDaoImpl implements UserDao {
    @Override
    public User login(String username,String password) {
        User user = new User();
        System.out.println("從資料庫中查詢:"+"select username,password from user");
        user.setUsername("亞遠");
        user.setPassword("admin");
        return user;
    }
}

配置業務邏輯介面,

package com.mybatis.service;

import com.mybatis.entity.User;

/**
 * package_name:com.mybatis.service
 *
 * @author:徐亞遠 Date:2020/2/21 15:27
 * 專案名:springDemo01
 * Description:TODO
 * Version: 1.0
 **/
public interface UserService {

    User login(String username,String password);
}

配置業務邏輯的實現類,

package com.mybatis.service.impl;

import com.mybatis.dao.UserDao;
import com.mybatis.entity.User;
import com.mybatis.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * package_name:com.mybatis.service.impl
 *
 * @author:徐亞遠 Date:2020/2/21 15:33
 * 專案名:springDemo01
 * Description:TODO
 * Version: 1.0
 **/
@Service("userService")
public class UserServiceImpl implements UserService {
    @Autowired
    private UserDao userDao;
    @Override
    public User login(String username,String password) {
        User user = userDao.login(username,password );
        if (user !=null && user.getUsername().equals(username) && user.getPassword().equals(password)){
               return user;
        }
        return null;
    }
}

配置login.jsp登入頁面放在了/WEB-INF的根目錄下了 js檔案自己可以下載把它引入就行了,否則執行check()函式的時候會有錯誤。

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>登陸頁面</title>
    <script src="${pageContext.request.contextPath}/js/jquery-1.11.2.min.js"></script>
<script>
    function check() {
        var username = $("#username").val();
        var password = $("#password").val();
        if (username == null || username == "") {
            $("#error").html("使用者名稱不能為空!");
            return false;
        }
        if (password == null || password == "") {
            $("#error").html("密碼不能為空!");
            return false;
        }
        return true;
    }
</script>
</head>
<body>
<form action="${pageContext.request.contextPath}/login" method="post" onsubmit="return check()" >
    使用者名稱:<input name="username"  id="username" type="text" placeholder="輸入使用者名稱"/>
    密 碼:<input id="password" name="password" type="password" placeholder="請輸入密碼"/>
    <span><font color="red" id="error">${error}</font></span>
         <input type="submit" value="登入"/>
</form>
</body>
</html>

配置登入成功的頁面也是放在/WEB-INF的根目錄下面success.jsp

<%--
  Created by IntelliJ IDEA.
  User: Lenovo
  Date: 2020/2/21
  Time: 16:10
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
  <h2>登入成功 歡迎您:${username}</h2>
</body>
</html>

配置一個工具類用來獲得Bean物件的

package com.mybatis.util;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.BeanInitializationException;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.*;

/**
 * package_name:com.mybatis.util
 *
 * @author:徐亞遠 Date:2020/2/21 17:44
 * 專案名:springDemo01
 * Description:TODO
 * Version: 1.0
 **/

public class SpringBeanUtil implements ApplicationContextAware {
    private static ApplicationContext ac;
    /**
     * Set the ApplicationContext that this object runs in.
     * Normally this call will be used to initialize the object.
     * <p>Invoked after population of normal bean properties but before an init callback such
     * as {@link InitializingBean#afterPropertiesSet()}
     * or a custom init-method. Invoked after {@link ResourceLoaderAware#setResourceLoader},* {@link ApplicationEventPublisherAware#setApplicationEventPublisher} and
     * {@link MessageSourceAware},if applicable.
     *
     * @param applicationContext the ApplicationContext object to be used by this object
     * @throws ApplicationContextException in case of context initialization errors
     * @throws BeansException              if thrown by application context methods
     * @see BeanInitializationException
     */
    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
         ac = applicationContext;
    }
    public static Object getBean(String beanName){
        return ac.getBean(beanName);
    }

    public static Class getBean(Class clazz){
        return (Class) ac.getBean(clazz);
    }

}

配置servlet控制器

package com.mybatis.servlet;

import com.mybatis.entity.User;
import com.mybatis.service.UserService;
import com.mybatis.util.SpringBeanUtil;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * package_name:com.mybatis.servlet
 *
 * @author:徐亞遠 Date:2020/2/21 15:39
 * 專案名:springDemo01
 * Description: servlet是web容器管理的,不能交友spring容器管理
 * Version: 1.0
 **/
@WebServlet("/login")
public class UserServlet extends HttpServlet {

    private UserService userService;

    @Override
    protected void doGet(HttpServletRequest req,IOException {
        req.getRequestDispatcher("WEB-INF/login.jsp").forward(req,resp);
    }

    @Override
    protected void doPost(HttpServletRequest req,IOException {
        //req.setCharacterEncoding("utf-8");
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        System.out.println("username:"+username);
        System.out.println("password:"+password);
        userService = (UserService) SpringBeanUtil.getBean("userService");
       User user = userService.login(username,password );
       if (user !=null){
          req.getSession().setAttribute("username",user.getUsername() );
          req.getRequestDispatcher("/WEB-INF/success.jsp").forward(req,resp );
       } else {
           req.setAttribute("error","使用者名稱或密碼錯誤" );
           req.getRequestDispatcher("/WEB-INF/login.jsp").forward(req,resp );
       }

    }
}

**

最後一步配置web.xml檔案用來解決中文亂碼新增如下配置

**

<!--解決中文亂碼-->
    <filter>
        <filter-name>encodingFilter</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <init-param>
            <param-name>encoding</param-name>
            <param-value>utf-8</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encodingFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

啟動web容器後在瀏覽器輸入http://localhost:8080/login 如圖頁面效果:
在這裡插入圖片描述
輸入正確的使用者名稱,密碼跳轉到登入成功頁面效果如圖:
在這裡插入圖片描述
使用者名稱密碼出錯時返回登入頁面繼續輸入使用者名稱密碼:如圖效果
在這裡插入圖片描述