Eclipse
Maven插件
JDK1.8
MySQL5.7
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.lyxgroupId>
<artifactId>1011houseartifactId>
<version>1.0.0version>
<packaging>warpackaging>
<dependencies>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
<scope>testscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>3.1.0version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>javax.servlet.jsp-apiartifactId>
<version>2.3.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-coreartifactId>
<version>5.2.10.Finalversion>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.40version>
dependency>
<dependency>
<groupId>org.apache.commonsgroupId>
<artifactId>commons-dbcp2artifactId>
<version>2.1.1version>
dependency>
<dependency>
<groupId>commons-codecgroupId>
<artifactId>commons-codecartifactId>
<version>1.10version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.39version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>4.3.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-ormartifactId>
<version>4.3.10.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>4.3.10.RELEASEversion>
<scope>testscope>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjrtartifactId>
<version>1.8.10version>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.10version>
dependency>
<dependency>
<groupId>org.hibernategroupId>
<artifactId>hibernate-validatorartifactId>
<version>5.4.1.Finalversion>
dependency>
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.9.0version>
dependency>
dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.pluginsgroupId>
<artifactId>maven-war-pluginartifactId>
<version>3.2.0version>
<configuration>
<failOnMissingWebXml>falsefailOnMissingWebXml>
configuration>
plugin>
plugins>
build>
project>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:aop="http://www.springframework.org/schema/aop"
xmlns:tx="http://www.springframework.org/schema/tx"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx.xsd">
<context:component-scan base-package="com.lyx.house">
<context:exclude-filter type="annotation"
expression="org.springframework.stereotype.Controller"/>
<context:exclude-filter type="annotation"
expression="org.springframework.web.bind.annotation.ControllerAdvice"/>
context:component-scan>
<context:annotation-config/>
<bean id="dataSource" class="org.apache.commons.dbcp2.BasicDataSource" destroy-method="close">
<property name="driverClassName" value="com.mysql.jdbc.Driver">property>
<property name="url" value="jdbc:mysql://localhost:3306/house">property>
<property name="username" value="root">property>
<property name="password" value="951112">property>
<property name="initialSize" value="10">property>
<property name="maxTotal" value="100">property>
<property name="maxWaitMillis" value="5000">property>
bean>
<bean id="sessionFactory" class="org.springframework.orm.hibernate5.LocalSessionFactoryBean">
<property name="dataSource" ref="dataSource">property>
<property name="packagesToScan" value="com.lyx.house.domain">property>
<property name="hibernateProperties">
<value>
hibernate.dialect=org.hibernate.dialect.MySQL57Dialect
hibernate.show_sql=true
hibernate.format_sql=true
value>
property>
bean>
<bean id="transactionManager" class="org.springframework.orm.hibernate5.HibernateTransactionManager">
<property name="sessionFactory" ref="sessionFactory">property>
bean>
<tx:annotation-driven transaction-manager="transactionManager"/>
beans>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
id="WebApp_ID" version="3.1">
<servlet>
<servlet-name>frontControllerservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<load-on-startup>1load-on-startup>
<multipart-config />
servlet>
<servlet-mapping>
<servlet-name>frontControllerservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:spring.xmlparam-value>
context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
<error-page>
<error-code>404error-code>
<location>/404.htmllocation>
error-page>
<display-name>1011housedisplay-name>
<welcome-file-list>
<welcome-file>index.htmlwelcome-file>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
web-app>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/toPublish" />
<mvc:mapping path="/doPublish" />
<bean class="com.lyx.house.interceptor.LoginInterceptor" />
mvc:interceptor>
mvc:interceptors>
<context:component-scan base-package="com.lyx.house.controller" />
<mvc:annotation-driven>
<mvc:message-converters>
<bean class="org.springframework.http.converter.BufferedImageHttpMessageConverter"/>
<bean class="org.springframework.http.converter.StringHttpMessageConverter"/>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"/>
mvc:message-converters>
mvc:annotation-driven>
<mvc:default-servlet-handler />
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/">property>
<property name="suffix" value=".jsp">property>
<property name="order" value="10">property>
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView">property>
bean>
<bean class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="contentType" value="text/html;charset=utf-8"/>
<property name="cache" value="true" />
<property name="prefix" value="" />
<property name="suffix" value=".ftl" />
<property name="order" value="5"/>
bean>
<bean id="multipartResolver"
class="org.springframework.web.multipart.support.StandardServletMultipartResolver">
bean>
beans>
package com.lyx.house.domain;
import java.io.Serializable;
import javax.persistence.Column; //用官方JPA,不要耦合Hibernate
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.Table;
@Entity // 表示实体类(一个要持久化的类)
@Table(name = "tb_user") // 对应的表名称
public class User implements Serializable {
private static final long serialVersionUID = 1L;
@Id // 标志字段(即数据库中一张表的主键字段)
@Column(name = "userid") // 对应的字段名称
@GeneratedValue(strategy = GenerationType.IDENTITY) // 生成策越(自动增长)
private Integer id;
private String username;
private String password;
private String realname;
private String tel;
@Column(name = "isadmin")
private Boolean admin; // 是否是管理员 false 不是,true 是
public User() {
super();
}
public User(String username, String password, String realname, String tel, Boolean admin) {
super();
this.username = username;
this.password = password;
this.realname = realname;
this.tel = tel;
this.admin = admin;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
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 String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
public String getTel() {
return tel;
}
public void setTel(String tel) {
this.tel = tel;
}
public Boolean getAdmin() {
return admin;
}
public void setAdmin(Boolean admin) {
this.admin = admin;
}
}
package com.lyx.house.domain;
import java.io.Serializable;
import java.util.Date;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.Table;
@Entity
@Table(name = "tb_login_log")
public class LoginLog implements Serializable {
private static final long serialVersionUID = 1L;
@Id
@Column(name = "loginid")
@GeneratedValue(strategy = GenerationType.IDENTITY)
private Integer id;
@ManyToOne // 表示多对一关系,外键列(对应User实体的主键-即User实体的id字段)
@JoinColumn(name = "user_id") //外键列在数据库中的名字"user_id"
private User user;
@Column(name = "ipaddr")
private String ipAddress;// 登陆的ip地址
private Date logDate;
public LoginLog() {
super();
}
public LoginLog(User user, String ipAddress, Date logDate) {
super();
this.user = user;
this.ipAddress = ipAddress;
this.logDate = logDate;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public String getIpAddress() {
return ipAddress;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public Date getLogDate() {
return logDate;
}
public void setLogDate(Date logDate) {
this.logDate = logDate;
}
}
package com.lyx.house.persistence;
import java.io.Serializable;
import java.util.List;
/**
* 基本的增删改查功能
* @author Administrator
* @param 实体类型
* @param 标识字段(主键类型)
*/
public interface BaseDao<E,K extends Serializable>{
/**
* 保存一个实体
* @param entity 要保存的实体
* @return 主键
*/
K save(E entity);
void delete(E entity);
/**
* 删除 根据主键
* @param id 主键
* @return 是否删除(真-删除)
*/
boolean deleteById(K id);
/**
* 更新一个实体
* @param entity 要更新的实体
* @return 更新后的实体
*/
E update(E entity);
/**
* 查找一个实体,根据主键
* @param id 主键
* @return 找到的实体
*/
E findById(K id);
/**
* 查找所有
* @return 装着所有实体的集合
*/
List findAll();
}
package com.lyx.house.persistence.impl;
import java.io.Serializable;
import java.lang.reflect.ParameterizedType;
import java.util.Collections;
import java.util.List;
import org.hibernate.SessionFactory;
import org.springframework.beans.factory.annotation.Autowired;
import com.lyx.house.persistence.BaseDao;
public abstract class BaseDaoAdapter<E,K extends Serializable> implements BaseDao<E, K>{
@Autowired //Hibernate的自动注入
protected SessionFactory sessionFactroy;
private Class entityType;
private String entityName;
@SuppressWarnings("unchecked")
protected BaseDaoAdapter() {
ParameterizedType pt=(ParameterizedType) this.getClass().getGenericSuperclass();
entityType=(Class) pt.getActualTypeArguments()[0];
entityName=entityType.getSimpleName();
}
@SuppressWarnings("unchecked")
@Override
public K save(E entity) {
return (K) sessionFactroy.getCurrentSession().save(entity);
}
@Override
public void delete(E entity) {
sessionFactroy.getCurrentSession().delete(entity);
}
@Override
public boolean deleteById(K id) {
return sessionFactroy.getCurrentSession().
createQuery("delete from "+entityName+" as o where o.id=:id").
setParameter("id", id).
executeUpdate()==1;
}
@SuppressWarnings("unchecked")
@Override
public E update(E entity) {
return (E) sessionFactroy.getCurrentSession().merge(entity);
}
@Override
public E findById(K id) {
return sessionFactroy.getCurrentSession().get(entityType, id);
}
@Override
public List findAll() {
List entities = sessionFactroy.getCurrentSession().
createQuery("from "+entityName,entityType).getResultList();
return entities.size()>0?entities:Collections.emptyList();
}
}
package com.lyx.house.persistence;
import com.lyx.house.domain.User;
public interface UserDao extends BaseDao<User, Integer>{
/**
* 登陆 根据用户名(还可以检查用户名是否唯一)
* @param username
* @return 查到的实体
*/
User findByUsername(String username);
}
package com.lyx.house.persistence.impl;
import java.util.List;
import org.springframework.stereotype.Repository;
import com.lyx.house.domain.User;
import com.lyx.house.persistence.UserDao;
@Repository //纳入SpringIoC容器
public class UserDaoImpl extends BaseDaoAdapter<User, Integer> implements UserDao{
//其中的sessionFactory继承于抽象类(被自动注入了的)
@Override
public User findByUsername(String username) {
List userList= sessionFactroy.getCurrentSession()
.createQuery("from User as u where u.username=:username",User.class).
setParameter("username", username).
getResultList();
return userList.size()==1?userList.get(0):null;
}
}
package com.lyx.house.dto;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Pattern;
import javax.validation.constraints.Size;
//用户登陆时,接收数据的数据传输实体
public class UserLoginDto {
@Pattern(regexp = "\\w{6,20}") // 数据提交到后台的验证(底层依赖SpringMVC实现)
private String username;
@Size(min = 6) // 数据提交到后台的验证
private String password;
@NotNull // 数据提交到后台的验证
private String code;
private String ipAddress;
private Integer id;
private String realname;
public UserLoginDto() {
}
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 String getCode() {
return code;
}
public void setCode(String code) {
this.code = code;
}
public void setIpAddress(String ipAddress) {
this.ipAddress = ipAddress;
}
public String getIpAddress() {
return ipAddress;
}
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getRealname() {
return realname;
}
public void setRealname(String realname) {
this.realname = realname;
}
}
package com.lyx.house.service;
import com.lyx.house.dto.UserLoginDto;
import com.lyx.house.dto.UserRegisterDto;
public interface UserService {
/**
* 用户登录
* @param userLoginDto
* @return
*/
boolean login(UserLoginDto userLoginDto);
/**
* 用户注册
* @param userRegisterDto
* @return
*/
boolean register(UserRegisterDto userRegisterDto);
/**
* 检查用户名是否存在
* @param username 用户名
* @return 存在返回false,不存在返回true(可以注册)
*/
boolean checkUsername(String username);
}
package com.lyx.house.service.impl;
import java.util.Date;
import org.apache.commons.codec.digest.DigestUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import com.lyx.house.domain.LoginLog;
import com.lyx.house.domain.User;
import com.lyx.house.dto.UserLoginDto;
import com.lyx.house.dto.UserRegisterDto;
import com.lyx.house.persistence.LoginLogDao;
import com.lyx.house.persistence.UserDao;
import com.lyx.house.service.UserService;
@Service //纳入SpringIoC容器
@Transactional //Spring的事务切面(事务脚本模式-用户的一个操作对应一个方法-一个方法即一个事务)
public class UserServiceImpl implements UserService{
@Autowired //Spring自动注入
private UserDao userDao;
@Autowired
private LoginLogDao loginLogDao;
@Override
public boolean login(UserLoginDto userLoginDto) {
boolean flag=false;
User temp=userDao.findByUsername(userLoginDto.getUsername());
if (temp!=null) {
String md5=DigestUtils.md5Hex(userLoginDto.getPassword());
if (temp.getPassword().equals(md5)) {
LoginLog loginLog=new LoginLog(temp, userLoginDto.getIpAddress(), new Date());
if (loginLogDao.save(loginLog)!=null) {
userLoginDto.setId(temp.getId());
userLoginDto.setRealname(temp.getRealname());
flag=true;
}
}
}
return flag;
}
@Override
public boolean register(UserRegisterDto userRegisterDto) {
User temp=userDao.findByUsername(userRegisterDto.getUsername());
if (temp==null) {
String md5=DigestUtils.md5Hex(userRegisterDto.getPassword());
User user=new User(userRegisterDto.getUsername(),
md5,
userRegisterDto.getRealname(),
userRegisterDto.getTel(),
false);
return userDao.save(user)!=null;
}
return false;
}
@Override
public boolean checkUsername(String username) {
return userDao.findByUsername(username)==null;
}
}
package com.lyx.house.controller;
import java.awt.image.BufferedImage;
import java.io.IOException;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.lyx.house.util.CommonUtil;
@Controller //交给SpringMVC管理
// @RequestMapping("/") //类路径映射-多级路径
public class ResourceDispatcherController {
private static final int CODE_LENGTH = 4;
/*
* 设置首页
*/
//Get请求
@GetMapping({ "/toHome", "/" }) // 多个映射指向同一个资源("/"默认首页)
public String toIndex() {
return "index";
}
/*
* 登陆页面
*/
// @RequestMapping(value="/toLogin",method=RequestMethod.GET)
@GetMapping("toLogin")
public ModelAndView toLogin() {
ModelAndView mav = new ModelAndView();
mav.setViewName("login");
mav.addObject("hint", "欢迎您的登陆!!!");
return mav;
}
/*
* 注册页面
*/
@GetMapping("/toRegister")
public String toRegister(Model model) {
model.addAttribute("hint", "欢迎您的注册!!!");
return "register";
}
/*
* 发布房源的页面
*/
@GetMapping("/toPublish")
public String toPublish() {
return "pub";
}
@GetMapping(value="/getCodeImage",produces="image/png") //produces配置MIME类型(资源的媒体类型)
@ResponseBody
public BufferedImage getCode(HttpSession session) throws IOException {
String code = CommonUtil.generateCode(CODE_LENGTH);
session.setAttribute("code", code);
return CommonUtil.generateCodeImage(code, 80, 30);
// response.setContentType("image/png");
// BufferedImage bi = CommonUtil.generateCodeImage(code, 80, 30);
// ImageIO.write(bi, "PNG", response.getOutputStream());
}
}
package com.lyx.house.controller;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.validation.Valid;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.Errors;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.lyx.house.dto.CheckResult;
import com.lyx.house.dto.UserLoginDto;
import com.lyx.house.dto.UserRegisterDto;
import com.lyx.house.service.UserService;
@Controller
public class UserController {
@Autowired //自动注入
private UserService userService;
/*
* 用户登录
*/
@PostMapping("/doLogin")
public String doLogin(@Valid UserLoginDto userLoginDto,Errors errors,HttpServletRequest request) {
String viewName="login";
if (request.getSession().getAttribute("code").toString().equalsIgnoreCase(userLoginDto.getCode())) {
request.getSession().removeAttribute("code");
if (!errors.hasErrors()) {
userLoginDto.setIpAddress(request.getRemoteAddr());
if (userService.login(userLoginDto)) {
request.getSession().setAttribute("userId", userLoginDto.getId());
request.getSession().setAttribute("userRealname", userLoginDto.getRealname());
viewName="redirect:toHome";
} else {
request.setAttribute("hint", "用户名或密码错误,请重新登陆!!!");
}
}else {
request.setAttribute("hint", "MMP,能不能好好填写登陆信息!!!");
}
} else {
request.setAttribute("hint", "验证码错误!!!");
request.setAttribute("codeHint", "X");
}
return viewName;
}
/*
* 用户注册
*/
@PostMapping("/doRegister")
public String doRegister(@Valid UserRegisterDto userRegisterDto,Errors errors,HttpServletRequest request) {
String viewName="register";
if (request.getSession().getAttribute("code").toString().equalsIgnoreCase(userRegisterDto.getCode())) {
request.getSession().removeAttribute("code");
if (!errors.hasErrors()) {
if (userService.register(userRegisterDto)) {
viewName="redirect:toLogin";
} else {
request.setAttribute("hint", "注册失败!!!请重新注册!!!");
}
}else if(userRegisterDto.getPassword().equals(userRegisterDto.getRepassword())){
request.setAttribute("hint", "MMP,能不能好好填写注册信息");
}else{
request.setAttribute("hint", "MMP,能不能填好好写注册信息");
}
} else {
request.setAttribute("hint", "验证码错误!!!");
request.setAttribute("codeHint", "X");
}
return viewName;
}
/*
* 检查用户名的唯一性(Ajax操作)
*/
@GetMapping("doCheck")
@ResponseBody
public CheckResult doCheckUsername(String username) {
boolean valid=userService.checkUsername(username);
return new CheckResult(username,valid, valid?"可以注册":"已被占用", valid?"ok.png":"no.png");
}
/*
* 注销登录
*/
@GetMapping("/doLogout")
public String doLogout(HttpSession session) {
session.removeAttribute("userId");
session.removeAttribute("userRealname");
return "redirect:toHome";
}
}
package com.lyx.house.controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
@ControllerAdvice //配置服务器控制层抛出异常或错误时的处理(跳转到指定页面-用户最小惊讶原则-不要抱异常或错误抛到页面给用户看)
public class MyExceptionAdvice {
@ExceptionHandler({Exception.class}) //发生哪些异常
public String toException(Model model) {
return "error/hint";
}
}
package com.lyx.house.util;
import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;
import javax.imageio.ImageIO;
public final class CommonUtil {
private static final String ALL_CHAR = "0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ";
private CommonUtil() {
throw new AssertionError();
}
/**
* 生成[min, max)范围的随机整数
* @param min 下限值(闭区间)
* @param max 上限值(开区间)
* @return 随机整数
*/
public static int getRandomInt(int min, int max) {
return (int) (Math.random() * (max - min) + min);
}
/**
* 生成随机码
* @param length 随机码的长度
* @return
*/
public static String generateCode(int length) {
String code = ALL_CHAR;
StringBuilder targetCode = new StringBuilder();
for (int i = 0; i < length; i++) {
int index = getRandomInt(0, 62);
targetCode.append(code.charAt(index));
}
return targetCode.toString();
}
/**
* 根据随机码生成模糊图片
* @param code 随机码
* @param width
* @param height
* @return
*/
public static BufferedImage generateCodeImage(String code, int width, int height) {
BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_BGR);
Graphics g = bi.getGraphics();
g.setColor(new Color(getRandomInt(0, 256), getRandomInt(0, 256), getRandomInt(0, 256)));
g.fillRect(0, 0, width, height);
int size = (width - 10) / code.length();
g.setFont(new Font("Arial", Font.BOLD, size));
for (int i = 0; i < code.length(); i++) {
g.setColor(new Color(getRandomInt(0, 256), getRandomInt(0, 256), getRandomInt(0, 256)));
String currentChar = code.substring(i, i + 1);
g.drawString(currentChar, 5 + size * i, height / 2);
}
// 干扰线
for (int i = 0; i < 12; i++) {
g.setColor(new Color(getRandomInt(0, 256), getRandomInt(0, 256), getRandomInt(0, 256)));
g.drawLine(getRandomInt(0, 60), getRandomInt(0, 30), getRandomInt(0, 60), getRandomInt(0, 30));
}
g.dispose();// 图片生成
return bi;
}
/**
* 字符串日期转换成Date对象
* @param 指定的日期格式
* @param 字符串日期
* @return Date对象
*/
public static Date stringToDate(String pattern, String str) {
SimpleDateFormat myFormat = new SimpleDateFormat(pattern);
try {
return myFormat.parse(str);
} catch (ParseException e) {
throw new RuntimeException("字符串转日期格式出错!!!", e);
}
}
/**
* 日期转换成指定的字符串形式
* @param 日期格式
* @param 具体日期
* @return 日期的字符串形式
*/
public static String dateToString(String pattern, Date date) {
SimpleDateFormat myFormat = new SimpleDateFormat(pattern);
return myFormat.format(date);
}
/**
* 取得文件后缀名
* @param 文件名
* @return 文件后缀名
*/
public static String getFilenameSuffix(String fileName) {
int index = fileName.lastIndexOf(".");
return index > 0 && index < fileName.length() - 1 ? fileName.substring(index) : "";
}
/**
* 随机生成文件名(全局唯一)
* @return 随机文件名
*/
public static String getRadomFilename() {
return UUID.randomUUID().toString();
}
/**
* 上传图片并压缩(全部转换成PNG格式)
*
* @param inputStream 图片二进制流
* @param filePath 文件要存储的路径
* @param width 宽度(高度自适应)
* @throws IOException
*/
public static void imgUploadCompress(InputStream inputStream, String filePath, int width) throws IOException {
File file = new File(filePath);
BufferedImage oldImage = ImageIO.read(inputStream);
int oldWidth = oldImage.getWidth();
double ratio = (double) width / (double) oldWidth;
int newHeight = (int) (oldImage.getHeight() * ratio);
// System.out.println("比例="+ratio+"--高="+newHeight);
BufferedImage newImage = new BufferedImage(width, newHeight, BufferedImage.TYPE_INT_RGB);
newImage.getGraphics().drawImage(oldImage, 0, 0, width, newHeight, null);
ImageIO.write(newImage, "PNG", file);
}
}