spring 整合Web基于注解的开发使用maven管理的模拟登录的小案例

11 篇文章 0 订阅
11 篇文章 0 订阅

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, HttpServletResponse resp) throws ServletException, 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, HttpServletResponse resp) throws ServletException, IOException {
        req.getRequestDispatcher("WEB-INF/login.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, 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 如图页面效果:
在这里插入图片描述
输入正确的用户名,密码跳转到登录成功页面效果如图:
在这里插入图片描述
用户名密码出错时返回登录页面继续输入用户名密码:如图效果
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值