springMVC实现登录的小例子

今天,学习使用springMVC实现登录,简单了解了一下这个mvc,很粗浅,我参考的博文如下,写的非常详细

本文章知道简单的能够搭建Sping MVC环境进行代码基础开发。

根据Spring的体系结构图画出Spring开发过程中涉及的文件和交流细节:

springMVC实现登录的小例子_第1张图片

Spring MVC流程说明:

  1. 用户请求http://127.0.0.1:8080/user/login

  2. 根据org.springframework.web.servlet.DispatcherServlet配置的xml文件找到相应处理器

  3. 根据映射到Contorller处理器的用户请求访问业务Service和数据访问DAO层处理得出返回结果到前端JSP页面

  4. 用户通过返回结果得到相应的信息

    springMVC实现登录的小例子_第2张图片

 

 

在开发工具中新增Java Web项目,项目结构分布说明图如下:

 springMVC实现登录的小例子_第3张图片

 

lib列表说明如下图:

springMVC实现登录的小例子_第4张图片

 

项目核心文件列表说明如下:

(1)jdbc-context.xml spring的jdbc配置

(2)springmvc-servlet.xml  sping mvc相关的配置文件

(3)web.xml  配置spring过滤器和编码

(4)LoginController.java   登录功能的控制器

(5)LoginService.java 登录功能业务接口

(6)LoginServiceImpl.java 登录功能业务实现层

(7)BaseDao.java 登录功能的数据访问接口

(8)BaseDaoImpl.java 登录功能的数据访问层

(9)DBUtil.java 数据操作公共类

(10)login.jsp  登录页面

(11)database.properties 数据库访问配置

(12)User.java 实体

源码访问如下:

(1)jdbc-context.xml spring的jdbc配置



     
      
     
      
      
      
      
        
        
      
      
      
        
       
        
     
      
     
      
     
      
     
     
      
     
     
      
       
       
       
      
     
      
     
     
      
     
      


(2)springmvc-servlet.xml  sping mvc相关的配置文件



     
    
    
     
    
    
     
    
    
     
      
      
   
     
    
     
     
    
    
     
    
    
     
     
    
     


(3)web.xml



  
  
 contextConfigLocation
 classpath:/META-INF/jdbc-context.xml
    
   
  
   org.springframework.web.context.ContextLoaderListener
  
  
  
   spring-mvc
   org.springframework.web.servlet.DispatcherServlet
   
    contextConfigLocation
    classpath:/META-INF/springmvc-servlet.xml
   
   1
  
   
  
   spring-mvc
   /
  
   
  
   encodingFilter
   org.springframework.web.filter.CharacterEncodingFilter
  
   
  
   encodingFilter
   /*
  
   
  
    index.jsp
  


(4)LoginController.java   登录功能的控制器

/**
 * 
 */
package com.springTest.web.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import com.springTest.po.User;
import com.springTest.service.LoginService;
import com.springTest.web.BaseController;
/**
 * 登陆方法
 * @author tushen
 * @date Nov 4, 2011
 */
@Controller
public class LoginController extends BaseController{
 @Autowired
 private LoginService loginService;
  
 @RequestMapping(value="/user/login",method=RequestMethod.GET)
 public String login(){
   
  return "login";
 }
  
  
  
 @RequestMapping(value="/user/login",method=RequestMethod.POST)
 public String logon(String userName,String passWord){
  User user = null;
  try {
   user = loginService.getUser(userName, passWord);
  } catch (RuntimeException e) {
  }
  if(user!=null){
   return "MyHome";
  }else{
   return "login";
  }
 }
  
 @RequestMapping(value="/user/register",method=RequestMethod.POST)
 public String register(User user){
  loginService.addUser(user);
  return "login";
 }
  
 @RequestMapping(value="/user/toRegister",method=RequestMethod.GET)
 public String toRegister(){
  return "register";
 }
}


(5)LoginService.java 登录功能业务接口

/**
 * 
 */
package com.springTest.service;
import com.springTest.po.User;
/**
 * @author tushen
 * @date Nov 4, 2011
 */
public interface LoginService {
 public User getUser(String userName,String password);
 public void addUser(User user);
  
}


(6)LoginServiceImpl.java 登录功能业务实现层

/**
 * 
 */
package com.springTest.service.impl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.springTest.dao.BaseDao;
import com.springTest.po.User;
import com.springTest.service.LoginService;
/**
 * @author tushen
 * @date Nov 4, 2011
 */
@Service
public class LoginServiceImpl implements LoginService {
 @Autowired
 private BaseDao baseDao;
 static String addUser = "insert into user(username,password,first_name,last_name,birthday,age) values(:userName,:passWord,:firstName,:lastName,:birthday,:age);";
 static String getUser = "select * from user where username = ? and password = ?";
  
 @Override
 public User getUser(String userName, String password) {
  User user = baseDao.getObject(getUser, User.class, new Object[]{userName,password});
  return user;
 }
 @Override
 public void addUser(User user) {
  baseDao.saveOrUpdateObject(addUser, user);
 }
}


(7)BaseDao.java 登录功能的数据访问接口

/**
 * 
 */
package com.springTest.dao;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
/**
 * @author tushen
 * @date Nov 5, 2011
 */
public interface BaseDao {
 /**
  * 保存或者更新实体
  * @param sql
  * @param entry
  */
  void saveOrUpdateObject(String sql,T entry);
  
 /**
  * 查询实体列表
  * @param sql
  * @param className
  * @param obj
  * @return
  */
  List getObjList(String sql,Class className,Object[] objs);
  
 /**
  * 查询实体
  * @param 
  * @param sql
  * @param objs
  * @return
  */
  T getObject(String sql,Class clazz,Object[] objs);
  
 /**
  * 查询一个Map集合
  * @param sql
  * @param objs
  * @return
  */
 Map find(String sql,Object[] objs);
  
 /**
  * 批量操作
  * @param sql
  * @param objLs
  */
 void batchOperate(String sql,List objLs);
  
 /**
  * 判断实体是否存在
  * @param sql
  * @param obj
  * @return
  */
 int isExist(String sql,Object[] obj);
  
 /**
  * 编辑操作
  * @param sql
  * @param obj
  * @return
  */
 int editObject(String sql,Object[] obj);
}


(8)BaseDaoImpl.java 登录功能的数据访问层

/**
 * 
 */
package com.springTest.dao.impl;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import com.springTest.dao.BaseDao;
import com.springTest.util.DBUtil;
/**
 * @author tushen
 * @date Nov 5, 2011
 */
@Repository
public class BaseDaoImpl implements BaseDao {
 @Autowired
 private DBUtil util;
 @Override
 public void batchOperate(String sql, List objs) {
  util.batchOperate(sql, objs);
 }
 @Override
 public int editObject(String sql, Object[] obj) {
  return util.editObject(sql, obj);
 }
 @Override
 public Map find(String sql, Object[] objs) {
  return util.getMap(sql, objs);
 }
 @Override
 public  List getObjList(String sql,
   Class className, Object[] objs) {
  return (List)util.getObjList(sql, className, objs);
 }
 @Override
 public int isExist(String sql, Object[] obj) {
  return util.isExist(sql, obj);
 }
 @Override
 public  void saveOrUpdateObject(String sql, T entry) {
  util.addOrUpdate(sql, entry);
 }
 @Override
 public  T getObject(String sql,Class clazz,Object[] objs) {
  return (T)util.getObject(sql, clazz, objs);
 }
}


(9)DBUtil.java 数据操作公共类

/**
 * 
 */
package com.springTest.util;
import java.io.Serializable;
import java.util.List;
import java.util.Map;
import javax.annotation.Resource;
import javax.sql.DataSource;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.namedparam.BeanPropertySqlParameterSource;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.jdbc.core.simple.ParameterizedBeanPropertyRowMapper;
import org.springframework.jdbc.core.simple.SimpleJdbcTemplate;
import org.springframework.stereotype.Repository;
/**
 * @author tushen
 * @date Nov 5, 2011
 */
@Repository(value="util")
public class DBUtil{
 private Log log = LogFactory.getLog(DBUtil.class);
  
 private SimpleJdbcTemplate simpleJdbcTemplate;
  
 /**
  * 添加或者更新数据
  * @param sql
  * @param obj
  * @return
  */
 public Integer addOrUpdate(String sql,Object obj){
  Integer id = 0;
  try {
   id = simpleJdbcTemplate.update(sql, new BeanPropertySqlParameterSource(obj));
  } catch (Exception e) {
   log.info(e);
   throw new DaoException("数据库操作失败!",e);
  }
  return id;
 }
  
 /**
  * 获取List集合
  * @param sql
  * @param className
  * @param obj
  * @return
  */
 @SuppressWarnings("unchecked")
 public List getObjList(String sql,Class className,Object[] obj){
   
  List array = null;
  try {
   array =  simpleJdbcTemplate.queryForList(sql,
        ParameterizedBeanPropertyRowMapper.newInstance(className),
        obj);
  } catch (Exception e) {
   log.info(e);
   throw new DaoException("数据库操作失败!",e);
  }
  return array;
 }
  
 /**
  * 获取Map集合值
  * @param sql
  * @param obj
  * @return
  */
 public Map getMap(String sql,Object[] obj){
   
  Map map = null;
  try {
   map = simpleJdbcTemplate.queryForMap(sql, obj);
  } catch (Exception e) {
   log.info(e);
   throw new DaoException("数据库操作失败!",e);
  }
   
  return map;
 }
  
 /**
  * 获取相应的Object
  * @param sql
  * @param className
  * @param obj
  * @return
  */
 public Object getObject(String sql,Class className,Object[] obj){
   
  Object object = null;
  try {
   object = simpleJdbcTemplate.queryForObject(sql, BeanPropertyRowMapper.newInstance(className), obj);
  } catch (DataAccessException e) {
   log.info(e);
   throw new DaoException("数据库操作失败!",e);
  }
  return object;
 }
  
 /**
  * 批量操作
  * @param sql
  * @param obj
  * @return
  */
 public int[] batchOperate(String sql,List obj){
   
  int[] a = null;
  try {
   a = simpleJdbcTemplate.batchUpdate(sql, 
             SqlParameterSourceUtils.createBatch(obj.toArray()));
  } catch (Exception e) {
   log.info(e);
   throw new DaoException("数据库操作失败!",e);
  }
  return a;
 }
  
 /**
  * 检查是否有值
  * @param sql
  * @param obj
  * @return
  */
 public int isExist(String sql,Object[] obj){
  int index = 0;
  try {
   index = simpleJdbcTemplate.queryForInt(sql, obj);
  } catch (Exception e) {
   log.info(e);
   throw new DaoException("数据库操作失败!",e);
  }
  return index;
 }
  
 /**
  * 编辑操作(增删改查都可以)
  * @param sql
  * @param obj
  * @return
  */
 public int editObject(String sql,Object[] obj){
  int index = 0;
  try {
   index = simpleJdbcTemplate.update(sql, obj);
  } catch (DataAccessException e) {
   log.info(e);
   throw new DaoException("数据库操作失败!",e);
  }
  return index;
 }
  
 /**
  * @param simpleJdbcTemplate the simpleJdbcTemplate to set
  */
 @Resource(name="dataSource")
 public void setSimpleJdbcTemplate(DataSource dataSource) {
  this.simpleJdbcTemplate = new SimpleJdbcTemplate(dataSource);
 }
}


(10)login.jsp  登录页面

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>







	
userName:
passWord:


(11)database.properties 数据库访问配置


mysql.driverclass=com.mysql.jdbc.Driver
mysql.jdbcurl=jdbc:mysql://127.0.0.1:3306/test
mysql.user=root
mysql.password=admin

(12)User.java 实体

/**
 * 
 */
package com.springTest.po;
import java.io.Serializable;
/**
 * @author tushen
 * @date Nov 4, 2011
 */
public class User implements Serializable{
 private Integer id;
 private String userName;  //用户名
 private String passWord;  //密码
 private String firstName; 
 private String lastName;
 private String birthday;  //生日
 private Integer age;
 /**
  * @return the id
  */
 public Integer getId() {
  return id;
 }
 /**
  * @param id the id to set
  */
 public void setId(Integer id) {
  this.id = id;
 }
 /**
  * @return the firstName
  */
 public String getFirstName() {
  return firstName;
 }
 /**
  * @param firstName the firstName to set
  */
 public void setFirstName(String firstName) {
  this.firstName = firstName;
 }
 /**
  * @return the lastName
  */
 public String getLastName() {
  return lastName;
 }
 /**
  * @param lastName the lastName to set
  */
 public void setLastName(String lastName) {
  this.lastName = lastName;
 }
 /**
  * @return the age
  */
 public Integer getAge() {
  return age;
 }
 /**
  * @param age the age to set
  */
 public void setAge(Integer age) {
  this.age = age;
 }
 /**
  * @return the userName
  */
 public String getUserName() {
  return userName;
 }
 /**
  * @param userName the userName to set
  */
 public void setUserName(String userName) {
  this.userName = userName;
 }
 /**
  * @return the passWord
  */
 public String getPassWord() {
  return passWord;
 }
 /**
  * @param passWord the passWord to set
  */
 public void setPassWord(String passWord) {
  this.passWord = passWord;
 }
 /**
  * @return the birthday
  */
 public String getBirthday() {
  return birthday;
 }
 /**
  * @param birthday the birthday to set
  */
 public void setBirthday(String birthday) {
  this.birthday = birthday;
 }
  
}


附录数据库脚步如下:

/*
SQLyog v10.2 
MySQL - 5.0.87-community-nt : Database - test
*********************************************************************
*/
 
/*!40101 SET NAMES utf8 */;
/*!40101 SET SQL_MODE=''*/;
/*!40014 SET @OLD_UNIQUE_CHECKS=@@UNIQUE_CHECKS, UNIQUE_CHECKS=0 */;
/*!40014 SET @OLD_FOREIGN_KEY_CHECKS=@@FOREIGN_KEY_CHECKS, FOREIGN_KEY_CHECKS=0 */;
/*!40101 SET @OLD_SQL_MODE=@@SQL_MODE, SQL_MODE='NO_AUTO_VALUE_ON_ZERO' */;
/*!40111 SET @OLD_SQL_NOTES=@@SQL_NOTES, SQL_NOTES=0 */;
CREATE DATABASE /*!32312 IF NOT EXISTS*/`test` /*!40100 DEFAULT CHARACTER SET utf8 */;
USE `test`;
/*Table structure for table `user` */
DROP TABLE IF EXISTS `user`;
CREATE TABLE `user` (
  `username` varchar(64) default NULL,
  `password` varchar(32) default NULL,
  `first_name` varchar(32) default NULL,
  `last_name` varchar(32) default NULL,
  `birthday` date default NULL,
  `age` int(11) default NULL
) ENGINE=InnoDB DEFAULT CHARSET=utf8;
/*Data for the table `user` */
LOCK TABLES `user` WRITE;
insert  into `user`(`username`,`password`,`first_name`,`last_name`,`birthday`,`age`) 
values ('admin','123456',NULL,NULL,NULL,NULL),('liaoxj','123456','liao','xiongjian','1988-06-21',25),('changjiang','123456','zhang','liang','2013-01-01',25);
UNLOCK TABLES;
/*!40101 SET SQL_MODE=@OLD_SQL_MODE */;
/*!40014 SET FOREIGN_KEY_CHECKS=@OLD_FOREIGN_KEY_CHECKS */;
/*!40014 SET UNIQUE_CHECKS=@OLD_UNIQUE_CHECKS */;
/*!40111 SET SQL_NOTES=@OLD_SQL_NOTES */;



感谢

http://www.open-open.com/lib/view/open1392881407548.html

你可能感兴趣的:(java,spring,mvc)