SSM框架整合+拦截器+登录注销功能

一、SSM框架整合步骤:

        1、创建Web项目,导入项目所要用到的jar包

       2、配置web.xml文件      



  SSM
  
    /WEB-INF/jsp/login.jsp
  
  
  
  
    contextConfigLocation
    classpath:applicationContext-*.xml
  
  
  
  
  	springmvc
  	org.springframework.web.servlet.DispatcherServlet
  	
  		contextConfigLocation
  		classpath:springmvc-servlet.xml
  	
  	1
  
  
  	springmvc
  	/
  
  
  
  
    encodingFilter
    
	      org.springframework.web.filter.CharacterEncodingFilter
	  
    
      encoding
      UTF-8
    
    
      forceEncoding
      true
    
  
  
    encodingFilter
    /*
  
  
  
  
    org.springframework.web.context.ContextLoaderListener
  
  
  
  
    log4jConfigLocation
    classpath:log4j.properties
  
  
  
    webAppRootKey
    SSM.root
  
  
  
    
		org.springframework.web.util.Log4jConfigListener
	
  

        3、配置springmvc-servlet.xml文件



        
	
	
	
	 	
	 		
	 			
	 				
	 					application/json;charset=UTF-8
	 				
	 			
	 		 
	 		
	 			
	 				
	 					text/html;charset=UTF-8
	 					application/json
	 				
	 			
	 			
	 				
	 				 
					  WriteDateUseDateFormat
					
				
			
		
	
	
	
	
	
	
		
		
		
			
				
				
				
			
		
		
			
				
					
					
						
			
		
	
	  
	
	
		
			
			
		
	
	
	
	  
	
		 
		 
	
   
        4、配置applicationContext-mybatis.xml文件
  
  
            
     
     
    
    
	
	
	
	
    		  
			  
			  
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
    
    
    
   	
   		
   	 
   	
   	
    
    	
    	
    
    
    
      
           
    
   	        
   	    
	
	
		
		
	 
	  
	      
	       
	      
	 
		

        5、配置mybatis-config.xml文件

  
      
  
        
            
            
        
       
          
         
      
  

        6、编写数据库配置文件-----database.properties

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/smbms?useUnicode=true&characterEncoding=utf-8
user=root
password=mysql
minIdle=45
maxIdle=50
initialSize=5
maxActive=100
maxWait=100
removeAbandonedTimeout=180
removeAbandoned=true

        7、编写日志输出文件----------log4j.properties

log4j.rootLogger=debug,CONSOLE,file
#log4j.rootLogger=ERROR,ROLLING_FILE

log4j.logger.cn.smbms=debug
log4j.logger.org.apache.ibatis=debug
log4j.logger.org.mybatis.spring=debug
log4j.logger.java.sql.Connection=debug
log4j.logger.java.sql.Statement=debug
log4j.logger.java.sql.PreparedStatement=debug
log4j.logger.java.sql.ResultSet=debug

######################################################################################
# Console Appender  \u65e5\u5fd7\u5728\u63a7\u5236\u8f93\u51fa\u914d\u7f6e
######################################################################################
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.Threshold=debug
log4j.appender.CONSOLE.DatePattern=yyyy-MM-dd
log4j.appender.CONSOLE.Target=System.out
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n



######################################################################################
# Rolling File  \u6587\u4ef6\u5927\u5c0f\u5230\u8fbe\u6307\u5b9a\u5c3a\u5bf8\u7684\u65f6\u5019\u4ea7\u751f\u4e00\u4e2a\u65b0\u7684\u6587\u4ef6
######################################################################################
#log4j.appender.ROLLING_FILE=org.apache.log4j.RollingFileAppender
#log4j.appender.ROLLING_FILE.Threshold=INFO
#log4j.appender.ROLLING_FILE.File=${baojia.root}/logs/log.log
#log4j.appender.ROLLING_FILE.Append=true
#log4j.appender.ROLLING_FILE.MaxFileSize=5000KB
#log4j.appender.ROLLING_FILE.MaxBackupIndex=100
#log4j.appender.ROLLING_FILE.layout=org.apache.log4j.PatternLayout
#log4j.appender.ROLLING_FILE.layout.ConversionPattern=%d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n

######################################################################################
# DailyRolling File  \u6bcf\u5929\u4ea7\u751f\u4e00\u4e2a\u65e5\u5fd7\u6587\u4ef6\uff0c\u6587\u4ef6\u540d\u683c\u5f0f:log2009-09-11
######################################################################################
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.DatePattern=yyyy-MM-dd
log4j.appender.file.File=${SMBMS_C12_10.root}/logs/log.log
log4j.appender.file.Append=true
log4j.appender.file.Threshold=debug
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern= - (%r ms) - %d{yyyy-M-d HH:mm:ss}%x[%5p](%F:%L) %m%n

#DWR \u65e5\u5fd7
#log4j.logger.org.directwebremoting = ERROR

#\u663e\u793aHibernate\u5360\u4f4d\u7b26\u7ed1\u5b9a\u503c\u53ca\u8fd4\u56de\u503c
#log4j.logger.org.hibernate.type=DEBUG,CONSOLE 

#log4j.logger.org.springframework.transaction=DEBUG
#log4j.logger.org.hibernate=DEBUG
#log4j.logger.org.acegisecurity=DEBUG
#log4j.logger.org.apache.myfaces=TRACE
#log4j.logger.org.quartz=DEBUG

#log4j.logger.com.opensymphony=INFO  
#log4j.logger.org.apache.struts2=DEBUG  
log4j.logger.com.opensymphony.xwork2=debug

        8、创建dao、service、controller、pojo、tools、interceptor包,

        9、创建前端页面目录(/WEB-INF/jsp)和静态资源文件目录(/WEB-INF/statics)


二、编写自定义拦截器

package cn.ssm.interceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.web.servlet.handler.HandlerInterceptorAdapter;

import cn.ssm.pojo.User;
import cn.ssm.tools.Constants;

public class SysInterceptor extends HandlerInterceptorAdapter {

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
			throws Exception {
		// TODO Auto-generated method stub
		HttpSession session = request.getSession();
		User user = (User)session.getAttribute(Constants.USER_SESSION);
		if (null == user) {
			response.sendRedirect(request.getContextPath() + "/401.jsp");
			return false;
		}
		return true;
	}
}

三、编写实体类------------User.java

package cn.ssm.pojo;

import java.util.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Past;
import org.hibernate.validator.constraints.Length;
import org.hibernate.validator.constraints.NotEmpty;
import org.springframework.format.annotation.DateTimeFormat;
import com.alibaba.fastjson.annotation.JSONField;

public class User {
	private Integer id; //id 
	
	@NotEmpty(message="用户编码不能为空")
	private String userCode; //用户编码
	
	@NotEmpty(message="用户名称不能为空")
	private String userName; //用户名称
	
	@NotNull(message="密码不能为空")
	@Length(min=6,max=10,message="用户密码长度为6-10")
	private String userPassword; //用户密码	
	
	@Past(message="必须是一个过去的时间")
	//@DateTimeFormat(pattern="yyyy-MM-dd")
	@JSONField(format="yyyy-MM-dd")
	private Date birthday;  //出生日期
	
	private Integer gender;  //性别
	private String phone;   //电话
	private String address; //地址
	private Integer userRole;    //用户角色
	private Integer createdBy;   //创建者
	private Date creationDate; //创建时间
	private Integer modifyBy;     //更新者
	private Date modifyDate;   //更新时间
	
	private Integer age;//年龄
	
	private String userRoleName;    //用户角色名称
	
	private String idPicPath;	//证件照路径
	
	private String workPicPath; //工作证照片路径
	
	public String getWorkPicPath() {
		return workPicPath;
	}

	public void setWorkPicPath(String workPicPath) {
		this.workPicPath = workPicPath;
	}

	public String getIdPicPath() {
		return idPicPath;
	}

	public void setIdPicPath(String idPicPath) {
		this.idPicPath = idPicPath;
	}

	public User(){}
	
	public User(Integer id,String userCode,String userName,String userPassword,Integer gender,Date birthday,String phone,
			String address,Integer userRole,Integer createdBy,Date creationDate,Integer modifyBy,Date modifyDate){
		this.id = id;
		this.userCode = userCode;
		this.userName = userName;
		this.userPassword = userPassword;
		this.gender = gender;
		this.birthday = birthday;
		this.phone = phone;
		this.address = address;
		this.userRole = userRole;
		this.createdBy = createdBy;
		this.creationDate = creationDate;
		this.modifyBy = modifyBy;
		this.modifyDate = modifyDate;
	}
	public String getUserRoleName() {
		return userRoleName;
	}
	public void setUserRoleName(String userRoleName) {
		this.userRoleName = userRoleName;
	}
	public Integer getAge() {
		/*long time = System.currentTimeMillis()-birthday.getTime();
		Integer age = Long.valueOf(time/365/24/60/60/1000).IntegerValue();*/
		Date date = new Date();
		Integer age = date.getYear()-birthday.getYear();
		return age;
	}
	public Integer getId() {
		return id;
	}
	public void setId(Integer id) {
		this.id = id;
	}
	public String getUserCode() {
		return userCode;
	}
	public void setUserCode(String userCode) {
		this.userCode = userCode;
	}
	public String getUserName() {
		return userName;
	}
	public void setUserName(String userName) {
		this.userName = userName;
	}
	public String getUserPassword() {
		return userPassword;
	}
	public void setUserPassword(String userPassword) {
		this.userPassword = userPassword;
	}
	public Integer getGender() {
		return gender;
	}
	public void setGender(Integer gender) {
		this.gender = gender;
	}
	public Date getBirthday() {
		return birthday;
	}
	public void setBirthday(Date birthday) {
		this.birthday = birthday;
	}
	public String getPhone() {
		return phone;
	}
	public void setPhone(String phone) {
		this.phone = phone;
	}
	public String getAddress() {
		return address;
	}
	public void setAddress(String address) {
		this.address = address;
	}
	public Integer getUserRole() {
		return userRole;
	}
	public void setUserRole(Integer userRole) {
		this.userRole = userRole;
	}
	public Integer getCreatedBy() {
		return createdBy;
	}
	public void setCreatedBy(Integer createdBy) {
		this.createdBy = createdBy;
	}
	public Date getCreationDate() {
		return creationDate;
	}
	public void setCreationDate(Date creationDate) {
		this.creationDate = creationDate;
	}
	public Integer getModifyBy() {
		return modifyBy;
	}
	public void setModifyBy(Integer modifyBy) {
		this.modifyBy = modifyBy;
	}
	public Date getModifyDate() {
		return modifyDate;
	}
	public void setModifyDate(Date modifyDate) {
		this.modifyDate = modifyDate;
	}
}

四、dao层编码----------------UserMapper.java    UserMapper.xml

package cn.ssm.dao.user;

import org.apache.ibatis.annotations.Param;

import cn.ssm.pojo.User;

public interface UserMapper {
	/**
	 * 
	 * 通过userCode获取用户
	 * @param userCode
	 * @return
	 * @throws Exception
	 */
	public User getLoginByUserCode(@Param("userCode") String userCode) throws Exception;
}



	

五、service层编码----------UserService.java、 UserServiceImpl.java

package cn.ssm.service.user;

import cn.ssm.pojo.User;

public interface IUserService {

	/**
	 * 登录
	 * @param userCode
	 * @param password
	 * @return
	 * @throws Exception
	 */
	public User login(String userCode,String password) throws Exception;
}
package cn.ssm.service.user;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import cn.ssm.dao.user.UserMapper;
import cn.ssm.pojo.User;

@Service
public class UserServiceImpl implements IUserService {

	
	@Resource
	private UserMapper userMapper;
	
	@Override
	public User login(String userCode, String userPassword) throws Exception {
		User user = null;
		user = userMapper.getLoginByUserCode(userCode);
		//匹配密码
		if (null != user) {
			if (!user.getUserPassword().equals(userPassword)) {
				user = null;
			}
		}
		return user;
	}

}

六、controller层编码-----------UserController.java

package cn.ssm.controller;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.apache.tomcat.util.descriptor.web.LoginConfig;
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.RequestParam;

import cn.ssm.pojo.User;
import cn.ssm.service.user.IUserService;
import cn.ssm.tools.Constants;
import sun.util.logging.resources.logging_de;

@Controller
@RequestMapping("/user/")
public class UserController {

	@Resource
	private IUserService iUserService;
	
	@RequestMapping(value = "login.html")
	public String login() {
		
		return "login";
	}
	
	@RequestMapping(value = "logout.html")
	public String logout(HttpSession session) {
		session.removeAttribute(Constants.USER_SESSION);
		return "login";
	}
	
	@RequestMapping(value = "dologin.html",method = RequestMethod.POST)
	public String doLogin(@RequestParam String userCode,@RequestParam String userPassword,HttpServletRequest request,HttpSession session) {
		User user = iUserService.login(userCode, userPassword);
		if (null != user) {
			session.setAttribute(Constants.USER_SESSION, user);
			return "redirect:sys/main.html";
		}
		return "login";
	}
	
	@RequestMapping(value = "sys/main.html")
	public String main() {
		
		return "frame";
	}
	
}

七、前端页面编写-------以后补上  下班咯





你可能感兴趣的:(Java学习)