dao层以及对应的mapper文件:
(1)查询所有区域
public interface AreaMapper {
List<Area> listArea();
}
<?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.unistrong.dao.AreaMapper">
<select id="listArea" resultType="com.unistrong.bean.Area">
select * from tb_area order by priority desc;
</select>
</mapper>
(2)查询所有店铺种类
public interface ShopCategoryMapper {
List<ShopCategory> listShopCategory(@Param("shopCategoryCondition") ShopCategory shopCategoryCondition);
}
<?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.unistrong.dao.ShopCategoryMapper">
<!-- 查询所有的类别 -->
<select id="listShopCategory"
resultType="com.unistrong.bean.ShopCategory"
parameterType="com.unistrong.bean.ShopCategory">
select * from tb_shop_category
<where>
<!-- parent_id不为空的,查询的是以及一级类别下的二级类别 -->级
<if test="shopCategoryCondition!=null">
and parent_id is not null
</if>
<!-- 查询指定的parent_id,也就是二级类别 下的所有店铺-->
<if test="shopCategoryCondition.parent!=null">
and parent_id=#{shopCategoryCondition.parent.shopCategoryId}
</if>
</where>
order by priority desc
</select>
</mapper>
(3)注册店铺
public interface ShopMapper {
int insertShop(Shop shop);
int updateShop(Shop shop);
}
<?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.unistrong.dao.ShopMapper">
<insert id="insertShop" parameterType="com.unistrong.bean.Shop"
useGeneratedKeys="true" keyColumn="shop_id" keyProperty="shopId">
insert into
tb_shop
values(#{shopId},#{owner.userId},#{area.areaId},#{shopCategory.shopCategoryId},#{shopName},
#{shopDesc},#{shopAddr},#{phone},#{shopImg},#{priority},#{createTime},#{lastEditTime},#{enableStatus},#{advice});
<!-- INSERT into
tb_shop (owner_id,area_id,shop_category_id,shop_name,shop_desc,shop_addr,phone,shop_img,
priority,create_time,last_edit_time,enable_status,advice) values(#{owner.userId},#{area.areaId},#{shopCategory.shopCategoryId},
#{shopName},#{shopDesc},
#{shopAddr},#{phone},#{shopImg},#{priority},#{createTime},#{lastEditTime},#{enableStatus},#{advice}); -->
</insert>
<update id="updateShop" parameterType="com.unistrong.bean.Shop">
update tb_shop
<set>
<if test="shopName!=null">shop_name=#{shopName},</if>
<if test="owner!=null">owner_id=#{owner.userId},</if>
<if test="area!=null">area_id=#{area.areaId},</if>
<if test="shopCategory!=null">shop_category_id=#{shopCategory.shopCategoryId},</if>
<if test="shopDesc!=null">shop_desc=#{shopDesc},</if>
<if test="shopAddr!=null">shop_addr=#{shopAddr},</if>
<if test="phone!=null">phone=#{phone},</if>
<if test="shopImg!=null">shop_img=#{shopImg},</if>
<if test="priority!=null">priority=#{priority},</if>
<if test="createTime!=null">create_time=#{createTime},</if>
<if test="lastEditTime!=null">last_edit_time=#{lastEditTime},</if>
<if test="enableStatus!=null">enable_status=#{enableStatus},</if>
<if test="advice!=null">advice=#{advice}</if>
</set>
where shop_id=#{shopId};
</update>
</mapper>
dto层:
public class ShopExecution {
// 结果状态
private int state;
// 状态标识,解释结果状态
private String stateInfo;
// 店铺数量
private int count;
// 操作店铺的shop(增删改店铺的时候使用)
private Shop shop;
public String getStateInfo() {
return stateInfo;
}
public void setStateInfo(String stateInfo) {
this.stateInfo = stateInfo;
}
// 查询店铺列表的时候使用
private List<Shop> shopList;
public ShopExecution() {
super();
}
// 店铺操作失败的构造器,也就是有问题的时候,使用返回信息的
public ShopExecution(ShopSateEnum sateEnum) {
this.state = sateEnum.getState();
this.stateInfo = sateEnum.getStateInfo();
}
// 店铺操作成功的构造器,返回单个对象
public ShopExecution(ShopSateEnum sateEnum, Shop shop) {
this.state = sateEnum.getState();
this.stateInfo = sateEnum.getStateInfo();
this.shop = shop;
}
// 店铺操作成功的的构造器,查询多个对象时
public ShopExecution(ShopSateEnum sateEnum, List<Shop> shopList) {
this.state = sateEnum.getState();
this.stateInfo = sateEnum.getStateInfo();
this.shopList = shopList;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
public Shop getShop() {
return shop;
}
public void setShop(Shop shop) {
this.shop = shop;
}
public List<Shop> getShopList() {
return shopList;
}
public void setShopList(List<Shop> shopList) {
this.shopList = shopList;
}
}
enum枚举:
public enum ShopSateEnum {
CHECK(0, "审核中"), OFFLINE(-1, "非法店铺"), SUCCESS(1, "操作成功"), PASS(2, "通过认证"), INNER_ERROR(-1001, "内部错误"),
NULL_SHOPID(-1002,"shopId为空"),NULL_SHOP(-1003,"shop信息为空");
// 结果状态
private int state;
// 状态标识,解释结果状态
private String stateInfo;
private ShopSateEnum(int state, String stateInfo) {
this.state = state;
this.stateInfo = stateInfo;
}
// 根据传入的state返回相应的enum值
public static ShopSateEnum stateOf(int state) {
// values()方法,是上面所有有的说明(审核中、非法店铺、操作成功。。。。))
for (ShopSateEnum sateEnum : values()) {
// 值所对应的状态,是通过getState()获得的t
if (sateEnum.getState() == state) {
return sateEnum;
}
}
return null;
}
public int getState() {
return state;
}
public void setState(int state) {
this.state = state;
}
public String getStateInfo() {
return stateInfo;
}
public void setStateInfo(String stateInfo) {
this.stateInfo = stateInfo;
}
}
exception异常:
public class ShopOperationException extends Exception {
/**
*
*/
private static final long serialVersionUID = 1L;
public ShopOperationException(String message) {
super(message);
}
}
util工具类:
public class CodeUtil {
public static boolean checkVerifyCode(HttpServletRequest request) {
String verifyCodeExpected = (String) request.getSession().getAttribute(
com.google.code.kaptcha.Constants.KAPTCHA_SESSION_KEY);
String verifyCodeActual = HttpServletRequestUtil.getString(request,
"verifyCodeActual");
if (verifyCodeActual == null
|| !verifyCodeActual.equalsIgnoreCase(verifyCodeExpected)) {
return false;
}
return true;
}
}
public class HttpServletRequestUtil {
public static int getInt(HttpServletRequest request, String name) {
try {
return Integer.decode(request.getParameter(name));
} catch (Exception e) {
return -1;
}
}
public static long getLong(HttpServletRequest request, String name) {
try {
return Long.valueOf(request.getParameter(name));
} catch (Exception e) {
return -1;
}
}
public static Double getDouble(HttpServletRequest request, String name) {
try {
return Double.valueOf(request.getParameter(name));
} catch (Exception e) {
return -1d;
}
}
public static Boolean getBoolean(HttpServletRequest request, String name) {
try {
return Boolean.valueOf(request.getParameter(name));
} catch (Exception e) {
return false;
}
}
public static String getString(HttpServletRequest request, String name) {
try {
String result = request.getParameter(name);
if (result != null) {
result = result.trim();
}
if ("".equals(result))
result = null;
return result;
} catch (Exception e) {
return null;
}
}
}
public class ImageUtil {
private static String basePath = Thread.currentThread().getContextClassLoader().getResource("").getPath();
private static final SimpleDateFormat sf = new SimpleDateFormat("yyMMddHHmmsss");
private static final Random r = new Random();
public static String generateThumbnail(InputStream thumbailnputStream,String fileName,String targetAddr) {
String realFileName = getRandomFileName();
String extension = getFileExtension(fileName);
makeDirPath(targetAddr);
String relativePath = targetAddr + realFileName + extension;
File dest = new File(PathUtil.getImageBasePath() + relativePath);
try {
Thumbnails.of(thumbailnputStream).size(200, 200)
.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "/water.gif")), 0.25f)
.outputQuality(0.8).toFile(dest);
} catch (IOException e) {
e.printStackTrace();
}
return relativePath;
}
// 创建目标路径所涉及的路径
private static void makeDirPath(String targetAddr) {
String parentBasePath = PathUtil.getImageBasePath();
File f=new File(parentBasePath);
if(!f.exists()) {
f.mkdirs();
}
}
private static String getFileExtension(String fileName) {
// // 以分隔符来获取扩展名
// String orginFileName = thumbail.getName();
return fileName.substring(fileName.lastIndexOf("."));
}
public static String getRandomFileName() {
// 获取随即五位数
int ranNum = r.nextInt(89999) + 10000;
String currentTime = sf.format(new Date());
return currentTime + ranNum;
}
public static void main(String[] args) {
try {
Thumbnails.of(new File("C:\\Users\\edz\\Desktop\\images\\item\\2017061320315746624.jpg")).size(200, 200)
.watermark(Positions.BOTTOM_RIGHT, ImageIO.read(new File(basePath + "\\water.gif")), 0.25f)
.outputQuality(0.8).toFile("C:\\Users\\edz\\Desktop\\images\\item\\new.jpg");
} catch (IOException e) {
e.printStackTrace();
}
}
}
public class PathUtil {
// 获取文件分隔符
private static String separator = System.getProperty("file.separator");
public static String getImageBasePath() {
// 获取操作系统名字
String os = System.getProperty("os.name");
String basePath = "";
if (os.toLowerCase().startsWith("win")) {
basePath = "C:/Users/edz/Desktop/images/";
} else {
basePath = "/home";
}
basePath = basePath.replace("/", separator);
return basePath;
}
public static String getShopImagePath(long shopId) {
String imagePath = "upload/item/shop/" + shopId + "/";
imagePath.replace("/", separator);
return imagePath;
}
}
service层:
public interface AreaService {
List<Area> listAreas();
}
public interface ShopCategoryService {
List<ShopCategory> listShopCategory(ShopCategory shopCategoryCondition);
}
public interface ShopService {
ShopExecution insertShop(Shop shop, InputStream shopImgInputStream, String fileName);
}
serviceImp实现类:
@Service
public class AreaServiceImpl implements AreaService {
@Autowired
private AreaMapper areaMapper;
@Override
public List<Area> listAreas() {
return areaMapper.listArea();
}
}
@Service
public class ShopCategoryServiceImpl implements ShopCategoryService {
@Autowired
private ShopCategoryMapper shopCategoryMapper;
@Override
public List<ShopCategory> listShopCategory(ShopCategory shopCategoryCondition){
List<ShopCategory> list=shopCategoryMapper.listShopCategory(shopCategoryCondition);
return list;
}
}
@Service
public class ShopServiceImpl implements ShopService {
@Autowired
private ShopMapper shopMapper;
@Override
public ShopExecution insertShop(Shop shop, InputStream shopImgInputStream,String fileName) {
if (shop == null) {
return new ShopExecution(ShopSateEnum.NULL_SHOP);
}
try {
// 给店铺赋初始值
shop.setEnableStatus(0);
shop.setCreateTime(new Date());
shop.setLastEditTime(new Date());
// 添加店铺的方法
int effect = shopMapper.insertShop(shop);
if (effect < 1) {
throw new ShopOperationException("店铺创建失败");
} else {
if (shopImgInputStream != null) {
// 存储图片
try {
addShop(shop, shopImgInputStream,fileName);
} catch (Exception e) {
throw new ShopOperationException("店铺添加图片失败");
}
effect = shopMapper.updateShop(shop);
if (effect < 1) {
throw new ShopOperationException("店铺更新失败");
}
}
}
} catch (Exception e) {
try {
throw new ShopOperationException("shop adderr:" + e.getMessage());
} catch (ShopOperationException e1) {
e1.printStackTrace();
}
}
return new ShopExecution(ShopSateEnum.CHECK, shop);
}
private void addShop(Shop shop, InputStream shopImgInputStream,String fileName) {
// 获取图片目录的相对值路径
String dest = PathUtil.getShopImagePath(shop.getShopId());
String shopImgAddr = ImageUtil.generateThumbnail(shopImgInputStream,fileName,dest);
shop.setShopImg(shopImgAddr);
}
}
controller层:
@Controller
@RequestMapping(value = "/shopadmin", method = RequestMethod.GET)
public class ShopadminController {
@RequestMapping(value = "/shopoperation")
public String ShopOperation() {
return "/shop/shopoperation";
}
}
@Controller
@RequestMapping("/shopadmin")
public class ShopManagement {
@Autowired
private ShopService shopService;
@Autowired
private ShopCategoryService shopCategoryService;
@Autowired
private AreaService areaService;
@RequestMapping(value = "/getshopinitinfo", method = RequestMethod.GET)
@ResponseBody
public Map<String, Object> getShopInitInfo() {
Map<String, Object> modelMap = new HashMap<>();
List<ShopCategory> shopCategoryList = new ArrayList<>();
List<Area> areaList = new ArrayList<>();
try {
shopCategoryList = shopCategoryService.listShopCategory(new ShopCategory());
areaList = areaService.listAreas();
modelMap.put("shopCategoryList", shopCategoryList);
modelMap.put("areaList", areaList);
modelMap.put("success", true);
} catch (Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
}
return modelMap;
}
@RequestMapping(value = "/registershop", method = RequestMethod.POST)
@ResponseBody
public Map<String, Object> registerShop(HttpServletRequest request) {
// 接受前端传回来的参数,接受并转化店铺信息以及图片信息
Map<String, Object> modelMap = new HashMap<>();
if (!CodeUtil.checkVerifyCode(request)) {
modelMap.put("success", false);
modelMap.put("errMsg", "输入了错误的验证码");
return modelMap;
}
String shopStr = HttpServletRequestUtil.getString(request, "shopStr");
ObjectMapper mapper = new ObjectMapper();
Shop shop = null;
try {
shop = mapper.readValue(shopStr, Shop.class);
} catch (Exception e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
return modelMap;
}
CommonsMultipartFile shopImg = null;
CommonsMultipartResolver commonsMultipartResolver = new CommonsMultipartResolver(
request.getSession().getServletContext());
if (commonsMultipartResolver.isMultipart(request)) {
MultipartHttpServletRequest multipartHttpServletRequest = (MultipartHttpServletRequest) request;
shopImg = (CommonsMultipartFile) multipartHttpServletRequest.getFile("shopImg");
} else {
modelMap.put("success", false);
modelMap.put("errMsg", "上传图片不能为空");
return modelMap;
}
// 注册店铺功能实现
if (shop != null && shopImg != null) {
PersonInfo owner = new PersonInfo();
// 模拟的数据,数据库中要有,因为是是外键,所以需要注意。
owner.setUserId(8L);
shop.setOwner(owner);
/*
* File shopImgFile = new File(PathUtil.getImageBasePath() +
* ImageUtil.getRandomFileName()); try { shopImgFile.createNewFile(); } catch
* (IOException e) { modelMap.put("success", false); modelMap.put("errMsg",
* e.getMessage()); return modelMap; }
*/
/*
* try { inputStreamToFile(shopImg.getInputStream(), shopImgFile); } catch
* (IOException e) {
*
* modelMap.put("success", false); modelMap.put("errMsg", e.getMessage());
* return modelMap; }
*/
ShopExecution se = null;
try {
se = shopService.insertShop(shop, shopImg.getInputStream(), shopImg.getOriginalFilename());
if (se.getState() == ShopSateEnum.CHECK.getState()) {
modelMap.put("success", true);
} else {
modelMap.put("success", false);
modelMap.put("errMsg", se.getStateInfo());
}
} catch (IOException e) {
modelMap.put("success", false);
modelMap.put("errMsg", e.getMessage());
return modelMap;
}
} else {
modelMap.put("success", false);
modelMap.put("errMsg", "请输入店铺信息");
return modelMap;
}
return modelMap;
}
/*
* public static void inputStreamToFile(InputStream ins, File file) {
* FileOutputStream os = null; try { os = new FileOutputStream(file); int
* byteRead = 0; byte[] buffer = new byte[1024]; while ((byteRead =
* ins.read(buffer)) != -1) { os.write(buffer, 0, byteRead); } } catch
* (Exception e) { throw new RuntimeException("调用inputStreamToFile方法产生异常" +
* e.getMessage()); } finally { try { if (os != null) { os.close(); } if (ins !=
* null) { ins.close(); } } catch (Exception e) { throw new
* RuntimeException("调用inputStreamToFile方法关闭异常" + e.getMessage()); } } }
*/
}
@Controller
@RequestMapping("/superadmin")
public class AreaController {
@Autowired
private AreaService areaService;
@RequestMapping(value = "/listArea", method = RequestMethod.GET)
@ResponseBody
// @ResponseBody这个注解是解析成json的字符串
// 返回结果装到Map中,前端解析Map集合
private Map<String, Object> listArea() {
Map<String, Object> modelMap = new HashMap<>();
List<Area> list = new ArrayList<>();
try {
list = areaService.listAreas();
// 将结果集放到map中
modelMap.put("rows", list);
// 结果集的个数放到map中
modelMap.put("total", list.size());
} catch (Exception e) {
e.printStackTrace();
// 将错误信息放到map中
modelMap.put("sucess", false);
// 将错误信息返回给前端
modelMap.put("errMsg", e.toString());
}
return modelMap;
}
}
pom.xml文件:工程所有需要引入的依赖:
<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.0</modelVersion>
<groupId>com.unistrong</groupId>
<artifactId>o2o</artifactId>
<version>0.0.1-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<spring.version>4.3.7.RELEASE</spring.version>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
<dependency>
<groupId>ch.qos.logback</groupId>
<artifactId>logback-classic</artifactId>
<version>1.2.3</version>
</dependency>
<!-- Spring -->
<!-- 1)Spring核心工具类,spring其它组件都要使用到这个包里的类,是其他组件的基本核心 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-core</artifactId>
<version>${spring.version}</version>
</dependency>
<!--2)这个jar文件是所有应用都要用到的,包含访问配置文件、创建和管理bean以及控制与反转-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-beans</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 3)这个jar文件为spring核心提供了大量扩展。可以找到使用springApplicationContext特性时
所需的全部类,instrumentation组件以及校验Validation方面相关的类 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 4)这个jar文件包含对jdbc数据访问进行封装所有的类 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>${spring.version}</version>
</dependency>
<!--5)为jdbc、Hibernate、JDo、JPA等提供一致的声明式和编程的事务管理 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 6)Spring web包含web应用开发时,用到Spring框架时所需的核心类,包括自动载入webApplicationContent -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-web</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 7)包含SpringMvc框架相关的所有的类-->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${spring.version}</version>
</dependency>
<!-- 8)Spring test对JUNIT等测试框架的简单封装 -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>${spring.version}</version>
<scope>test</scope>
</dependency>
<!-- Servlet web -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
</dependency>
<!--jsp标签库 -->
<dependency>
<groupId>taglibs</groupId>
<artifactId>standard</artifactId>
<version>1.1.2</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- json解析-->
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.7</version>
</dependency>
<!-- Map工具类对标准java Collection的扩展spring-core.jar需commons-collections.jar -->
<dependency>
<groupId>commons-collections</groupId>
<artifactId>commons-collections</artifactId>
<version>3.2</version>
</dependency>
<!-- 数据库-->
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.37</version>
<scope>runtime</scope>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<!-- DAO: MyBatis的配置 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.2</version>
</dependency>
<!-- mybatis与spring整合的jar包 -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<!-- 图片处理 -->
<groupId>net.coobird</groupId>
<artifactId>thumbnailator</artifactId>
<version>0.4.8</version>
</dependency>
<!-- 验证码处理 -->
<!-- https://mvnrepository.com/artifact/com.github.penggle/kaptcha -->
<dependency>
<groupId>com.github.penggle</groupId>
<artifactId>kaptcha</artifactId>
<version>2.3.2</version>
</dependency>
<dependency>
<groupId>commons-fileupload</groupId>
<artifactId>commons-fileupload</artifactId>
<version>1.3.2</version>
</dependency>
</dependencies>
<build>
<finalName>o2o</finalName>
<plugins>
<plugin>
<!-- maven-compiler-plugin插件制定JDK版本-->
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.6.1</version>
<!-- 配置JDK -->
<configuration>
<!-- 源代码使用的开发版本 -->
<source>1.8</source>
<!-- 需要生成的目标class文件的编译版本 -->
<target>1.8</target>
<!--JDK的编码 -->
<encoding>UTF8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
web.xml:工程的配置
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee
http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
version="3.1" metadata-complete="true">
<display-name>customer</display-name>
<welcome-file-list>
<welcome-file>index.html</welcome-file>
<welcome-file>index.htm</welcome-file>
<welcome-file>index.jsp</welcome-file>
<welcome-file>default.html</welcome-file>
<welcome-file>default.htm</welcome-file>
<welcome-file>default.jsp</welcome-file>
</welcome-file-list>
<!-- 如果是用mvn命令生成的xml,需要修改servlet版本为3.1 -->
<servlet>
<!-- 生成图片的Servlet -->
<servlet-name>Kaptcha</servlet-name>
<servlet-class>com.google.code.kaptcha.servlet.KaptchaServlet</servlet-class>
<!-- 是否有边框 -->
<init-param>
<param-name>kaptcha.border</param-name>
<param-value>no</param-value>
</init-param>
<!-- 字体颜色 -->
<init-param>
<param-name>kaptcha.textproducer.font.color</param-name>
<param-value>red</param-value>
</init-param>
<!-- 图片宽度 -->
<init-param>
<param-name>kaptcha.image.width</param-name>
<param-value>135</param-value>
</init-param>
<!-- 使用哪些字符生成验证码 -->
<init-param>
<param-name>kaptcha.textproducer.char.string</param-name>
<param-value>ACDEFHKPRSTWX345679</param-value>
</init-param>
<!-- 图片高度 -->
<init-param>
<param-name>kaptcha.image.height</param-name>
<param-value>50</param-value>
</init-param>
<!-- 字体大小 -->
<init-param>
<param-name>kaptcha.textproducer.font.size</param-name>
<param-value>43</param-value>
</init-param>
<!-- 干扰线的颜色 -->
<init-param>
<param-name>kaptcha.noise.color</param-name>
<param-value>black</param-value>
</init-param>
<!-- 字符个数 -->
<init-param>
<param-name>kaptcha.textproducer.char.length</param-name>
<param-value>4</param-value>
</init-param>
<!-- 使用哪些字体 -->
<init-param>
<param-name>kaptcha.textproducer.font.names</param-name>
<param-value>Arial</param-value>
</init-param>
</servlet>
<!-- 映射的url -->
<servlet-mapping>
<servlet-name>Kaptcha</servlet-name>
<url-pattern>/Kaptcha</url-pattern>
</servlet-mapping>
<!-- 配置spring -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/spring-*.xml</param-value>
</context-param>
<resource-ref>
<description>DB Connection</description>
<res-ref-name>zjut_echarts</res-ref-name>
<res-type>javax.sql.DataSource</res-type>
<res-auth>Container</res-auth>
</resource-ref>
<!-- 配置监听器加载spring -->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!-- 配置过滤器,解决post的乱码问题 -->
<filter>
<filter-name>encoding</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encoding</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- 配置DispatcherServlet -->
<servlet>
<servlet-name>DispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 配置springMVC需要加载的配置文件 spring-dao.xml,spring-service.xml,spring-web.xml
Mybatis - > spring -> springmvc -->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:/spring/springmvc.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>DispatcherServlet</servlet-name>
<!-- 默认匹配所有的请求 -->
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
前端文件
html文件:shopoperation.html
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>SUI Mobile Demo</title>
<meta name="description"
content="MSUI: Build mobile apps with simple HTML, CSS, and JS components.">
<meta name="author" content="阿里巴巴国际UED前端">
<meta name="viewport" content="initial-scale=1, maximum-scale=1">
<link rel="shortcut icon" href="/favicon.ico">
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black">
<meta name="format-detection" content="telephone=no">
<!-- Google Web Fonts -->
<link rel="stylesheet"
href="//g.alicdn.com/msui/sm/0.6.2/css/sm.min.css">
<link rel="stylesheet"
href="//g.alicdn.com/msui/sm/0.6.2/css/sm-extend.min.css">
<link rel="apple-touch-icon-precomposed"
href="/assets/img/apple-touch-icon-114x114.png">
<script>
//ga
</script>
<script>
var _hmt = _hmt || [];
(function() {
var hm = document.createElement("script");
hm.src = "//hm.baidu.com/hm.js?ba76f8230db5f616edc89ce066670710";
var s = document.getElementsByTagName("script")[0];
s.parentNode.insertBefore(hm, s);
})();
</script>
</head>
<body>
<div class="page-group">
<div id="page-label-input" class="page">
<header class="bar bar-nav">
<a class="button button-link button-nav pull-left back"
href="/demos/form"> <span class="icon icon-left"></span> 返回
</a>
<h1 class="title">商店信息</h1>
</header>
<div class="content">
<div class="list-block">
<ul>
<!-- Text inputs -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">商铺名称</div>
<div class="item-input">
<input type="text" id="shop_name" placeholder="商铺名称">
</div>
</div>
</div>
</li>
<!-- 商铺分类 下拉列表 -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">商铺分类</div>
<div class="item-input">
<select id="shop_category">
</select>
</div>
</div>
</div>
</li>
<!-- 区域分类 下拉列表 -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">所属区域</div>
<div class="item-input">
<select id="area">
</select>
</div>
</div>
</div>
</li>
<!-- 详细地址 text -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">详细地址</div>
<div class="item-input">
<input type="text" id="shop_addr" placeholder="详细地址">
</div>
</div>
</div>
</li>
<!-- 联系电话 text -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">联系电话</div>
<div class="item-input">
<input type="text" id="shop_phone" placeholder="联系电话">
</div>
</div>
</div>
</li>
<!-- 缩略图 上传控件 -->
<li>
<div class="item-content">
<div class="item-inner">
<div class="item-title label">缩略图</div>
<div class="item-input">
<input type="file" id="shop_img">
</div>
</div>
</div>
</li>
<!-- 店铺简介 textarea -->
<li class="align-top">
<div class="item-content">
<div class="item-inner">
<div class="item-title label">店铺简介</div>
<div class="item-input">
<textarea id="shop_desc" placeholder="店铺简介"></textarea>
</div>
</div>
</div>
</li>
<!-- 验证码 kaptcha -->
<li>
<div class="item-content">
<div class="item-media">
<i class="icon icon-form-name"></i>
</div>
<div class="item-inner">
<div class="item-title label">验证码</div>
<input type="text" id="j_kaptcha" placeholder="验证码">
<div class="item-input">
<img id="kaptcha_img" alt="点击更换" title="点击更换"
onclick="changeVerifyCode(this)" src="../Kaptcha">
</div>
</div>
</div>
</li>
</ul>
</div>
<div class="content-block">
<div class="row">
<div class="col-50">
<a href="#" class="button button-big button-fill button-danger">返回</a>
</div>
<div class="col-50">
<a href="#" class="button button-big button-fill" id="submit">提交</a>
</div>
</div>
</div>
</div>
</div>
</div>
<script type='text/javascript'
src='//g.alicdn.com/sj/lib/zepto/zepto.min.js' charset='utf-8'></script>
<script type='text/javascript'
src='//g.alicdn.com/msui/sm/0.6.2/js/sm.min.js' charset='utf-8'></script>
<script type='text/javascript'
src='//g.alicdn.com/msui/sm/0.6.2/js/sm-extend.min.js' charset='utf-8'></script>
<script type='text/javascript'
src='../resources/js/shop/shopoperation.js' charset='utf-8'></script>
<script type='text/javascript'
src='../resources/js/common/commonutil.js' charset='utf-8'></script>
</body>
</html>
js文件:shopoperation.js
/**
*
*/
$(function(){
// 传递id说明是修改店铺信息,不传递是注册店铺信息
var shopId=getQueryString('shopId');
var isEdit=shopId ? true : false;
var initUrl='/o2o/shopadmin/getshopinitinfo';
var registerShopUrl='/o2o/shopadmin/registershop';
var shopInfoUrl="/o2o/shopadmin/getshopbyid?shopId="+shopId;
var editShopUrl='/o2o/shopdamin/modifyshop';
// 通过isEdit来判断是修改店铺信息还是注册店铺,来调用不同的方法
if(!isEdit){
getShopInitInfo();
} else{
getShopInfo(shopId);
}
function getShopInitInfo(){
$.getJSON(initUrl,function(data){
if(data.success){
var tempHtml='';
var tempAreaHtml='';
/*
* 以map的形式遍历集合
*/
data.shopCategoryList.map(function(item,index){
tempHtml+='<option data-id="'+item.shopCategoryId+'">'+
item.shopCategoryName+'<option>';
});
data.areaList.map(function(item,index){
tempAreaHtml+='<option data-id="'+item.areaId+'">'+
item.areaName+'<option>';
});
$('#shop_category').html(tempHtml);
$('#area').html(tempAreaHtml);
}
});
};
// 通过传入的shopId,查询shop的信息,然后获取到js页面中,为后面修改shop信息做准备
function getShopInfo(shopId){
$.getJSON(shopInfoUrl, function(data){
if(data.success){
var shop = data.shop;
$('#shop_name').val(shop.shopName);
$('#shop_addr').val(shop.shopAddr);
$('#shop_phone').val(shop.phone);
$('#shop_desc').val(shop.shopDesc);
// 将shopCategory的信息以option的形式保存,然后赋值到下面的shop_category,并且它的attr是disabled的(不可选择的)
// area是以下拉列表的形式保存,area的attr默认选择的是现在的店铺区域信息
var shopCategory = '<option data-id="'
+ shop.shopCategory.shopCategoryId + '"selected>'
+ shop.shopCategory.shopCategoryName + '</option>';
var tempAreaHtml = '';
data.areaList.map(function(item, index){
tempAreaHtml += '<option data-id=""' + item.areaId + '"">'
+ item.areaName + '</option>';
});
$('#shop_category').html(shopCategory);
$('#shop_category').attr('disabled', 'disabled');
$('#area').html(tempAreaHtml);
$("#area option[data-id='" + shop.area.areaId + "']").attr("selected", "selected");
}
});
}
// 提交按钮,将店铺信息提交到后台进行处理 url根据isEdit来分情况选择
$('#submit').click(function(){
var shop = {};
if(isEdit){
shop.shopId = shopId;
}
shop.shopName = $('#shop_name').val();
shop.shopAddr = $('#shop_addr').val();
shop.phone = $('#shop_phone').val();
shop.shopDesc = $('#shop_desc').val();
/* 使用的下拉菜单来进行选择,获取值的方法 */
shop.shopCategory = {
shopCategoryId : $('#shop_category').find('option').not(function(){
return !this.selected;
}).data('id')
};
shop.area = {
areaId : $('#area').find('option').not(function(){
return !this.selected;
}).data('id')
};
/* 获取的是上传图片的输入流 */
var shopImg = $('#shop_img')[0].files[0];
// 在ajax中传递的参数
var formData = new FormData();
// 参数的内容,分别是上面的shop和shop图片
formData.append('shopImg', shopImg);
formData.append('shopStr', JSON.stringify(shop));
var verifyCodeActual = $('#j_kaptcha').val();
if(!verifyCodeActual){
$.toast('请输入验证码!');
return;
}
formData.append('verifyCodeActual', verifyCodeActual);
/* 使用ajax提交到后台 */
$.ajax({
url:(isEdit?editShopUrl:registerShopUrl),
type:'POST',
data:formData,
contentType:false,
processData:false,
cache:false,
success:function(data){
if(data.success){
$.toast('提交成功!');
} else{
$.toast('提交失败!' + data.errMsg);
}
/* 更换验证码 */
$('#kaptcha_img').click();
}
});
});
});
commonutil.js
/**
*
*/
function changeVerifyCode(img){
img.src = "../Kaptcha?" + Math.floor(Math.random() * 100);
}
/**
* 获取前端url中的name的id值
* @param name
* @returns {*}
*/
function getQueryString(name){
var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)");
var r = window.location.search.substr(1).match(reg);
if(r != null){
return decodeURIComponent(r[2]);
}
return '';
}