spring+springmvc+mybatis+jQuery easyUI案例

spring+springmvc+mybatis+jQuery easyUI案例

项目运行的截图:

spring+springmvc+mybatis+jQuery easyUI案例_第1张图片
下面是今天做的一个小的登录测试程序:目的是练习如何添加验证码和jQuery easyUI中的数据表格(datagrid)以及spring+springmvc+mybatis的整合
用到的技术:spring+springmvc+mybatis+jQuery easyUI

下面就让我们来看看如何给登录添加验证码验证以及数据表格的使用:
1、首先创建一个web工程,其工程的目录结构如图所示:
spring+springmvc+mybatis+jQuery easyUI案例_第2张图片
项目需要用到的jar如图所示:
spring+springmvc+mybatis+jQuery easyUI案例_第3张图片spring+springmvc+mybatis+jQuery easyUI案例_第4张图片
2、由于用到了jQuery easyUI所以需要用到easyUI插件:可以到官网上下载http://www.jeasyui.net/download/;下载之后将其解压,把解压后的文件放到工程对应的目录下面,这里我是放在js包下spring+springmvc+mybatis+jQuery easyUI案例_第5张图片
3、创建数据库 tb_user:这里就不在说明了。想必大家都会建表把。这里附上一张表的截图
spring+springmvc+mybatis+jQuery easyUI案例_第6张图片
***注意这里我用的是MySQL数据库
配置文件相关目录结构:
spring+springmvc+mybatis+jQuery easyUI案例_第7张图片
web.xml


  easyUI
  
    index.html
    index.htm
    index.jsp
    default.html
    default.htm
    default.jsp
  
    
      
        org.springframework.web.context.ContextLoaderListener  
      
      
      
        contextConfigLocation  
        classpath:spring/applicationContext-*.xml  
      
      
      
        dispatcher  
        org.springframework.web.servlet.DispatcherServlet  
          
            contextConfigLocation  
            classpath:spring/applicationContext-mvc.xml  
          
        1  
      
      
      
        dispatcher  
        /  
      
    
     default
     *.css



    default
    *.gif

 
    
 
     default
     *.png
 
    
 
     default
     *.js
 
 
 default
 *.jpg
 
      
      
        characterEncodingFilter  
        org.springframework.web.filter.CharacterEncodingFilter  
          
            encoding  
            UTF-8  
          
              
            forceEncoding      
            true      
          
      
      
        characterEncodingFilter  
        /*  
      


4、spring和mybatis整合的配置文件:applicationContext-common.xml

  
      
        
        
    
		
		
		
		
	
	
      
      
          
          
          
         
          
      
      
          
          
      
  

5、spring与springmvc整合的配置文件:applicationContext-mvc.xml

  
      
      
      
      
        
            
              
                
              
            
      
      
          
              
                  
                text/html;charset=UTF-8      
                  
              
      
          
              
              
              
       
  

applicationContext-bean..xml

  
      
      
      
      
    
    
      
      
  
config.xml

  
  
      
            
            
            
            
            
            
            
      
      
          
      
  
jdbc.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&zeroDateTimeBehavior=convertToNull
username=root
password=smilelife



6、配置文件创建完成之后,需要在项目中创建表对应的实体类、接口文件、实体类的映射文件

这里我把实体类和映射文件都放在了com.easyui.model包下了:spring+springmvc+mybatis+jQuery easyUI案例_第8张图片
User.java
package com.easyui.model;
import java.util.Date;

public class User {
	private Integer userId;
	private String loginname;
	private String username;
	private String password;
	private String rights;
	private Integer status;
	private Integer roleId;
	private Date lastLogin;
	
	
	private Date lastLoginStart;
	private Date lastLoginEnd;
	
	public Integer getUserId() {
		return userId;
	}
	public void setUserId(Integer userId) {
		this.userId = userId;
	}
	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;
	}
	public Integer getStatus() {
		return status;
	}
	public void setStatus(Integer status) {
		this.status = status;
	}
	public String getRights() {
		return rights;
	}
	public void setRights(String rights) {
		this.rights = rights;
	}
	public String getLoginname() {
		return loginname;
	}
	public void setLoginname(String loginname) {
		this.loginname = loginname;
	}
	
	public Integer getRoleId() {
		return roleId;
	}
	public void setRoleId(Integer roleId) {
		this.roleId = roleId;
	}
	public Date getLastLogin() {
		return lastLogin;
	}
	public void setLastLogin(Date lastLogin) {
		this.lastLogin = lastLogin;
	}
	public Date getLastLoginStart() {
		return lastLoginStart;
	}
	public void setLastLoginStart(Date lastLoginStart) {
		this.lastLoginStart = lastLoginStart;
	}
	public Date getLastLoginEnd() {
		return lastLoginEnd;
	}
	public void setLastLoginEnd(Date lastLoginEnd) {
		this.lastLoginEnd = lastLoginEnd;
	}
	
}

UserMapper.xml

  
  
      
      
		
		
		
		
		
		
		
      
      
    
    
	
  
UserMapper.java
package com.easyui.mapper;

import java.util.List;
import java.util.Map;

import com.easyui.model.User;


public interface UserMapper extends BaseMapper{
	//查询所有用户
	 List selAllUser();
	//查询所有用户数量
	public int selAllUserNum();
	//根据根据用户名和密码来判断该用户是否存在
	public User selUser(User user);
	

}
BaseMapper.java 里面不声明任何方法

7、这些建完之后,需要创建业务层service
UserService.java
package com.easyui.service;

import java.util.List;
import java.util.Map;

import com.easyui.model.User;

public interface UserService {
	//用户列表
		public List selAllUser();
		//根据用户名和密码来查询该用户
		public User selUser(String loginname,String password);

}

UserServiceImpl.java
package com.easyui.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.easyui.mapper.UserMapper;
import com.easyui.model.User;
import com.easyui.service.UserService;

@Service
public class UserServiceImpl implements UserService {
	@Autowired
	private UserMapper userMapper;

	@Override
	public List selAllUser() {
		
		return userMapper.selAllUser();
	}

	@Override
	public User selUser(String loginname, String password) {
		User user=new User();
		user.setLoginname(loginname);
		user.setPassword(password);
		return userMapper.selUser(user);
	}
	

}

8、下面就是控制层controller
①、首先是控制登录的LoginController.java
package com.easyui.controller;

import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.servlet.ModelAndView;

import com.easyui.model.User;
import com.easyui.service.UserService;
import com.easyui.util.Const;



@Controller
public class LoginController {

	@Autowired
	private UserService userService;
	
	/**
	 * 访问登录页
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.GET)
	public String loginGet(){
		return "login";
	}
	/*@RequestMapping(value="/login")
	public ModelAndView login(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("login");
		return mv;
	}*/
	
	/**
	 * 请求登录,验证用户
	 * @param session
	 * @param loginname
	 * @param password
	 * @param code
	 * @return
	 */
	@RequestMapping(value="/login",method=RequestMethod.POST)
	public ModelAndView loginPost(HttpSession session,@RequestParam String loginname,@RequestParam String password,@RequestParam String code){
		String sessionCode = (String)session.getAttribute(Const.SESSION_SECURITY_CODE);
		ModelAndView mv = new ModelAndView();
		
		String errInfo = "";
		if(sessionCode.equalsIgnoreCase(code)){
			User user = userService.selUser(loginname, password);
			if(user!=null && password.equals(user.getPassword())){
				
				session.removeAttribute(Const.SESSION_SECURITY_CODE);
				
				
			}else{
				errInfo = "用户名或密码有误!";
			}
		}else{
			errInfo = "验证码输入有误!";
		}
		if(null==errInfo || "".equals(errInfo) ||"null".equals(errInfo)){
			mv.setViewName("users");
		}
		else{
			mv.addObject("errInfo", errInfo);
			mv.addObject("loginname",loginname);
			mv.addObject("password",password);
			mv.setViewName("login");
		}
		
		return mv;
	}
	
	
}

其中String sessionCode = (String)session.getAttribute(Const.SESSION_SECURITY_CODE);这句代码是来获取验证码的
②、验证码相关代码:SecCodeController.java
package com.easyui.controller;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics2D;
import java.awt.font.FontRenderContext;
import java.awt.geom.Rectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.easyui.util.Const;


/**
 * @author Administrator
 * 验证码生成类
 */
@Controller
@RequestMapping("/code")
public class SecCodeController {

	@RequestMapping
	public void generate(HttpSession session,HttpServletResponse response){
		ByteArrayOutputStream output = new ByteArrayOutputStream();
		String code = drawImg(output);
		session.setAttribute(Const.SESSION_SECURITY_CODE, code); //放入session
		//System.out.println(session.getAttribute(Const.SESSION_SECURITY_CODE));
		try {
			ServletOutputStream out = response.getOutputStream();
			output.writeTo(out);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}
	
	private String drawImg(ByteArrayOutputStream output){
		String code = "";
		for(int i=0; i<4; i++){
			code += randomChar();
		}
		int width = 70;
		int height = 25;
		BufferedImage bi = new BufferedImage(width,height,BufferedImage.TYPE_3BYTE_BGR);
		Font font = new Font("Times New Roman",Font.PLAIN,20);
		Graphics2D g = bi.createGraphics();
		g.setFont(font);
		Color color = new Color(66,2,82);
		g.setColor(color);
		g.setBackground(new Color(226,226,240));
		g.clearRect(0, 0, width, height);
		FontRenderContext context = g.getFontRenderContext();
		Rectangle2D bounds = font.getStringBounds(code, context);
		double x = (width - bounds.getWidth()) / 2;
		double y = (height - bounds.getHeight()) / 2;
		double ascent = bounds.getY();
		double baseY = y - ascent;
		g.drawString(code, (int)x, (int)baseY);
		g.dispose();
		try {
			ImageIO.write(bi, "jpg", output);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return code;
	}
	
	private char randomChar(){
		Random r = new Random();
		String s = "ABCDEFGHJKLMNPRSTUVWXYZ0123456789";
		return s.charAt(r.nextInt(s.length()));
	}
}
其中用到了一个工具类:Const.java
package com.easyui.util;

import org.springframework.context.ApplicationContext;

public class Const {
	public static final String SESSION_SECURITY_CODE = "sessionSecCode";
}

③、UserController.java
package com.easyui.controller;

import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.easyui.model.User;
import com.easyui.service.UserService;

@Controller
@RequestMapping(value="/easyui")
public class UserController {
	@Autowired
	private UserService userService;
	
	/*@RequestMapping(value="/main")
	public ModelAndView main(){
		ModelAndView mv=new ModelAndView();
		mv.setViewName("users");
		return mv;
		
	}
	@RequestMapping(value="/list.do")
	@ResponseBody
	 public Map selectAllUser(@RequestParam String page,@RequestParam String rows){
	    	return userService.selAllUser(page, rows);
	    }*/
	@RequestMapping(value="/list")
	@ResponseBody
	public Object selectAllUser(Model model){
		List listUser=userService.selAllUser();
		return listUser;
	}

}

9、下面就是创建视图:
spring+springmvc+mybatis+jQuery easyUI案例_第9张图片
用到就是红色框框出来的部分:其他的没有用到
login.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>




用户权限管理系统后台




Copyright © 2011 xxx

users.jsp
<%@ page language="java" contentType="text/html; charset=utf-8"  
    pageEncoding="UTF-8"%>  
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>  
  
<%  
    String path = request.getContextPath();  
    String basePath = request.getScheme() + "://"  
            + request.getServerName() + ":" + request.getServerPort()  
            + path ;  
%>  
  
  
  
用户列表  

    
    
    



  
  
  
    

至此该简单的spring+springmvc+mybatis+jQuery easyUI小项目就完成了,按照上面的步骤,就可以实现。写的不好还请多多担待,如有什么问题,希望大家能够指出来。大家互相学习。。。


你可能感兴趣的:(spring)