SpringMVC_Spring_Hibernate模版

开发工具:eclipse MSR.2;

数据库:mysql5;

注:1)web.xml:配置错误页面

2)hibernate.cfg.xml:数据库连接配置,配置model类完整包名

3)applicationContext.xml:配置基础包,配置数据库连接文件

4)Contants.java:添加自己的发件人邮箱和密码

5)BaseController.java:注意发送的邮件的内容的网址连接

6)MyConfig.java:注意配置 basePackages = "com.ssh.controller"

7)MyWebApplicationInitializer.java:注意配置classpath:applicationContext.xml

jar包:

SpringMVC_Spring_Hibernate模版_第1张图片

项目模版完整截图:

SpringMVC_Spring_Hibernate模版_第2张图片

web.xml



	SpringMVC_Spring_Hibernate

	
		index.html
		index.htm
		index.jsp
		default.html
		default.htm
		default.jsp
	

	
	
		404
		/error.jsp
	
	
		500
		/error.jsp
	

applicationContext.xml



     
  
    
    
    
    
	
	
	
	
		
			classpath:hibernate.cfg.xml
		
	 
	
	
	   
	       
	   
	
	
	  
	
hibernate.cfg.xml






    
	    
	    com.mysql.jdbc.Driver
	    jdbc:mysql://localhost:3306/test
	    root
	    123456
	
	    
	
	    20
		5
		120
		100
		120
		2
		false
		
		false
	    
	    org.hibernate.dialect.MySQLDialect
	
	    
	    org.hibernate.cache.internal.NoCacheProvider
	
	    
	    true
	
	    
	    update
	    
	    true
	    
	    true
	    
	    

  	

log4j.properties(可删除)
### setting
#log4j.rootLogger = debug,stdout,D,E
log4j.rootLogger = OFF,stdout,D,E

### print out information to Console
log4j.appender.stdout = org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target = System.out
log4j.appender.stdout.layout = org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern = [%-5p] %d{yyyy-MM-dd HH:mm:ss,SSS} method:%l%n%m%n

###  DEBUG to = E://logs/error.log ###
log4j.appender.D = org.apache.log4j.DailyRollingFileAppender
log4j.appender.D.File = C://logs/log.log
log4j.appender.D.Append = true
log4j.appender.D.Threshold = DEBUG 
log4j.appender.D.layout = org.apache.log4j.PatternLayout
log4j.appender.D.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

### ERROR to = E://logs/error.log ###
log4j.appender.E = org.apache.log4j.DailyRollingFileAppender
log4j.appender.E.File =C://logs/error.log 
log4j.appender.E.Append = true
log4j.appender.E.Threshold = ERROR 
log4j.appender.E.layout = org.apache.log4j.PatternLayout
log4j.appender.E.layout.ConversionPattern = %-d{yyyy-MM-dd HH:mm:ss}  [ %t:%r ] - [ %p ]  %m%n

error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" isErrorPage="true"%>





ERROR



	

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





忘记密码

	
	
	
	
	
	
	
 






	
head.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8" errorPage="error.jsp"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>




	















	


head


	

	
	

	

home.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>





home


	<%@ include file="head.jsp" %>
	

home

index.jsp

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





login

	
	
	
	
	
	
	
 







	
Log.java(可删除)

package com.ssh.anno;

import java.lang.annotation.*;

@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Log {

	/** 要执行的操作类型比如:add操作 **/
	public String operationType() default "";

	/** 要执行的具体操作比如:添加用户 **/
	public String add() default "";

}
MyConfig.java

package com.ssh.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.web.servlet.ViewResolver;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;

/**
 * 配置类 视图解析器
 *
 */
@Configuration
@Profile(value = { "default" })
@EnableWebMvc
@ComponentScan(basePackages = "com.ssh.controller")
public class MyConfig extends WebMvcConfigurerAdapter {

	@Bean
	public ViewResolver viewResolver() {
		InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
		viewResolver.setViewClass(JstlView.class);
//		viewResolver.setPrefix("/");
//		viewResolver.setSuffix(".jsp");
		viewResolver.setOrder(1);
		return viewResolver;
	}

}
MyWebApplicationInitializer.java

package com.ssh.config;

import javax.servlet.FilterRegistration;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.ContextLoaderListener;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.filter.CharacterEncodingFilter;
import org.springframework.web.servlet.DispatcherServlet;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter;

/**
 * 初始化类 该类添加监听用于启动spring容器,注册配置类以及添加映射器
 * 
 */
public class MyWebApplicationInitializer extends WebMvcConfigurerAdapter implements WebApplicationInitializer {

	@Override
	public void onStartup(ServletContext context) throws ServletException {

		// 添加Listener 完成Spring容器建立
		context.setInitParameter("contextConfigLocation", "classpath:applicationContext.xml");
		context.addListener(new ContextLoaderListener());

		AnnotationConfigWebApplicationContext webContext = new AnnotationConfigWebApplicationContext();
		webContext.register(MyConfig.class);

		CharacterEncodingFilter filter = new CharacterEncodingFilter("UTF-8");
		FilterRegistration.Dynamic register2 = context.addFilter("encodingFilter", filter);
		register2.addMappingForUrlPatterns(null, false, "/*");

		ServletRegistration.Dynamic dispatcher = context.addServlet("dispatcher", new DispatcherServlet(webContext));
		dispatcher.addMapping("/");

	}

	@Override
	public void addResourceHandlers(ResourceHandlerRegistry registry) {
		// 注册静态文件目录,防止静态文件被Spring MVC拦截
		registry.addResourceHandler("/js/**").addResourceLocations("/js/");
		registry.addResourceHandler("/css/**").addResourceLocations("/css/");
	}

}
ChineseCodeFilter.java

package com.ssh.util;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;

@WebFilter(filterName = "ChineseCodeFilter", urlPatterns = "/*")
public class ChineseCodeFilter implements Filter {

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {

	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {

		request.setCharacterEncoding("UTF-8"); //
		response.setContentType("text/html;charsset=utf-8");
		chain.doFilter(request, response);
	}

	@Override
	public void destroy() {

	}

}
Contants.java

package com.ssh.util;

/**
 * 常量
 * 
 * @author xingyang
 *
 */
public class Contants {

	/**
	 * SMTP Host 简单邮件传送协议服务器
	 */
	public static final String HOST = "smtp.163.com";

	/**
	 * 邮局协议,用于电子邮件的接收
	 */
	public static final String PROTOCOL = "smtp";

	/**
	 * 邮箱服务端口号
	 */
	public static final int PORT = 25;

	/**
	 * 发件人的email
	 */
	public static final String FROM = "";

	/**
	 * 发件人显示名称
	 */
	public static final String MAIL_USER = "用户注册帐号激活";
	
	/**
	 * 发件人密码
	 */
	public static final String PWD = "";

}
SessionFactoryHelper.java
package com.ssh.util;

import org.hibernate.SessionFactory;
import org.hibernate.boot.MetadataSources;
import org.hibernate.boot.registry.StandardServiceRegistry;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;

/**
 * 
 * 尝试获取SessionFactory
 * 
 * @author xingyang
 *
 */
public class SessionFactoryHelper {

	private static SessionFactory sessionFactory;

	public static SessionFactory getSessionFactory() {

		// 建立一个标准的服务 和注册, 用户可以定制
		final StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build();
		try {
			sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory();
		} catch (Exception e) {
			StandardServiceRegistryBuilder.destroy(registry);
		}
		return sessionFactory;
	}

	// 关闭连接
	public static void closeSessionFactory() {
		if (sessionFactory != null) {
			sessionFactory.close();
		}
	}

}
SessionManager.java

package com.ssh.util;

import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 线程安全箱
 * 
 * @author xingyang
 */
public class SessionManager {

	public static SessionFactory sessionFactory;

	@Autowired
	public void setSessionFactory(SessionFactory sessionFactory) {
		SessionManager.sessionFactory = sessionFactory;
	}

	private static ThreadLocal sessionHolder = new ThreadLocal() {
		protected Session initialValue() {

			Session session = sessionFactory.openSession();
			sessionHolder.set(session);
			return session;
		}
	};

	public Session getSession() {
		return sessionHolder.get();
	}

	/**
	 * close connection and put it back to connection pool
	 */
	public void closeSession() {
		Session session = sessionHolder.get();
		if (session != null) {
			session.flush();
			session.close();
			sessionHolder.remove();
		}
	}

}

FromEmail.java

package com.ssh.mail;

import javax.mail.Authenticator;
import javax.mail.PasswordAuthentication;

/**
 * 认证器
 * 
 * @author xingyang
 *
 */
public class FromEmail extends Authenticator {

	private String fromEmail;
	private String password;

	public FromEmail(String fromEmail, String password) {
		this.fromEmail = fromEmail;
		this.password = password;
	}

	@Override
	protected PasswordAuthentication getPasswordAuthentication() {
		return new PasswordAuthentication(fromEmail, password);
	}
}
MD5Util.java

package com.ssh.mail;

import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 激活码验证和处理
 * 
 * @author xingyang
 * 
 */
public class MD5Util {

	/**
	 * 将源字符串使用MD5加密为字节数组
	 * 
	 * @param source
	 * @return
	 */
	public static byte[] encode2bytes(String source) {
		byte[] result = null;
		try {
			MessageDigest md = MessageDigest.getInstance("MD5");
			md.reset();
			md.update(source.getBytes("UTF-8"));
			result = md.digest();
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}

		return result;
	}

	/**
	 * 将源字符串使用MD5加密为32位16进制数
	 * 
	 * @param source
	 * @return
	 */
	public static String encode2hex(String source) {
		byte[] data = encode2bytes(source);
		StringBuffer hexString = new StringBuffer();
		for (int i = 0; i < data.length; i++) {
			String hex = Integer.toHexString(0xff & data[i]);

			if (hex.length() == 1) {
				hexString.append('0');
			}

			hexString.append(hex);
		}

		return hexString.toString();
	}

	/**
	 * 验证字符串是否匹配
	 * 
	 * @param unknown
	 *            待验证的字符串
	 * @param okHex
	 *            使用MD5加密过的16进制字符串
	 * @return 匹配返回true,不匹配返回false
	 */
	public static boolean validate(String unknown, String okHex) {
		return okHex.equals(encode2hex(unknown));
	}

}
SendEmail.java
package com.ssh.mail;

import java.util.Date;
import java.util.Properties;

import javax.mail.Address;
import javax.mail.Authenticator;
import javax.mail.Message.RecipientType;
import javax.mail.MessagingException;
import javax.mail.Session;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeMessage;

import com.ssh.util.Contants;

/**
 * 发送邮件
 * 
 * @author xingyang
 *
 */
public class SendEmail {

	public static void send(String toEmail, String content) {

		Session session = SendEmail.getSession(); // 用本类方法中获取session

		try {
			Address from = new InternetAddress(Contants.FROM);
			InternetAddress[] to = { new InternetAddress(toEmail) };

			MimeMessage msg = new MimeMessage(session);
			msg.setFrom(from);

			msg.setSubject("账号激活邮件");
			msg.setSentDate(new Date());
			msg.setContent(content, "text/html;charset=utf-8");
			msg.setRecipients(RecipientType.TO, to);

			Transport.send(msg);
		} catch (MessagingException e) {
			e.printStackTrace();
		}

	}

	/**
	 *  获取Session
	 * 
	 * @return
	 */
	private static Session getSession() {

		Properties props = new Properties();
		props.put("mail.smtp.host", Contants.HOST);// 设置服务器地址
		props.put("mail.store.protocol", Contants.PROTOCOL);// 设置协议
		props.put("mail.smtp.port", Contants.PORT);// 设置端口
		props.setProperty("mail.smtp.auth", "true");
		props.setProperty("mail.user", Contants.MAIL_USER);

		Authenticator authenticator = new FromEmail(Contants.FROM, Contants.PWD);

		Session session = Session.getDefaultInstance(props, authenticator);
		session.setDebug(true);

		return session;
	}

}
ServiceException.java
package com.ssh.mail;

/**
 * 邮箱服务异常处理
 * 
 * @author xingyang
 *
 */
public class ServiceException extends Exception {
	private static final long serialVersionUID = -1708015121235851228L;

	public ServiceException(String message) {
		super(message);
	}
}


Users.java

package com.ssh.model;

import java.io.Serializable;

import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;

/**
 * 用户类
 * 
 * @author xingyang
 * 
 */
@Entity
@Table(name = "USERS")
public class Users implements Serializable {

	private static final long serialVersionUID = 1L;

	private Integer uid;
	private String uemail; // 邮箱
	private String uname; // 用户名
	private String upwd; // 密码
	private Integer isLogin; // 是否登录

	public static long getSerialversionuid() {
		return serialVersionUID;
	}

	public Users() {
		super();
	}

	// login
	public Users(String uemail, String upwd) {
		super();
		this.uemail = uemail;
		this.upwd = upwd;
	}

	// register
	public Users(Integer uid, String uemail, String uname, String upwd, Integer isLogin) {
		super();
		this.uid = uid;
		this.uemail = uemail;
		this.uname = uname;
		this.upwd = upwd;
		this.isLogin = isLogin;
	}

	@Id
	@GeneratedValue(strategy = GenerationType.IDENTITY)
	@Column(name = "UID")
	public Integer getUid() {
		return uid;
	}

	public void setUid(Integer uid) {
		this.uid = uid;
	}

	@Column(name = "UEMAIL")
	public String getUemail() {
		return uemail;
	}

	public void setUemail(String uemail) {
		this.uemail = uemail;
	}

	@Column(name = "UNAME")
	public String getUname() {
		return uname;
	}

	public void setUname(String uname) {
		this.uname = uname;
	}

	@Column(name = "UPWD")
	public String getUpwd() {
		return upwd;
	}

	public void setUpwd(String upwd) {
		this.upwd = upwd;
	}

	@Column(name = "is_login")
	public Integer getIsLogin() {
		return isLogin;
	}

	public void setIsLogin(Integer isLogin) {
		this.isLogin = isLogin;
	}

	@Override
	public String toString() {
		return "Users [uid=" + uid + ", uemail=" + uemail + ", uname=" + uname + ", upwd=" + upwd + ", isLogin="
				+ isLogin + "]";
	}

}
UserDao.java
package com.ssh.dao;

import com.ssh.model.Users;

/**
 * 用户信息Dao层
 * 
 * @author xingyang
 * 
 */
public interface UserDao {

	/**
	 * 用户登陆
	 * 
	 * @param user
	 * @return boolean
	 */
	public boolean login(Users user);

	/**
	 * 用户注册
	 * 
	 * @param user
	 * @return boolean
	 */
	public boolean register(Users user);

	/**
	 * 删除用户
	 * 
	 * @param uid
	 * @return boolean
	 */
	public boolean delUser(Integer uid);

	/**
	 * 修改用户信息
	 * 
	 * @param newUser
	 * @return boolean
	 */
	public boolean updateUsers(Users newUser);

	/**
	 * 根据用户id查询
	 * 
	 * @param uid
	 * @return Users
	 */
	public Users checkUsersById(Integer uid);

	/**
	 * 根据用户email查询
	 * 
	 * @param uemail
	 * @return Users
	 */
	public Users checkUsersByEmail(String uemail);

}
UserDaoImpl.java

package com.ssh.dao.impl;

import java.util.List;

import org.hibernate.Query;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;

import com.ssh.dao.UserDao;
import com.ssh.model.Users;
import com.ssh.util.SessionManager;

@Repository(value = "udao")
@Transactional
public class UserDaoImpl extends SessionManager implements UserDao {

	@Override
	public boolean login(Users user) {
		Users users = checkUsersByEmail(user.getUemail());
		String upwd = users.getUpwd();
		String inPwd = user.getUpwd();
		if (upwd.equals(inPwd)) {
			return true;
		}
		return false;
	}

	@Override
	public boolean register(Users user) {
		if (user.getUemail() != null && (!user.getUemail().equals(""))) {
			getSession().save(user);
		}
		closeSession();
		return true;
	}

	@Override
	public boolean delUser(Integer uid) {
		Users user = getSession().get(Users.class, uid);
		getSession().delete(user);
		closeSession();
		return getSession().get(Users.class, uid) == null;
	}

	@Override
	public boolean updateUsers(Users newUser) {
		Integer uid = newUser.getUid();
		String uname = newUser.getUname();
		String upwd = newUser.getUpwd();
		Users user = this.checkUsersById(uid);
		if (uname != null) {
			user.setUname(uname);
		}
		if (upwd != null) {
			user.setUpwd(upwd);
		}
		getSession().update(user);
		closeSession();
		return true;
	}

	@Override
	public Users checkUsersById(Integer uid) {
		String hql = "from Users as u where u.uid=:uid";
		Query query = getSession().createQuery(hql);
		query.setParameter("uid", uid);
		List list = query.list();
		return (list.size() != 0) ? list.get(0) : null;
	}

	@Override
	public Users checkUsersByEmail(String uemail) {
		String hql = "from Users as u where u.uemail=:uemail";
		Query query = getSession().createQuery(hql);
		query.setParameter("uemail", uemail);
		List list = query.list();
		return (list.size() != 0) ? list.get(0) : null;
	}

}

UserService.java

package com.ssh.service;

import com.ssh.model.Users;

/**
 * 用户Service层
 * 
 * @author xingyang
 * 
 */
public interface UserService {

	/**
	 * 注册
	 * 
	 * @param user
	 * @return boolean
	 */
	public boolean register(Users user);

	/**
	 * 登录
	 * 
	 * @param user
	 * @return boolean
	 */
	public boolean login(Users user);

	/**
	 * 删除用户
	 * 
	 * @param user
	 * @return boolean
	 */
	public boolean delUser(Users user);

	/**
	 * 更改个人资料
	 * 
	 * @param newUsers
	 * @return boolean
	 */
	public boolean updateUsers(Users newUsers);

	/**
	 * 根据用户id查询
	 * 
	 * @param uid
	 * @return Users
	 */
	public Users checkUsersById(Integer uid);

	/**
	 * 根据用户email查询
	 * 
	 * @param uemail
	 * @return Users
	 */
	public Users checkUsersByEmail(String uemail);

}

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

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

import com.ssh.dao.UserDao;
import com.ssh.model.Users;
import com.ssh.service.UserService;

/**
 * Service层-事务实现类,可对该类实现AOP事务管理
 * 
 */
@Service("uService")
public class UserServiceImpl implements UserService {

	@Autowired
	private UserDao udao;

	@Override
	public boolean register(Users user) {
		Users users = new Users(null, user.getUemail(), user.getUname(), user.getUpwd(), 0);
		return udao.register(users);
	}

	@Override
	public boolean login(Users user) {
		return udao.login(user);
	}

	@Override
	public boolean delUser(Users user) {
		return udao.delUser(user.getUid());
	}

	@Override
	public boolean updateUsers(Users newUser) {
		return udao.updateUsers(newUser);
	}

	@Override
	public Users checkUsersById(Integer uid) {
		return udao.checkUsersById(uid);
	}

	@Override
	public Users checkUsersByEmail(String uemail) {
		return udao.checkUsersByEmail(uemail);
	}

}
BaseController.java
package com.ssh.controller;

import javax.annotation.Resource;

import org.springframework.ui.Model;

import com.google.gson.Gson;
import com.ssh.mail.SendEmail;
import com.ssh.model.Users;
import com.ssh.service.UserService;

/**
 * 这是一个整合SpringMVC,Hibernate,Spring基于注解的框架 该类为所有controller提供共同的功能,如json数据的转换
 * 
 * @author xingyang
 */
public class BaseController {

	@Resource
	protected UserService uService;

	private Gson gson = new Gson();

	/**
	 * 将对象转换成json数据
	 * 
	 * @param object
	 * @return json
	 */
	public String toJson(Object object) {
		return gson.toJson(object);
	}

	/**
	 * 将对象转换成json数据(2)
	 * 
	 * @param object
	 * @return json
	 */
	public String toJsonp(Object object) {
		return "jsonp(" + gson.toJson(object) + ")";
	}

	// 获取用户信息
	protected void getUsers(Model model, Integer uid) {
		Users user = uService.checkUsersById(uid);
		model.addAttribute("user", user);
	}

	// 获取首页信息
	protected void getHome(Model model, Users user) {
		Users u = uService.checkUsersByEmail(user.getUemail());
		getUsers(model, u.getUid());
	}

	/**
	 * 忘记密码处理
	 */
	protected void processForgetPwd(String email, String validateCode) {

		// 邮件的内容
		StringBuffer sb = new StringBuffer("

"); sb.append(email); sb.append(", 您好!


"); sb.append("

邮箱账号:"); sb.append(email); sb.append(",临时密码:"); sb.append(validateCode); sb.append("


请尽快登陆系统进行密码修改!

系统网址:


"); sb.append(""); sb.append("http://localhost:8080/SpringMVC_Spring_Hibernate/index.jsp"); SendEmail.send(email, sb.toString()); System.out.println("发送邮件"); } }
UserController.java
package com.ssh.controller;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.ssh.mail.MD5Util;
import com.ssh.model.Users;

/**
 * 处理用户信息的控制器类
 * 
 * @author xingyang
 *
 */
@Controller
public class UserController extends BaseController {

	/**
	 * 登录
	 * 
	 * @param user
	 * @return String
	 * 
	 */
	@RequestMapping(value = "/login", produces = "text/html;charset=UTF-8")
	public String login(Model model, @ModelAttribute Users user) {
		Users users = uService.checkUsersByEmail(user.getUemail());
		getHome(model, users);
		return "/home.jsp";
	}

	/**
	 * 注册
	 * 
	 * @param user
	 * @return String
	 * 
	 */
	@RequestMapping(value = "/register", produces = "text/html;charset=UTF-8")
	public String register(Model model, @ModelAttribute Users user) {
		uService.register(user);
		getHome(model, user);
		return "/home.jsp";
	}

	/**
	 * 登录验证
	 * 
	 * @param user
	 * @return json
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/loginUser", produces = "text/html;charset=UTF-8")
	public Object loginUser(@RequestParam("uemail") String uemail, @RequestParam("upwd") String upwd) {
		Users user = new Users(uemail, upwd);
		return toJson(uService.login(user));
	}

	/**
	 * 注册验证
	 * 
	 * @param uemail
	 * @return json
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/registerEmail", produces = "text/html;charset=UTF-8")
	public Object registerEmail(@RequestParam("uemail") String uemail) {
		Users user = uService.checkUsersByEmail(uemail);
		return toJson(user == null);
	}

	/**
	 * 回到首页
	 * 
	 * @param uid
	 * @return String
	 * 
	 */
	@RequestMapping(value = "/home", produces = "text/html;charset=UTF-8")
	public String home(Model model, @RequestParam("uid") Integer uid) {
		Users user = uService.checkUsersById(uid);
		getHome(model, user);
		return "/home.jsp";
	}

	/**
	 * 删除用户
	 * 
	 * @param user
	 * @return json
	 * 
	 */
	@ResponseBody
	@RequestMapping(value = "/delUser", produces = "text/html;charset=UTF-8")
	public Object delUser(@ModelAttribute Users user) {
		return toJson(uService.delUser(user));
	}

	/**
	 * 修改用户个人资料
	 * 
	 * @param user
	 * @return String
	 */
	@RequestMapping(value = "/updateUsers", produces = "text/html;charset=UTF-8")
	public Object updateUsers(Model model, @ModelAttribute Users user) {
		uService.updateUsers(user);
		getHome(model, user);
		return "/home.jsp";
	}

	/**
	 * 忘记密码
	 * 
	 * @param user
	 * @return String
	 */
	@RequestMapping(value = "/forgetUpwd", produces = "text/html;charset=UTF-8")
	public String forgetUpwd(@ModelAttribute Users user) {
		Integer uid = user.getUid();
		String uemail = user.getUemail();
		String uname = user.getUname();
		String validateCode = MD5Util.encode2hex(uemail);// 临时密码
		processForgetPwd(uemail, validateCode);
		Users users = new Users(uid, uemail, uname, validateCode, 0);
		uService.updateUsers(users);
		return "/home.jsp";
	}

}

login.js(登录注册验证,自定义)

$(document).ready(function() {

	// 登陆提交后验证表单
	$("#loginForm").validate({
		rules : {
			uemail : {
				required : true,
				email : true
			},
			upwd : {
				required : true,
				remote : {
					type : "POST",
					url : "loginUser",
					data : {
						uemail : function() {
							return $("#loginUemail").val();
						},
						upwd : function() {
							return $("#loginUpwd").val();
						}
					}
				}
			}
		},

		messages : {
			uemail : {
				required : "请输入一个正确的邮箱",
				remote : "此邮箱已经被注册"
			},
			upwd : {
				required : "请输入密码",
				remote : "密码不正确"
			}
		}
	});

	// 注册提交后验证表单
	$("#registerForm").validate({
		rules : {
			uemail : {
				required : true,
				email : true,
				remote : { // 验证邮箱是否存在
					type : "POST",
					url : "registerEmail", // controller
					data : {
						uemail : function() {
							return $("#uemail").val();
						}
					}
				}
			},
			uname : {
				required : true,
				minlength : 2
			},
			upwd : {
				required : true,
				minlength : 6,
				maxlength : 20
			},
			confirmPwd : {
				required : true,
				rangelength : [ 6, 20 ],
				equalTo : "#upwd"
			},
		},

		messages : {
			uemail : {
				required : "请输入一个正确的邮箱",
				remote : "此邮箱已经被注册"
			},
			uname : "请输入用户名",
			upwd : {
				required : "请输入密码",
				minlength : "密码不得小于6位(6-20位)",
				maxlength : "密码不得大于20位(6-20位)"
			},
			confirmPwd : {
				required : "请输入密码",
				rangelength : "密码为6-20位",
				equalTo : "两次密码输入不一致"
			}
		}
	});
	
	$("#login").click(function(){

		var flag = document.getElementsByName("remember")[0].checked;  // 取到是否记住密码
		setCookie("flag", flag, 1); // 标记选择
		
		var uemail = $("#loginUemail").val();
		var upwd = $("#loginUpwd").val();
		
		if(flag && uemail!=null && uemail!="") {
			setCookie("uemail", uemail, 7);  // 保存七天
			setCookie("upwd", upwd, 7);
		} else {
			setCookie("uemail", "", 365);
			setCookie("upwd", "", 365);
		}
	});

	checkCookie();  // 设置cookie
	
});

// 检测 cookie 值的函数
function checkCookie(){
	var uemail = getCookie("uemail"); // 取到uname的cookie
	var upwd = getCookie("upwd");
	var flag = getCookie("flag"); // 取到记住密码标记

	document.getElementById("loginUemail").value = uemail; // 给email输入框赋值
	document.getElementById("loginUpwd").value = upwd;
	document.getElementsByName("remember")[0].checked = flag;
}

// 获取 cookie 值的函数
function getCookie(cname){
	var name = cname + "=";
	var ca = document.cookie.split(';');
	for(var i=0; i


你可能感兴趣的:(Java)