Day66 Spring IOC(控制/反转)

Spring学习内容

Spring IOC
Spring AOP
Spring TX

Spring框架介绍

Spring 简介:
Spring可以称为是框架的框架。
发明者:Rod Johnson
理论:不要重复的发明轮子。
Spring框架介绍:
jar包介绍:
这里写图片描述

Spring IOC学习:

问题:
            处理一个用户的请求代码,是基于责任链的机制进行编写的。
            这样造成对象与对象之间的耦合性过高,不易于代码的升级迭代。
        解决:
            使用Spring IOC
        概念:
            作用:统一对对象的创建进行管理
            特点:将对象与对象之间的依赖关系进行了解耦
            IOC:控制/反转
            控制:
                由Spring容器对象创建对象的过程
            反转:
                Spring容器对象将创建的对象返回给调用对象的过程
        DI:
            依赖注入
    学习:
        构造器方式
        工厂方式
        属性注入方式
        Spring整合Mybatis
    使用:
        导入jar包:
                 commons-logging-1.1.3.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
        配置xml文件
            在src下创建applicationcontext.xml文件并配置
                加载Schema:
                    <beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
                配置bean标签:
                     <bean id="唯一标识" class="类的全限定路径"></bean>
                    示例:
                     <bean id="stu" class="com.bjsxt.pojo.Student2"></bean>
            使用Spring容器对象获取要使用的对象
                    创建Spring容器对象
                        ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml");
                    获取对象:
                        ac.getBean(String id)。id为要获取的对象在配置文件中的标签ID值。
                    使用对象完成操作

springIOC创建对象的三种方式

SpringIOC创建对象的三种方式:
        第一种方式:构造器方式
            无参构造器:默认使用,创建一个空对象并返回。
            有参构造器:
                    声明调用的有参构造器的参数的个数:
                        <constructor-arg type="int" value="6"></constructor-arg>
                        一个constructor-arg标签,代表一个参数个数
                    使用属性表明参数类型:
                        每一个参数声明,必须要写属性表名参数的类型,角标,属性名,实参值。示例:
                        <constructor-arg type="int" index="0" name="sid" value="6"></constructor-arg>
            注意:Spring默认使用无参构造器创建对象.
        第二种方式:工厂方式(工厂设计模式):
            作用:简化对象的创建流程。
            静态工厂:
                生产对象的方式是静态方法,直接类名.方法名完成对象的生产。
            动态工厂:
                生产对象的方式是非静态方法,工厂类实例化对象.方法完成对象的生产。
            Spring管理方式:
                静态管理:
                    先有静态工厂类
                    在applicationcontext.xml文件中配置bean,使用静态工厂对象。
                    <bean id="user2" class="静态工厂类的全限定路径" factory-method="生产对象的方法名"></bean>
                动态管理:
                    先有动态工厂类
                    在applicationcontext.xml文件中配置bean,使用动态工厂对象。
                    <bean id="factory" class="动态工厂的全限定路径"></bean>
                    <bean id="user" factory-bean="factory" factory-method="生产对象的方法名"></bean>
        第三种方式:属性注入方式(DI)
            创建bean标签,使用子标签property配置类的属性即可。
            示例:
            <bean id="s" class="com.bjsxt.pojo.Student">
                <!--基本类型属性注入  -->
                    <property name="sid" value="9"></property>
                    <property name="sname" value="柳岩"></property>
                <!--引入数据类型  -->
                    <!-- 普通对象类型 -->
                    <property name="teacher" ref="tea"></property>
                    <!-- 数组类型  -->
                    <property name="str">
                        <array>
                            <value>1</value>
                            <value>2</value>
                            <value>3</value>
                        </array>
                    </property>
                    <!--集合类型  -->
                        <property name="ls">
                            <list>
                                <value>a</value>
                                <value>b</value>
                            </list>
                        </property>
                        <property name="map">
                            <map>
                                <entry key="a" value="哈哈" ></entry>
                                <entry key="b" value="嘿嘿"></entry>
                            </map>
                        </property>
            </bean>
            <!--创建Teacher bean  -->
            <bean id="tea" class="com.bjsxt.pojo.Teacher">
                <property name="tid" value="3"></property>
                <property name="tname" value="大鹏"></property>
            </bean>

            原理:
                先创建一个空的实例化对象,然后反射调用set方法将属性进行赋值。
            依赖注入(DI):
                将一个对象作为另外一个对象的属性注入的过程称为依赖注入。




spring整合Mybatis

Spring整合Mybatis:
    第一步:搭建框架环境
        导入jar包:
            Spring核心包
                   commons-logging-1.1.3.jar
spring-beans-4.1.6.RELEASE.jar
spring-context-4.1.6.RELEASE.jar
spring-core-4.1.6.RELEASE.jar
spring-expression-4.1.6.RELEASE.jar
spring-tx-4.1.6.RELEASE.jar
spring-aop-4.1.6.RELEASE.jar
            Mybatis的所有jar包  --
            Spring+Mybatis的整合包        mybatis-spring-1.2.3
            Spring数据库操作相关包  spring-jdbc-4.1.6.RELEASE
                       Mysql的驱动包

        创建并配置applicationcontext.xml:
            <!--Spring Mybatis的整合  -->
            <!--配置数据源  -->
                <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property>
                    <property name="username" value="root"></property>
                    <property name="password" value="1234"></property>
                </bean>
            <!--配置工厂对象  -->
                <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
                    <property name="dataSource" ref="dataSource"></property>
                </bean>
            <!--配置mapper扫描  -->
                <bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                    <property name="basePackage" value="com.bjsxt.mapper"></property>
                    <property name="sqlSessionFactory" ref="factory"></property>
                </bean>
            <!--相关bean  -->
                <!--配置业务层bean  -->
                <bean id="ss" class="com.bjsxt.serviceImpl.StudentServiceImpl">
                    <property name="sm" ref="studentMapper"></property>
                </bean>
    第二步:
        创建包
        com.bjsxt.mapper
        com.bjsxt.service
        com.bjsxt.serviceImpl:
            public class StudentServiceImpl implements StudentService{
    //声明mapper接口对象
    private StudentMapper sm;

    public StudentMapper getSm() {
        return sm;
    }

    public void setSm(StudentMapper sm) {
        this.sm = sm;
    }

    @Override
    public List<Student> selStuService() {
        return sm.selStu();
    }

}
        com.bjsxt.servlet
            //获取业务层对象
                    //获取Spring容器对象
                    ApplicationContext ac=new ClassPathXmlApplicationContext("applicationcontext.xml");
                    //获取业务层对象
                    StudentService ss=(StudentService) ac.getBean("ss");
        com.bjsxt.pojo
    第三步:
        在mapper包中创建mapper.xml并创建对应的接口
        完成代码编写

DTD &Schema

mybatis:
<!DOCTYPE configuration
  PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-config.dtd">

mapper:
<!DOCTYPE mapper
  PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
  "http://mybatis.org/dtd/mybatis-3-mapper.dtd">


spring  :<beans xmlns="http://www.springframework.org/schema/beans"
    xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
           </beans>

其他知识点

容器:ApplicationContext
SpringIOC的作用:解耦
Spring IOC的应用:
    Spring整合Mybatis注意:
     1、mybatis.xml的东西被applicationContext.xml代替
     2、原来mybatis.xml 有用的jdbc和扫描包由 applicationContext.xml配置
     3、SqlSession对象的创建由applicationContext.xml配置工厂对象并创建
     4、所有在责任链上的对象的创建由applicationContext创建
     5、为了减少applicationContext对象的创建,和serviceImpl里必须得到studentMapper,所以在创建serviceImpl的时候,在serviceImpl的属性依赖注入studentMapper对象的创建,
                <!--配置业务层bean  -->
                <bean id="ss" class="com.bjsxt.serviceImpl.StudentServiceImpl">
                    <property name="sm" ref="studentMapper"></property>
                </bean>
          然后在serviceImpl里创建,因为依赖注入必须得由get,set方法。
                            //声明mapper接口层对象  
       private StudentMapper sm;
       public StudentMapper getSm() {
        return sm;
    }
    public void setSm(StudentMapper sm) {
        this.sm = sm;
    }
    //查询所有学生的的信息
    @Override
    public List<Student> getStuInfo() {
        return sm.sel();
    }

    配置数据源
    配置工厂对象
    mapper包扫描  :扫描过后   接口的别名为原名,首字母小写 比如 StudentMapper->studentMapper
    配置业务层bean
            <!--Spring Mybatis的整合  -->
            <!--配置数据源  -->
                <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
                    <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
                    <property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property>
                    <property name="username" value="root"></property>
                    <property name="password" value="1234"></property>
                </bean>
            <!--配置工厂对象  -->
                <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean">
                    <property name="dataSource" ref="dataSource"></property>
                </bean>
            <!--配置mapper扫描  -->
                <bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
                    <property name="basePackage" value="com.bjsxt.mapper"></property>
                    <property name="sqlSessionFactory" ref="factory"></property>
                </bean>
            <!--相关bean  -->
                <!--配置业务层bean  -->
                <bean id="ss" class="com.bjsxt.serviceImpl.StudentServiceImpl">
                    <property name="sm" ref="studentMapper"></property>
                </bean>
数据源配置参数所在包:spring-jdbc-4.1.6.RELEASE.jar->org.springframework.jdbc.datasource
参数:driverClassName  url   username  password
工厂对象所在包:mybatis-spring-1.2.3.jar->org.mybatis.spring->SqlSessionFactoryBean.class
参数: dataSource    ref="dataSource"
mapper包扫描:mybatis-spring-1.2.3.jar->org.mybatis.spring.mapper->MapperScannerConfigurer.class
参数:basePackage  : com.bjsxt.mapper  sqlSessionFactory        ref:factory
DTD和Schema的区别:
spring配置文件是基于schema
2.3.1 schema文件扩展名.xsd
2.3.2 把schema理解成DTD的升级版.
2.3.2.1 比DTD具备更好的扩展性.
2.3.3 每次引入一个xsd文件是一个namespace(xmlns)



Ioc—Inversion of Control,即“控制反转”,不是什么技术,而是一种设计思想。
:由Spring容器对象统一创建对象的过程称为控制,将创建的对象返回给调用对象的过程称为反转,最大特点是解耦
依赖注入:是通过spring ICO 的属性注入方式来创建对象,在创建对象的时候将另外一个对象使用ref注入进去的方式,  将一个对象注入另一个对象的属性的方式。

使用Spring IOC 的情况:任务链上的对象创建,耦合性较高的。

不解耦:自己用Java代码new出来的。
解耦一部分:如果一个对象的创建依赖于其他对象的创建,用工厂模式创建,然后用spring Ioc 管理工厂
完全解耦:使用  Spring容器的 DI  依赖注入方式创建对象


Bean标签:Spring里面的bean就类似是定义的一个组件,而这个组件的作用就是实现某个功能的,
作用域:
解耦:借用第三方

ApplicationContext对象的创建问题


问题1:ApplicationContext对象创建次数问题
ApplicationContext对象在Servlet中如果这样创建:
  //获取spring容器对象
           ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
            //获取业务层对象
           UserService us=(UserService) ac.getBean("ss");

那么一个请求就会创建一次,造成了资源浪费,所以,我们利用servlet的init方法创建它,这样不管多少请求来,就只创建一个。
       private UserService us;
  public void init() throws ServletException {
          //获取spring容器对象
           ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
            //获取业务层对象
           us=(UserService) ac.getBean("ss");

    }


问题2:把applicationContext路径与java代码解耦:
需要的包:spring-web-4.1.6.RELEASE.jar
WEB-INF下创建并配置web.xml:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 <!--配置Spring 配置文件路径  -->
     <!--配置参数  -->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext.xml</param-value>
  </context-param>
<!--配置监听器  -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>

更新servlet中 加载applicationContext.xml文件的方式,变更为
由于ServletContext可以获取在web.xml配置的全局属性。
由webApplicationContextUtils的方法获得一个ServletContext(Application)对象,作用域为一个项目之内。
getServletContext()是spring对外提供的封装好的获取全局配置文件的对象。

       private UserService us;
  public void init() throws ServletException {
          //获取spring容器对象
            ApplicationContext ac=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
            //获取业务层对象
                us=(UserService) ac.getBean("ss");
           }


服务器端验证码

服务器端验证码:
方式一:自己写生成代码:
生成验证码并放入session对象中:
//生成验证码
   public static void CreatVerifyCode(HttpServletRequest req,HttpServletResponse resp) throws IOException{
        //创建图片
        BufferedImage image=new BufferedImage(200,100, BufferedImage.TYPE_INT_RGB);
    //设置图片
        //获取画笔
        Graphics2D gh=(Graphics2D) image.getGraphics();
        //设置画笔颜色
        gh.setColor(Color.ORANGE);
        //填充画板
        gh.fillRect(0, 0, 200, 100);
        //作画

            //设置字体
            gh.setFont(new Font("宋体",Font.ITALIC|Font.BOLD, 40));
            //创建随机验证码
            ArrayList<Integer> list=new ArrayList<>();
            for(int i=0;i<4;i++){
                int num=(int) (Math.random()*10);
                list.add(num);                  
            }
            //设置颜色数组
            Color[] crs=new Color[]{Color.black,Color.cyan,Color.blue,Color.GREEN,Color.red,Color.yellow};
            //遍历验证码
            for(int i=0;i<list.size();i++){
                //重新设置画笔颜色
                gh.setColor(crs[(int) (Math.random()*crs.length)]);
                //画验证码
                gh.drawString(list.get(i)+"",i*40,(int)(70+(Math.random()*21-10)));
            }

            //画线
            gh.drawLine(0, (int)(Math.random()*100), 200, (int)(Math.random()*100));
            gh.drawLine(0, (int)(Math.random()*100), 200, (int)(Math.random()*100));
            //将验证码信息存储到session中
            req.getSession().setAttribute("codeSystem", ""+list.get(0)+list.get(1)+list.get(2)+list.get(3));
    //响应图片
        //获取响应流对象
        OutputStream os=resp.getOutputStream();
        //输出图片
        ImageIO.write(image, "jpg", os);
   }


Servlet 获取前台数据并且校验验证码:
                        String code=req.getParameter("code");
                        //校验验证码
                        String codeSystem=(String) req.getSession().getAttribute("codeSystem");
                        if(!code.equals(codeSystem)){
                            req.setAttribute("str", "验证码不正确");
                            //请求转发
                            req.getRequestDispatcher("login.jsp").forward(req, resp);
                            return;
                        }

方式二:使用插件:
https://www.cnblogs.com/xdp-gacl/p/4221848.html

小案例

使用spring 整合mybatis实现登录
数据库设计 t_usr : uid uname upwd

src:
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"
    xsi:schemaLocation="http://www.springframework.org/schema/beans
        http://www.springframework.org/schema/beans/spring-beans.xsd">
     <!--配置数据源  -->
     <bean id="dataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
     <property name="driverClassName" value="com.mysql.jdbc.Driver"></property>
     <property name="url" value="jdbc:mysql://localhost:3306/mybatis"></property>
     <property name="username" value="root"></property>
     <property name="password" value="root"></property>
     </bean>
     <!--配置工厂类对象  -->
     <bean id="factory" class="org.mybatis.spring.SqlSessionFactoryBean" >
     <property name="dataSource" ref="dataSource"></property>
     </bean>
     <!--配置mapper包扫描  -->
     <bean id="mapper" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.bjsxt.mapper"></property>
        <property name="sqlSessionFactory" ref="factory"></property>
     </bean>
     <!--相关bean  --> 
        <!--业务层bean  -->
     <bean id="ss" class="com.bjsxt.serviceImpl.UserServiceImpl">
     <property name="um" ref="userMapper"></property>
     </bean>
</beans>

com.bjsxt.mapper:
UserMapper.java:

package com.bjsxt.mapper;

import com.bjsxt.pojo.User;

public interface UserMapper {
    //根据账号密码查询用户数据
   User selUser(String uname,String upwd);
}

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.bjsxt.mapper.UserMapper">
  <select id="selUser" resultType="com.bjsxt.pojo.User" >
   select * from t_user where uname=#{0} and upwd=#{1}
  </select>

 </mapper>

com.bjsxt.pojo:
User.java:

package com.bjsxt.pojo;

public class User {
  private int uid;
  private String uname;
  private String upwd;
public User() {
    super();
    // TODO Auto-generated constructor stub
}
public User(int uid, String uname, String upwd) {
    super();
    this.uid = uid;
    this.uname = uname;
    this.upwd = upwd;
}
public int getUid() {
    return uid;
}
public void setUid(int uid) {
    this.uid = uid;
}
public String getUname() {
    return uname;
}
public void setUname(String uname) {
    this.uname = uname;
}
public String getUpwd() {
    return upwd;
}
public void setUpwd(String upwd) {
    this.upwd = upwd;
}
@Override
public String toString() {
    return "User [uid=" + uid + ", uname=" + uname + ", upwd=" + upwd + "]";
}
@Override
public int hashCode() {
    final int prime = 31;
    int result = 1;
    result = prime * result + uid;
    result = prime * result + ((uname == null) ? 0 : uname.hashCode());
    result = prime * result + ((upwd == null) ? 0 : upwd.hashCode());
    return result;
}
@Override
public boolean equals(Object obj) {
    if (this == obj)
        return true;
    if (obj == null)
        return false;
    if (getClass() != obj.getClass())
        return false;
    User other = (User) obj;
    if (uid != other.uid)
        return false;
    if (uname == null) {
        if (other.uname != null)
            return false;
    } else if (!uname.equals(other.uname))
        return false;
    if (upwd == null) {
        if (other.upwd != null)
            return false;
    } else if (!upwd.equals(other.upwd))
        return false;
    return true;
}

}

com.bjsxt.service:
UserService.java:

package com.bjsxt.service;

import com.bjsxt.pojo.User;

public interface UserService {
   User getUserInfo(String uname,String upwd);
}

com.bjsxt.serviceImpl:
UserServiceImpl.java:

package com.bjsxt.serviceImpl;

import com.bjsxt.mapper.UserMapper;
import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;

public class UserServiceImpl implements  UserService{
    private UserMapper um;


    public UserMapper getUm() {
        return um;
    }


    public void setUm(UserMapper um) {
        this.um = um;
    }


    //根据账号密码查询用户信息
    @Override
    public User getUserInfo(String uname, String upwd) {
        return um.selUser(uname, upwd);
    }

}

com.bjsxt.servlet:
UserServlet.java:

package com.bjsxt.servlet;

import java.io.IOException;

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 javax.servlet.http.HttpSession;

import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.bjsxt.pojo.User;
import com.bjsxt.service.UserService;

/**
 * Servlet implementation class UserServlet
 */
@WebServlet("/user")
public class UserServlet extends HttpServlet {
    //声明业务层对象
        private UserService us;
    @Override
    public void init() throws ServletException {
          //获取spring容器对象
           //ApplicationContext ac=new ClassPathXmlApplicationContext("applicationContext.xml");
         ApplicationContext ac=WebApplicationContextUtils.getWebApplicationContext(getServletContext());
            //获取业务层对象
            us=(UserService) ac.getBean("ss");
           //获取结果
    }
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //设置请求编码格式
        req.setCharacterEncoding("utf-8");
        //设置响应编码格式
        resp.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        //获取请求信息
        String uname=req.getParameter("uname");
        String upwd=req.getParameter("upwd");
        String code=req.getParameter("code");
        //处理请求信息
             User user=us.getUserInfo(uname, upwd);
            //校验验证码
                String codeSystem=(String) req.getSession().getAttribute("codeSystem");
                if(!code.equals(codeSystem)){
                    req.setAttribute("str", "验证码不正确");
                    //请求转发
                    req.getRequestDispatcher("login.jsp").forward(req, resp);
                    return;
                }
        //响应处理结果
           if(user!=null){
               //获取session对象
              HttpSession  hs=req.getSession();
              hs.setAttribute("user", user);
              resp.sendRedirect("main.jsp");
           }else{
               req.setAttribute("str", "账号或者密码错误,请重新输入");
               req.getRequestDispatcher("login.jsp").forward(req, resp);
           }
    }
}

CodeServlet.java:

扫描二维码关注公众号,回复: 639956 查看本文章
package com.bjsxt.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Random;

import javax.imageio.ImageIO;
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 com.bjsxt.util.VerifyCodeUtil;

/**
 * Servlet implementation class CodeServlet
 */
@WebServlet("/cs")
public class CodeServlet extends HttpServlet {
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //创建验证码
        VerifyCodeUtil.CreatVerifyCode(req, resp);
    }
}

com.bjsxt.util:
VerifyCodeUtil.java:

package com.bjsxt.util;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class VerifyCodeUtil {

    //生成验证码
   public static void CreatVerifyCode(HttpServletRequest req,HttpServletResponse resp) throws IOException{
        //创建图片
        BufferedImage image=new BufferedImage(200,100, BufferedImage.TYPE_INT_RGB);
    //设置图片
        //获取画笔
        Graphics2D gh=(Graphics2D) image.getGraphics();
        //设置画笔颜色
        gh.setColor(Color.ORANGE);
        //填充画板
        gh.fillRect(0, 0, 200, 100);
        //作画

            //设置字体
            gh.setFont(new Font("宋体",Font.ITALIC|Font.BOLD, 40));
            //创建随机验证码
            ArrayList<Integer> list=new ArrayList<>();
            for(int i=0;i<4;i++){
                int num=(int) (Math.random()*10);
                list.add(num);                  
            }
            //设置颜色数组
            Color[] crs=new Color[]{Color.black,Color.cyan,Color.blue,Color.GREEN,Color.red,Color.yellow};
            //遍历验证码
            for(int i=0;i<list.size();i++){
                //重新设置画笔颜色
                gh.setColor(crs[(int) (Math.random()*crs.length)]);
                //画验证码
                gh.drawString(list.get(i)+"",i*40,(int)(70+(Math.random()*21-10)));
            }

            //画线
            gh.drawLine(0, (int)(Math.random()*100), 200, (int)(Math.random()*100));
            gh.drawLine(0, (int)(Math.random()*100), 200, (int)(Math.random()*100));
            //将验证码信息存储到session中
            req.getSession().setAttribute("codeSystem", ""+list.get(0)+list.get(1)+list.get(2)+list.get(3));
    //响应图片
        //获取响应流对象
        OutputStream os=resp.getOutputStream();
        //输出图片
        ImageIO.write(image, "jpg", os);
   }
}

WebContext:
js:
jquery-1.9.1.js
login.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>登录界面</title>
<script type="text/javascript" src="j/jquery-1.9.1.js"></script>
<script type="text/javascript">
 $(function(){
     $("#a2").click(function(){
         $("#a1").attr("src","cs?"+new Date());
         return false;
     })
 })
</script>
</head>
<body>
${str } ${code}
  <form action="user" method="get">
    账号: <input type="text"  name="uname" value=""/><br />
   密码:<input type="password" name="upwd" value="" /><br />
   验证码: <input type="text" name="code" value="" /><img  src="cs" id="a1"/>
   <a href=""  id="a2">看不清点我</a><br />
  <input type="submit" value="登录" />
  </form>
</body>
</html>

main.jsp:

<%@ page language="java" contentType="text/html; charset=utf-8"
    pageEncoding="utf-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>主页面</title>
</head>
<body>
  欢迎${user.uname} 登录
</body>
</html>

WEB-INF:
web.xml:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
 <context-param>
 <param-name>contextConfigLocation</param-name>
 <param-value>classpath:applicationContext.xml</param-value>
 </context-param>
 <listener>
 <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
 </listener>
</web-app>

源码地址:
链接:https://pan.baidu.com/s/1rjWTJ9nl2UeBECt9JY0t2A 密码:svai

小结

Spring 框架介绍以及知识点
spring IOC学习
springIOC创建对象的三种方式
spring整合Mybatis
DTD &Schema
其他知识点
ApplicationContext对象的创建问题
服务器端验证码
小案例

猜你喜欢

转载自blog.csdn.net/qq_21953671/article/details/79779625
今日推荐