空框架
配置文件
CustomValidationMessages.properties
item.name.length.illigel=商品在名称在1到30个字符之间
createtime.is.null=时间不能为空
db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis?serverTimezone=Asia/Shanghai
jdbc.username=root
jdbc.password=root
log4j.properties
# Global logging configuration\uff0c\u5efa\u8bae\u5f00\u53d1\u73af\u5883\u4e2d\u8981\u7528debug
log4j.rootLogger=DEBUG, stdout
# Console output...
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n
applicationContext-dao.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<!-- 加载配置文件 -->
<context:property-placeholder location="classpath:db.properties" />
<!-- 数据库连接池 -->
<bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"
destroy-method="close">
<property name="driverClassName" value="${jdbc.driver}" />
<property name="url" value="${jdbc.url}" />
<property name="username" value="${jdbc.username}" />
<property name="password" value="${jdbc.password}" />
<property name="maxActive" value="30" />
<property name="maxIdle" value="5" />
</bean>
<!-- 让spring管理sqlsessionfactory 使用mybatis和spring整合包中的 -->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<!-- 数据库连接池 -->
<property name="dataSource" ref="dataSource" />
<!-- 加载mybatis的全局配置文件 -->
<property name="configLocation" value="classpath:mybatis/SqlMapConfig.xml" />
</bean>
<!-- mapper扫描器 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.neuedu.ssm.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory" />
</bean>
</beans>
applicationContext-service.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<bean id="itemsService" class="com.neuedu.ssm.service.ItemsServiceImpl"></bean>
</beans>
applicationContext-transation.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<!-- 事务管理器 -->
<bean id="transactionManager"
class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<!-- 数据源 -->
<property name="dataSource" ref="dataSource" />
</bean>
<!-- 通知 -->
<tx:advice id="txAdvice" transaction-manager="transactionManager">
<tx:attributes>
<!-- 传播行为 -->
<tx:method name="save*" propagation="REQUIRED" />
<tx:method name="insert*" propagation="REQUIRED" />
<tx:method name="delete*" propagation="REQUIRED" />
<tx:method name="update*" propagation="REQUIRED" />
<tx:method name="find*" propagation="SUPPORTS" read-only="true" />
<tx:method name="get*" propagation="SUPPORTS" read-only="true" />
</tx:attributes>
</tx:advice>
<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* com.neuedu.ssm.service.*.*(..))" />
</aop:config>
</beans>
Springmvc.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
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-4.2.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc-4.2.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-4.2.xsd
http://www.springframework.org/schema/aop
http://www.springframework.org/schema/aop/spring-aop-4.2.xsd
http://www.springframework.org/schema/tx
http://www.springframework.org/schema/tx/spring-tx-4.2.xsd ">
<!-- 扫描controller注解,多个包中间使用半角逗号分隔 -->
<context:component-scan base-package="com.neuedu.ssm.action" />
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<!--注解映射器 -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping" />
<!--注解适配器 -->
<bean
class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerAdapter">
<property name="webBindingInitializer" ref="customBinder"></property>
<property name="messageConverters">
<list>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter"></bean>
</list>
</property>
</bean>
<!-- 自定义webBinder -->
<bean id="customBinder"
class="org.springframework.web.bind.support.ConfigurableWebBindingInitializer">
<!-- <property name="propertyEditorRegistrars">
<list>
<ref bean="customPropertyEditor"/>
</list>
</property> -->
<property name="conversionService" ref="conversionService"></property>
<property name="validator" ref="validator"></property>
</bean>
<!-- 注册属性编辑器 -->
<!-- <bean id="customPropertyEditor" class="com.neuedu.ssm.action.propertyeditor.CustomPropertyEditor"></bean> -->
<!-- 注册转换器 -->
<bean id="conversionService"
class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<!-- 转换器 -->
<property name="converters">
<list>
<bean class="com.neuedu.ssm.action.converter.CustomDateConverter"/>
</list>
</property>
</bean>
<mvc:interceptors>
<!-- <mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.neuedu.ssm.interceptor.HandlerInterceptor1"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.neuedu.ssm.interceptor.HandlerInterceptor2"></bean>
</mvc:interceptor> -->
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.neuedu.ssm.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
<!-- ViewResolver -->
<bean
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="viewClass"
value="org.springframework.web.servlet.view.JstlView" />
<property name="prefix" value="/WEB-INF/jsp/" />
<property name="suffix" value=".jsp" />
</bean>
<!-- 文件上传解析器 -->
<bean id="multipartResolver"
class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
<!-- 设置上传文件的最大尺寸为5MB -->
<property name="maxUploadSize">
<value>5242880</value>
</property>
</bean>
<!-- 校验错误信息配置文件 -->
<bean id="validator"
class="org.springframework.validation.beanvalidation.LocalValidatorFactoryBean">
<property name="providerClass" value="org.hibernate.validator.HibernateValidator" />
<!-- 如果不指定则默认使用classpath下的ValidationMessages.properties -->
<property name="validationMessageSource" ref="messageSource" />
</bean>
<bean id="messageSource"
class="org.springframework.context.support.ReloadableResourceBundleMessageSource">
<property name="basenames">
<list>
<value>classpath:CustomValidationMessages</value>
</list>
</property>
<!-- <property name="fileEncodings" value="utf-8" /> -->
<property name="defaultEncoding" value="utf-8" />
<property name="cacheSeconds" value="120" />
</bean>
<!-- 自定义异常处理器 -->
<bean class="com.neuedu.ssm.exception.CustomExceptionResolver"></bean>
</beans>
SqlMapConfig.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-config.dtd">
<configuration>
<typeAliases>
<package name="com.neuedu.ssm.po"/>
</typeAliases>
<!--使用自动扫描器时,mapper.xml文件如果和mapper.java接口在一个目录则此处不用定义mappers -->
<!-- <mappers>
<package name="cn.itcast.ssm.mapper" />
</mappers> -->
</configuration>
包
src/com.neuedu.ssm
图一.png
src/com.neuedu.ssm/service
ItemsService.java
package com.neuedu.ssm.service;
import java.util.List;
import com.neuedu.ssm.po.Items;
import com.neuedu.ssm.po.QueryVo;
public interface ItemsService {
//商品查询列表
public List<Items> findItemsList(QueryVo queryVo)throws Exception;
public Items findItemById(int id) throws Exception;
public void saveItem(Items items)throws Exception;
}
ItemsServiceImpl.java
package com.neuedu.ssm.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import com.neuedu.ssm.mapper.ItemsMapper;
import com.neuedu.ssm.po.Items;
import com.neuedu.ssm.po.QueryVo;
public class ItemsServiceImpl implements ItemsService {
@Autowired
// @Qualifier("itemsMapper")
private ItemsMapper itemsMapper;
@Override
public List<Items> findItemsList(QueryVo queryVo) throws Exception {
return itemsMapper.findItemsList(queryVo);
}
@Override
public Items findItemById(int id) throws Exception {
return itemsMapper.findItemById(id);
}
@Override
public void saveItem(Items items) throws Exception {
itemsMapper.saveItem(items);
}
}
src/com.neuedu.ssm/po
Item.java
package com.neuedu.ssm.po;
import java.util.Date;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;
import com.neuedu.ssm.action.validator.ValidGroup1;
import com.neuedu.ssm.action.validator.ValidGroup2;
public class Items {
private Integer id;
@Size(min=1,max=30,message="{item.name.length.illigel}",groups={ValidGroup1.class})
private String name;
private Float price;
private String pic;
@NotNull(message="{createtime.is.null}",groups={ValidGroup2.class})
private Date createtime;
private String detail;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name == null ? null : name.trim();
}
public Float getPrice() {
return price;
}
public void setPrice(Float price) {
this.price = price;
}
public String getPic() {
return pic;
}
public void setPic(String pic) {
this.pic = pic == null ? null : pic.trim();
}
public Date getCreatetime() {
return createtime;
}
public void setCreatetime(Date createtime) {
this.createtime = createtime;
}
public String getDetail() {
return detail;
}
public void setDetail(String detail) {
this.detail = detail == null ? null : detail.trim();
}
@Override
public String toString() {
return "Items [id=" + id + ", name=" + name + ", price=" + price
+ ", pic=" + pic + ", createtime=" + createtime + ", detail="
+ detail + "]";
}
}
ItemsCustom.java
package com.neuedu.ssm.po;
public class ItemsCustom extends Items {
//
}
ItemsQueryVo.java
package com.neuedu.ssm.po;
import java.util.List;
public class ItemsQueryVo {
//
private Items items;
//
private ItemsCustom itemsCustom;
//
private List<ItemsCustom> itemsList;
//
//private UserCustom userCustom;
public Items getItems() {
return items;
}
public void setItems(Items items) {
this.items = items;
}
public ItemsCustom getItemsCustom() {
return itemsCustom;
}
public void setItemsCustom(ItemsCustom itemsCustom) {
this.itemsCustom = itemsCustom;
}
public List<ItemsCustom> getItemsList() {
return itemsList;
}
public void setItemsList(List<ItemsCustom> itemsList) {
this.itemsList = itemsList;
}
}
QueryVo.java
package com.neuedu.ssm.po;
import java.util.List;
public class QueryVo {
private Items items;
public Items getItems() {
return items;
}
public void setItems(Items items) {
this.items = items;
}
private User user;
//
private UserCustom userCustom;
//
private List<Integer> ids;
public User getUser() {
return user;
}
public void setUser(User user) {
this.user = user;
}
public UserCustom getUserCustom() {
return userCustom;
}
public void setUserCustom(UserCustom userCustom) {
this.userCustom = userCustom;
}
public List<Integer> getIds() {
return ids;
}
public void setIds(List<Integer> ids) {
this.ids = ids;
}
}
User.java
package com.neuedu.ssm.po;
import java.io.Serializable;
import java.util.Date;
public class User implements Serializable {
private int id;
private String username;// 用户姓名
private String sex;// 性别
private Date birthday;// 生日
private String address;// 地址
public int getId() {
return id;
}
public void setId(int id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getSex() {
return sex;
}
public void setSex(String sex) {
this.sex = sex;
}
public Date getBirthday() {
return birthday;
}
public void setBirthday(Date birthday) {
this.birthday = birthday;
}
public String getAddress() {
return address;
}
public void setAddress(String address) {
this.address = address;
}
@Override
public String toString() {
return "User [id=" + id + ", username=" + username + ", sex=" + sex
+ ", birthday=" + birthday + ", address=" + address + "]";
}
}
UserCustom.java
package com.neuedu.ssm.po;
import java.util.Date;
public class UserCustom extends User {
//这里添加扩展字段
private Date birthday_start;//起始日期
private Date birthday_end;//截止日期
}
src/com.neuedu.ssm/Mapper
ItemsMapper.xml
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
"http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.neuedu.ssm.mapper.ItemsMapper">
<!-- sql片段 -->
<!-- 商品查询条件 -->
<sql id="query_items_where">
<if test="items!=null">
<if test="items.name!=null and items.name!=''">
and items.name like '%${items.name}%'
</if>
</if>
</sql>
<!-- 查询商品信息 -->
<select id="findItemsList" parameterType="queryVo" resultType="items">
select * from items
<where>
<include refid="query_items_where" />
</where>
</select>
<select id="findItemById" parameterType="int" resultType="items">
select
* from items where id = #{id}
</select>
<update id="saveItem" parameterType="items">
update items
set name = #{name},
price = #{price},
createtime = #{createtime},
pic = #{pic},
detail = #{detail}
where id = #{id}
</update>
</mapper>
ItemsMapper.java
package com.neuedu.ssm.mapper;
import java.util.List;
import com.neuedu.ssm.po.Items;
import com.neuedu.ssm.po.QueryVo;
public interface ItemsMapper {
//商品列表
public List<Items> findItemsList(QueryVo queryVo) throws Exception;
//根据id查询商品信息
public Items findItemById(int id) throws Exception;
//修改商品信息
public void saveItem(Items items)throws Exception;
}
src/com.neuedu.ssm/Interceptor
HandlerInterceptor1.java
package com.neuedu.ssm.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
//定义拦截器
public class HandlerInterceptor1 implements HandlerInterceptor {
//进入handler方法之前执行
//用于身份认证,身份授权
//比如身份认证,如果认证不通过表示当前用户没有登录,需要此方法拦截,不再向下执行
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
System.out.println("HandlerInterceptor1...preHandle");
return true;
}
//进入handler方法之后,返回modelandview之前执行
//应用场景,将公共的模型数据(比如菜单导航、天气预报。。)在这里传到视图,也可以在这里统一指定视图
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("HandlerInterceptor1...postHandle");
}
//执行handler完成之后,执行此方法
//应用场景:统一异常处理,统一日志处理
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("HandlerInterceptor1...afterCompletion");
}
}
HandlerInterceptor2.java
package com.neuedu.ssm.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
//定义拦截器
public class HandlerInterceptor2 implements HandlerInterceptor {
//进入handler方法之前执行
//用于身份认证,身份授权
//比如身份认证,如果认证不通过表示当前用户没有登录,需要此方法拦截,不再向下执行
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
System.out.println("HandlerInterceptor2...preHandle");
return true;
}
//进入handler方法之后,返回modelandview之前执行
//应用场景,将公共的模型数据(比如菜单导航、天气预报。。)在这里传到视图,也可以在这里统一指定视图
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
System.out.println("HandlerInterceptor2...postHandle");
}
//执行handler完成之后,执行此方法
//应用场景:统一异常处理,统一日志处理
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("HandlerInterceptor2...afterCompletion");
}
}
LoginInterceptor.java
package com.neuedu.ssm.interceptor;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;
public class LoginInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse reponse, Object arg2) throws Exception {
//如果登录页面,则放行
if(request.getRequestURI().indexOf("login.action") >= 0){
return true;
}
//如果用户已经登陆,则放行
HttpSession session = request.getSession();
if(session.getAttribute("username") != null){
return true;
}
request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request, reponse);
return false;
}
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
// TODO Auto-generated method stub
}
@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
// TODO Auto-generated method stub
}
}
src/com.neuedu.ssm/Exception
CustomException.java
package com.neuedu.ssm.exception;
//自定义异常类
public class CustomException extends Exception {
public CustomException(String message){
super(message);
this.message = message;
}
private String message;
public String getMessage() {
return message;
}
public void setMessage(String message) {
this.message = message;
}
}
CustomExceptionResolver.java
package com.neuedu.ssm.exception;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
//自定义异常处理器
public class CustomExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2,
Exception ex) {
//打印异常信息
ex.printStackTrace();
CustomException customException = null;
//如果抛出的是系统自定义异常则直接转换
if(ex instanceof CustomException){
customException = (CustomException)ex;
}else{
//如果抛出的不是系统自定义异常,则重新构造一个未知异常
customException = new CustomException("未知错误,请与系统管理员联系!");
}
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message", customException.getMessage());
modelAndView.setViewName("error");
return modelAndView;
}
}
src/com.neuedu.ssm/converter
CustomDateConverter.java
package com.neuedu.ssm.converter;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
public class CustomDateConverter implements Converter<String, Date> {
public Date convert(String source) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return simpleDateFormat.parse(source);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
src/com.neuedu.ssm/action
../converter/CustomDateConverter.java
package com.neuedu.ssm.action.converter;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.core.convert.converter.Converter;
public class CustomDateConverter implements Converter<String, Date> {
@Override
public Date convert(String source) {
try {
SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
return simpleDateFormat.parse(source);
} catch (Exception e) {
e.printStackTrace();
}
return null;
}
}
../propertyeditor/CustomPropertyEditor.java
package com.neuedu.ssm.action.propertyeditor;
import java.text.SimpleDateFormat;
import java.util.Date;
import org.springframework.beans.PropertyEditorRegistrar;
import org.springframework.beans.PropertyEditorRegistry;
import org.springframework.beans.propertyeditors.CustomDateEditor;
public class CustomPropertyEditor implements PropertyEditorRegistrar {
@Override
public void registerCustomEditors(PropertyEditorRegistry binder) {
binder.registerCustomEditor(Date.class,
new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
}
}
../validator
- ValidGroup1.java
package com.neuedu.ssm.action.validator;
public interface ValidGroup1 {
}
- ValidGroup2.java
package com.neuedu.ssm.action.validator;
public interface ValidGroup2 {
}
../converter
- ItemsController.java
package com.neuedu.ssm.action;
import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.validation.BindingResult;
import org.springframework.validation.ObjectError;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.WebDataBinder;
import org.springframework.web.bind.annotation.InitBinder;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
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.bind.annotation.ResponseBody;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;
import com.neuedu.ssm.action.validator.ValidGroup1;
import com.neuedu.ssm.action.validator.ValidGroup2;
import com.neuedu.ssm.exception.CustomException;
import com.neuedu.ssm.po.Items;
import com.neuedu.ssm.po.ItemsQueryVo;
import com.neuedu.ssm.po.QueryVo;
import com.neuedu.ssm.service.ItemsService;
@Controller
@RequestMapping("/item")
public class ItemsController {
@Autowired
private ItemsService itemsService;
//商品分类
@ModelAttribute("itemtypes")
public Map<String, String> getItemTypes(){
Map<String, String> itemTypes = new HashMap<String,String>();
itemTypes.put("101", "数码");
itemTypes.put("102", "母婴");
return itemTypes;
}
@RequestMapping("/queryItem.action")
public ModelAndView queryItem() throws Exception {
// 商品列表
List<Items> itemsList = itemsService.findItemsList(null);
// 创建modelAndView准备填充数据、设置视图
ModelAndView modelAndView = new ModelAndView();
// 填充数据
modelAndView.addObject("itemsList", itemsList);
// 视图
modelAndView.setViewName("itemsList");
return modelAndView;
}
@RequestMapping("/queryItemsList.action")
public ModelAndView queryItemsList() throws Exception {
// 商品列表
List<Items> itemsList = itemsService.findItemsList(null);
// 创建modelAndView准备填充数据、设置视图
ModelAndView modelAndView = new ModelAndView();
// 填充数据
modelAndView.addObject("itemsList", itemsList);
// 视图
modelAndView.setViewName("editItemsQuery");
return modelAndView;
}
@RequestMapping("/itemsView/{id}")
public @ResponseBody Items itemsView(@PathVariable("id") Integer item_id) throws Exception{
Items items = itemsService.findItemById(item_id);
return items;
}
@RequestMapping("/queryItemsListTest.action")
public String queryItemsListTest(HttpServletRequest request,Model model) throws Exception {
//1.填充数据
request.setAttribute("data", 123);
//2
model.addAttribute("data", 123);
return "itemList";
}
//跳转到修改页面
// @RequestMapping("/editItem.action")
// public ModelAndView editItem(HttpServletRequest request,HttpServletResponse response) throws Exception {
//
// String id = request.getParameter("id");
//
// Items items =itemsService.findItemById(Integer.parseInt(id));
//
// // 创建modelAndView准备填充数据、设置视图
// ModelAndView modelAndView = new ModelAndView();
// modelAndView.addObject("items", items);
// modelAndView.setViewName("editItems");
//
// return modelAndView;
// }
@RequestMapping("/editItem.action")
public ModelAndView editItem(@RequestParam(value="id",required=false,defaultValue="123") int id_num) throws Exception {
Items items =itemsService.findItemById(id_num);
// int a = 1/0;
/*if(items==null){
throw new CustomException("商品信息不存在!");
}*/
// 创建modelAndView准备填充数据、设置视图
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("items", items);
modelAndView.setViewName("editItems");
return modelAndView;
}
//点击“提交”按钮,真正修改
// @RequestMapping(value="/editItemsSubmit.action",method={RequestMethod.GET,RequestMethod.POST})
// public String editItemsSubmit(HttpServletRequest request,Items items,Model model) throws Exception {
//
// itemsService.saveItem(items);
//
// return "success";
// }
@RequestMapping(value="/editItemsSubmit.action")
public String editItemsSubmit(@Validated(value={ValidGroup2.class,ValidGroup1.class}) Items items,BindingResult bindingResult, MultipartFile items_pic,Model model) throws Exception {
if(bindingResult.hasErrors()){
List<ObjectError> errors = bindingResult.getAllErrors();
for(ObjectError objectError:errors){
System.out.println(objectError.getCode());
System.out.println(objectError.getDefaultMessage());
}
model.addAttribute("allErrors", errors);
return "editItems";
}
//获取原始图片名称
String originalFilename = items_pic.getOriginalFilename();
if(items_pic!=null && originalFilename!=null && originalFilename.length()>0){
//存储图片的物理路径
String pic_path = "E:\\develop\\upload\\temp\\";
//新的图片名称
String newFileName = UUID.randomUUID() + originalFilename.substring(originalFilename.lastIndexOf("."));
//创建新图片
File newFile = new File(pic_path+newFileName);
//将内存中的数据写入磁盘
items_pic.transferTo(newFile);
//将新图片名称写到items中
items.setPic(newFileName);
}
// itemsService.saveItem(items);
return "success";
}
// @RequestMapping(value="/editItemsSubmit.action")
// public String editItemsSubmit(QueryVo queryVo) throws Exception {
//
// return "success";
// }
@RequestMapping("/deleteItems.action")
public String deleteItems(String[] items_id)
throws Exception {
return "success";
}
@RequestMapping(value="/editItemsAllSubmit.action")
public String editItemsAllSubmit(ItemsQueryVo itemsQueryVo) throws Exception {
return "success";
}
// 批量修改商品提交
// 通过ItemsQueryVo接收批量提交的商品信息,将商品信息存储到itemsQueryVo中itemsList属性中。
// @RequestMapping("/editItemsAllSubmit.action")
// public String editItemsAllSubmit(ItemsQueryVo itemsQueryVo)
// throws Exception {
//
// return "success";
// }
/**
* 注册属性编辑器(字符串转换为日期)
*/
// @InitBinder
// public void initBinder(WebDataBinder binder) throws Exception {
// binder.registerCustomEditor(Date.class,
// new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"), true));
// }
}
- JsonController.java
package com.neuedu.ssm.action;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.neuedu.ssm.po.Items;
@Controller
public class JsonController {
@RequestMapping("/requestJson.action")
public @ResponseBody Items requestJson(@RequestBody Items items){
return items;
}
@RequestMapping("/requestKeyValue.action")
public @ResponseBody Items requestKeyValue(Items items){
return items;
}
}
- LoginController.java
package com.neuedu.ssm.action;
import javax.servlet.http.HttpSession;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
@Controller
public class LoginController {
//登录
@RequestMapping("/login.action")
public String login(HttpSession session,String username,String password) throws Exception{
//调用service中的方法,进行用户名密码校验
//.....
//在session中保存用户信息
session.setAttribute("username", username);
return "redirect:/item/queryItem.action";
}
//退出
@RequestMapping("/logout.action")
public String logout(HttpSession session) throws Exception{
//清除session
session.invalidate();
return "redirect:/item/queryItem.action";
}
}
网友评论