Web作业02

流程图

1.先获取需要解析的源文件

InputStream is=Resources.getResourceAsStream("mybatis-config.xml");

执行流程Web作业02_第1张图片

 

  • 使用工具类的Rescources 源调用getResources(String resources)将配置文件加载进来
  • Rescources 工具类的getResourceAsStream(classLoader loader,String resources)方法将源文件的加载进类构造器
  • 在调用类加载器的过程中发现调用的是classLoaderWrapper中getResourceAsStream(String rescource,ClassLoader classLoader)里面的数组getResourceAsStream(String resource,ClassLoader[] classLoader)
  • 数组中还有ClassLoaderWrappper中成员变量默认的类加载器,当前对象的类加载器以及系统类加载器,五个类加载器
  • 最后通过对该数组进行判断,看类加载器中所读的流是否为null,如果不为null,则返回InputStream对象

2.获取SqlSessionFactory对象

SqlSessionFactory factory=new SqlSessionFactoryBuilder().build(is);

Web作业02_第2张图片

  • 进入到build 传递reader有参数构造函数
  • SqlSessionFactoryBuilder使用XMLConfigBuilder解析配置文件,封装成Configuration对象。
  • configuration是全局的所以只能被解析一次
  • 执行environmentsElement()  方法
  • 解析的文件内容套接到configuration中 而这个configuration 相当于 mybatis-config.xml 中的配置文件所对应的类返回DefaultSqlSessionFactory对象

3.获取sqlsession对象

SqlSession session=factory.openSession();

Web作业02_第3张图片

  •  先使用DefaultSqlSessionFactory对象的opensession方法返回DefaultSQLSession对象
  • 然后调用openSessionFromDataSource(ExecutorType execType, TransactionIsolationLevel level, boolean autoCommit)方法
  • 接下来声明事务对象,读取配置文件中的相关属性,通过envirnment对象去获得工厂对象
  • 创建实体类执行器newExcutor()
  • 返回 DefaultSqlSession对象。

 4.获得classmapper对象

ClassMapper mapper=session.getMapper(ClassMapper.class);

Web作业02_第4张图片 

  • 先执行configuration的getMapper(Class type,Sqlsession sqlSession)方法返回相关对象
  • MapperRegistry中的getMapper(Class type,Sqlsession sqlSession)方法返回 T泛型对象
  • MapperProxy.newMapperProxy(type, sqlSession);这句是创建接口的代理的
  • 通过mapperProxyFactory.newInstance(sqlSession),进入MapperProxyFactory的newInstance方法中
  • 找到MapperProxyFactory的newIntance方法,通过参数类型SqlSession可以得知,上面的调用先进入第二个newInstance方法中并创建我们所需要重点关注的MapperProxy对象,

mybaits实现分页

分页sql映射

pojo层抽象方法

public List findListBypage();

测试程序

String resource = "Mybatis-config.xml";
		InputStream is =Resources.getResourceAsStream(resource);
		SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(is);
		SqlSession session = sqlSessionFactory.openSession();
		
		Map map = new HashMap();
	    map.put("index", 0);
	    map.put("size", 5);
	    List list = session.selectList("com.openlab.mapper.TB7Mapper.findListBypage", map);
	    
	    System.out.println("姓名"+"---"+"年龄"+"---"+"薪水");
	    
	    for(TB7 r:list){
	      System.out.println(r.getUsername()+"---"+r.getAge()+"---"+r.getSalary());
	    }

结果

Web作业02_第5张图片

在线人数

Web作业02_第6张图片

监听器配置


  
     com.hand.pac1.SessionCounter
  

 

监听器类

package com.hand.pac1;

import javax.servlet.http.HttpSessionEvent;
import javax.servlet.http.HttpSessionListener;

public class SessionCounter implements HttpSessionListener{

	private static int activeSessions = 0;
	
	@Override
	public void sessionCreated(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		activeSessions++;
	}

	@Override
	public void sessionDestroyed(HttpSessionEvent arg0) {
		// TODO Auto-generated method stub
		if (activeSessions > 0)
		      activeSessions--;
	}

	 public static int getActiveSessions() {
		    return activeSessions;
		  }
	
}

注册和登录功能的实现

数据库

Web作业02_第7张图片

登录功能的Servlet

import java.io.IOException;
import java.io.PrintWriter;


import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class login extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		request.setCharacterEncoding("utf-8");
		response.setCharacterEncoding("GBK");
		 String username= request.getParameter("username") ;
		 String password= request.getParameter("password");
		 String checkcode= request.getParameter("checkcode");
		 String checkcode1=(String) request.getSession().getAttribute("chrr");
		 System.out.print(checkcode1);
		try {
			Class.forName("com.mysql.jdbc.Driver");
			Connection con= DriverManager.getConnection("jdbc:mysql:///ks","root","123456");
			Statement st=con.createStatement();
			  String sql="select * from zcuser where username='"+username+"'";
			  ResultSet rs=st.executeQuery(sql);
			  if(rs.next()){
				  System.out.println(rs.getString(3));
				      if(password.equals( rs.getString(3))){
					      if(checkcode.toLowerCase().equals(checkcode1.toLowerCase())){
					    	  request.getSession().setAttribute("username", username);
					    	     response.sendRedirect("index.jsp");
					    	    }
				    	  else {
				    		  response.getWriter().write("" );
							    response.setHeader("refresh","0;url=/index.jsp");
							   }
				       }
				    else {
				    	response.getWriter().write("" );
					    response.setHeader("refresh","0;url=/index.jsp");
				     }
				}
			  else {
				  response.getWriter().write("" );
					response.setHeader("refresh","0;url=index.jsp");
				}
			  }
		catch (ClassNotFoundException e) {
			e.printStackTrace();
}
        catch (SQLException e) {
			e.printStackTrace();
	}
		
	    

		
	}

		public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

			doGet(request,response);
		
	}

}

注册页面的Servlet

import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import util.myutil;
public class zhuce extends HttpServlet {

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		
		Connection con=null;
		PreparedStatement st=null;
		response.setCharacterEncoding("utf-8");
        String username=myutil.getNewString(request.getParameter("username"));
        String password =request.getParameter("password");
        String email=request.getParameter("email");
        String telephone =request.getParameter("telephone");
        String gender=myutil.getNewString(request.getParameter("gender"));
    try {
			Class.forName("com.mysql.jdbc.Driver");
			con = DriverManager.getConnection("jdbc:mysql://localhost:3306/ks","root","123456");
			String sql="insert into zcuser values(?,?,?,?,?)";
			st = con.prepareStatement(sql);
			st.setString(1,email);
			st.setString(2, username);
			st.setString(3,password);
			st.setString(4,gender);
			st.setString(5,telephone);
			st.executeUpdate();
			}catch (ClassNotFoundException e) {
					e.printStackTrace();
		}  
			 catch (SQLException e) {
			
				e.printStackTrace();
			}
			System.out.println("插入成功。。。");
			System.out.println(username);
			response.sendRedirect("index.jsp");

	}

	
	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

	doGet(request, response);
	}

}

验证码

package yzjs;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Random;

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


public class checkcode extends HttpServlet {

	
	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		 //1.在内存中生成图片
		int width=120;
		int height=30;
		BufferedImage img=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		//2.获取画笔
        Graphics2D g=(Graphics2D) img.getGraphics();
        //设置颜色
        g.setColor(Color.yellow);
        g.fillRect(0, 0, width, height);
        //画边框
        g.setColor(Color.blue);
        g.drawRect(0, 0, width-1, height-1);
        //3.随机生成验证码的字母和数字
        String words="ABCDEFGHIJKLMNOPQRSTUVWZXYZ123";
        //设置字体
        g.setFont(new Font("隶书",Font.BOLD,20));
        Random random=new Random();
        int x=20,y=20;
        //Graphics2D
        /*
         *   abstract void rotate(double theta,double x,double y)
         *   将当前的Graphics2D Transfrom 于平移后的旋转转换连接
         *   theta:hudu
         *   hudu:jiaodu*math.PI/100
         * */
      //创建 randomCode 对象, 用于保存随机产生的验证码, 以便用户登录后进行验证    
        StringBuffer randomCode;    
        randomCode = new StringBuffer();  
        for(int i=0;i<4;i++){
        	
        	int jiaodu=random.nextInt(60)-30;
        	double hudu=jiaodu*Math.PI/180;
        	g.rotate(hudu,x,y);
        	int index=random.nextInt(words.length());//随即下标
        	char chr=words.charAt(index);
        	g.drawString(""+chr, x, y);
        	g.rotate(-hudu,x,y);
        	x+=20;
        	randomCode.append(chr);
            System.out.println("........"+chr);
        }
        String st=randomCode.toString();
        request.getSession().setAttribute("chrr", st); 
        System.out.println(st);
        //5。画4条干扰线
        g.setColor(Color.green);
        int x1,y1,x2,y2;
        for(int i=0;i<4;i++){
        	x1=random.nextInt(width);
        	y1=random.nextInt(height);
        	x2=random.nextInt(width);
        	y2=random.nextInt(height);
        	g.drawLine(x1, y1, x2, y2);
        	
        }
        
        //6.把内存中的图片输入到客户端
        ImageIO.write(img, "jpg", response.getOutputStream());
    
		
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		doGet(request,response);

	}

}

结果:

Web作业02_第8张图片

Web作业02_第9张图片

你可能感兴趣的:(Web作业02)