SSM第三季-SpringMVC-Controller方法返回值&SSM整合案例&配置异常处理器
SpringMVC
SpringMVC简要处理流程
Controller方法返回值
① ModelAndView
②void:使用原生的request,response
③String:
Ⅰ 返回视图名 viewName推荐使用
Ⅱ返回forward
Ⅲ 重定向redirect
④ 自定义类型-需要@ResponseBody注解
package com.sikiedu.controller;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.servlet.ModelAndView;
import com.sikiedu.bean.ItemInfo;
/**
* 商品管理 游戏管理
* @author AzurLane
*Controller方法返回值
*/
@Controller
//简化路径 /item/xxx.do
@RequestMapping(value="/item/")
public class ItemController {
//ModelAndView 返回模型和视图
//多请求路径, 设置请求方法(不写的话,默认全部方法都支持)
@RequestMapping(value= {"list.do","mylist.do"},method= {RequestMethod.GET,RequestMethod.POST})
public ModelAndView list() {
ModelAndView mav = new ModelAndView();
//传递数据
ItemInfo info1 = new ItemInfo("1","碧蓝航线","休闲","0");
ItemInfo info2 = new ItemInfo("2","魔兽世界","RPG","0");
ItemInfo info3 = new ItemInfo("3","绝地求生","射击","90");
ItemInfo info4 = new ItemInfo("4","英雄联盟","MOBA","0");
List<ItemInfo> itemList = new ArrayList<ItemInfo>();
itemList.add(info1);
itemList.add(info2);
itemList.add(info3);
itemList.add(info4);
//将游戏列表返回给前台
mav.addObject("itemList",itemList);
mav.setViewName("/WEB-INF/jsp/item_list.jsp");
return mav;
}
//void 使用原生的request和response
@RequestMapping(value="")
public void voidTest(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
//获取参数
request.getParameter("");
//转发
request.getRequestDispatcher("").forward(request, response);
//重定向
response.sendRedirect(request.getContextPath() + "/xx.jsp");
}
//String 转发
@RequestMapping("forwardString.do")
public String forwardString() {
return "forward:mylist.do";
}
//String 重定向
@RequestMapping("redirectString.do")
public String redirectString() {
return "redirect:/form.jsp";
}
//String 返回视图名 viewName 推荐使用
@RequestMapping("testList.do")
public String testList(Model model) {
//传递数据
ItemInfo info1 = new ItemInfo("1","碧蓝航线","休闲","0");
ItemInfo info2 = new ItemInfo("2","魔兽世界","RPG","0");
ItemInfo info3 = new ItemInfo("3","绝地求生","射击","90");
ItemInfo info4 = new ItemInfo("4","英雄联盟","MOBA","0");
List<ItemInfo> itemList = new ArrayList<ItemInfo>();
itemList.add(info1);
itemList.add(info2);
itemList.add(info3);
itemList.add(info4);
//将游戏列表返回给前台
model.addAttribute("itemList",itemList);
return "/WEB-INF/jsp/item_list.jsp";
}
}
SpringMVC&Spring&MyBatis整合
整合ssm 3大框架
a) 导包 -> spring_Jar整理 -> ssm框架整合包
c3p0-0.9.5.5.jar
com.springsource.org.aopalliance-1.0.0.jar
com.springsource.org.apache.commons.logging-1.1.1.jar
com.springsource.org.aspectj.weaver-1.6.8.RELEASE.jar
jstl-1.2.jar
mchange-commons-java-0.2.19.jar
mybatis-3.4.6.jar
mybatis-spring-1.3.2.jar
mysql-connector-java-8.0.16.jar
spring-aop-5.0.8.RELEASE.jar
spring-aspects-5.0.8.RELEASE.jar
spring-beans-5.0.8.RELEASE.jar
spring-context-5.0.8.RELEASE.jar
spring-core-5.0.8.RELEASE.jar
spring-expression-5.0.8.RELEASE.jar
spring-jdbc-5.0.8.RELEASE.jar
spring-tx-5.0.8.RELEASE.jar
spring-web-5.0.8.RELEASE.jar
spring-webmvc-5.0.8.RELEASE.jar
standard.jar
jackson-annotations-2.9.6.jar
jackson-core-2.9.6.jar
jackson-databind-2.9.6.jar
b) 配置 -> web.xml
i. 读取spring配置文件;
ii. 配置springmvc前端控制器;
<?xml version="1.0" encoding="UTF-8"?>
<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">
<display-name>ssm_project_springmvc</display-name>
<!-- 过滤器 解决表单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>*.do</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<!-- 读取配置文件 -->
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<!-- 拦截规则 -->
<!--
1 *.html *.do *.action 以扩展名方式进行拦截,不拦截静态资源 .jpg .css .js .png 什么情况下都可以使用
2 / 不拦截 jsp 拦截静态资源 .jpg .css .js .png RESTful 风格 静态资源放行 稍后会讲到
/* 全都拦截 包括jsp 以及所有静态资源 不推荐使用的
-->
<url-pattern>*.do</url-pattern>
</servlet-mapping>
</web-app>
c) 配置 -> applicationContext.xml
i. 读取数据库配置文件;
ii. 配置数据源连接池;
iii. 开启注解扫描;
iv. 配置事务核心管理器;
v. 开启注解事务;
vi. 配置视图解析器;
vii. 配置Mybatis:
\1. 配置sqlSessionFactory;
\2. 配置别名;
\3. 配置mapper工厂;
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx" xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.3.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.3.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context-4.3.xsd
http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-4.3.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-4.3.xsd">
<!-- 读取配置文件 数据库 -->
<context:property-placeholder location="classpath:db.properties"/>
<!-- 配置数据源 -->
<bean name="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driverClass}"/>
<property name="jdbcUrl" value="${jdbc.jdbcUrl}"/>
<property name="user" value="${jdbc.user}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!-- 开启注解扫描 -->
<context:component-scan base-package="com.sikiedu"></context:component-scan>
<!-- 开启注解驱动 -->
<mvc:annotation-driven/>
<!-- 事务核心管理器 -->
<bean name="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
</bean>
<!-- 开启注解事务 -->
<tx:annotation-driven/>
<!-- 配置视图解析器 -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- 配置mybatis -->
<bean name="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="typeAliasesPackage" value="com.sikiedu.bean"/>
</bean>
<!-- mapper工厂 -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.sikiedu.mapper"/>
</bean>
</beans>
SpringMVC参数绑定与数据交互
bean层
ItemInfo.java
package com.sikiedu.bean;
/**
* 游戏信息
* @author AzurLane
*
*/
public class ItemInfo {
private String item_id;
private String item_name;
private String item_type;
private Double item_price;
/*get和set方法*/
}
ItemInfoVo.java
package com.sikiedu.bean;
import java.util.List;
/**
* 包装类 ItemInfoVo
* @author AzurLane
*
*/
public class ItemInfoVo {
private ItemInfo itemInfo;
private String[] ids;
private List<Double> priceList;
/*get和set方法*/
}
mapper层
ItemMapper.接口
package com.sikiedu.mapper;
import java.util.List;
import com.sikiedu.bean.ItemInfo;
import com.sikiedu.bean.ItemInfoVo;
/**
*
* @author AzurLane
*
*/
public interface ItemMapper {
//查询全部
public List<ItemInfo> selectAll();
//根据id查询
public ItemInfo selectItemInfoById(String id);
public void deleteById(String id);
//保存
public void save(ItemInfo item);
//根据vo查询 返回列表
public List<ItemInfo> selectByVo(ItemInfoVo vo);
}
ItemMapper.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.sikiedu.mapper.ItemMapper">
<select id="selectAll" resultType="ItemInfo">
SELECT * FROM item_info
</select>
<!-- //根据id 查询ItemInfo
public ItemInfo selectItemInfoById(String id); -->
<select id="selectItemInfoById" parameterType="String" resultType="ItemInfo">
SELECT * FROM item_info WHERE item_id = #{id}
</select>
<!-- //根据id删除
public void deleteById(String id); -->
<delete id="deleteById" parameterType="String">
DELETE FROM item_info WHERE item_id = #{id}
</delete>
<!-- //保存
public void save(ItemInfo item); -->
<insert id="save" parameterType="ItemInfo">
INSERT INTO item_info VALUES(
#{item_id},
#{item_name},
#{item_type},
#{item_price}
)
</insert>
<!-- //根据vo 查询 返回列表
public List<ItemInfo> selectByVo(ItemInfoVo vo); -->
<select id="selectByVo" parameterType="ItemInfoVo" resultType="ItemInfo">
SELECT * FROM item_info
<where>
<!-- 多条件查询 -->
<if test="itemInfo.item_id != null and itemInfo.item_id != ''">
item_id = #{itemInfo.item_id}
</if>
<if test="itemInfo.item_name != null and itemInfo.item_name != ''">
and item_name LIKE "%"#{itemInfo.item_name}"%"
</if>
<if test="itemInfo.item_type != null and itemInfo.item_type != ''">
and item_type = #{itemInfo.item_type}
</if>
<if test="itemInfo.item_price != null and itemInfo.item_price != ''">
and item_price = #{itemInfo.item_price}
</if>
</where>
</select>
</mapper>
service层
ItemService.java接口
package com.sikiedu.service;
import java.util.List;
import com.sikiedu.bean.ItemInfo;
import com.sikiedu.bean.ItemInfoVo;
public interface ItemService {
//查询全部
public List<ItemInfo> selectAll();
public ItemInfo selectItemInfoById(String id);
//根据id删除
public void deleteById(String id);
//保存
public void save(ItemInfo item);
//根据vo查询返回列表
public List<ItemInfo> selectByVo(ItemInfoVo vo);
}
ItemServiceImpl.java
package com.sikiedu.service;
import java.util.List;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import com.sikiedu.bean.ItemInfo;
import com.sikiedu.bean.ItemInfoVo;
import com.sikiedu.mapper.ItemMapper;
@Service
public class ItemServiceImpl implements ItemService{
@Autowired
private ItemMapper itemMapper;
@Override
public List<ItemInfo> selectAll() {
return itemMapper.selectAll();
}
@Override
public ItemInfo selectItemInfoById(String id) {
return itemMapper.selectItemInfoById(id);
}
@Override
public void deleteById(String id) {
itemMapper.deleteById(id);
}
@Override
public void save(ItemInfo item) {
itemMapper.save(item);
}
//通过包装类查询
@Override
public List<ItemInfo> selectByVo(ItemInfoVo vo) {
return itemMapper.selectByVo(vo);
}
}
controller层
ItemController.java
参数绑定-默认参数&基本类型&bean对象&包装类&数组&List
package com.sikiedu.controller;
import java.util.ArrayList;
import java.util.List;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
import com.sikiedu.bean.ItemInfo;
import com.sikiedu.bean.ItemInfoVo;
import com.sikiedu.service.ItemService;
/**
* 游戏信息管理
*
* @author AzurLane
*
*/
@Controller
@RequestMapping("/item/")
public class ItemController {
@Autowired
private ItemService itemService;
//主页面
@RequestMapping("allList.do")
public ModelAndView list() {
ModelAndView mav = new ModelAndView();
List<ItemInfo> itemList = itemService.selectAll();
// 查询 将结果赋值给mav
mav.addObject("itemList", itemList);
// 设置视图名
mav.setViewName("item_list");
return mav;
}
@RequestMapping("select.do")
public String select(HttpServletRequest request, HttpServletResponse response, HttpSession session, Model model) {
String id = request.getParameter("id");
ItemInfo item = itemService.selectItemInfoById(id);
List<ItemInfo> itemList = new ArrayList<ItemInfo>();
itemList.add(item);
// model
model.addAttribute("itemList", itemList);
// 返回视图名称 保存数据
return "item_list";
}
// 基本类型参数绑定
@RequestMapping("delete.do")
// 此处的id要与前台传递的id名字相同 如果不相同需要使用
// public String delete(@RequestParam(value="id",required=false,
// defaultValue="1")String deleteId)
public String delete(String id) {
// 从前台获取id
System.out.println("delete id = " + id);
// 删除
itemService.deleteById(id);
// 重定向到列表页
return "redirect:allList.do";
}
// 绑定bean对象的形式 来完成参数的获取
@RequestMapping("save.do")
public String save(ItemInfo item) {
// 获取参数
System.out.println(item);
// 保存逻辑
itemService.save(item);
// 重定向到列表页
return "redirect:allList.do";
}
// 包装类绑定
@RequestMapping("selectByVo.do")
public String selectByVo(ItemInfoVo vo, Model model) {
// 获取vo对象
System.out.println("itemInfoVo" + vo.getItemInfo());
// 查询
List<ItemInfo> itemList = itemService.selectByVo(vo);
// 保存数据
model.addAttribute("itemList", itemList);
// 返回视图名称
return "item_list";
}
// 绑定数组
@RequestMapping("selectArrays.do")
public void selectArrays(String[] ids) {
System.out.println("ids= " + ids.length);
for (String string : ids) {
System.out.println("id=" + string);
}
}
// 绑定Vo数组
@RequestMapping("selectVoArrays.do")
public void selectVoArrays(ItemInfoVo vo) {
System.out.println("ids=" + vo.getIds().length);
for (String string : vo.getIds()) {
System.out.println("id=" + string);
}
}
// 绑定VoList集合
@RequestMapping("selectVoList.do")
public void selectVoList(ItemInfoVo vo) {
System.out.println("list=" + vo.getPriceList().size());
Double totalPrice = 0d;
for (Double price : vo.getPriceList()) {
System.out.println("price=" + price);
totalPrice += price;
}
System.out.println("总价=" + totalPrice);
}
// 接受前台的json字符串
// 使用@RequestBody注解可以将前台发送的json格式字符串转换为ItemInfo对象
// 使用@ResponseBody可以将ItemInfo对象转换为json格式字符串返回给前台
@RequestMapping("jsonData.do")
@ResponseBody
public ItemInfo jsonData(@RequestBody ItemInfo item) {
System.out.println("json Data = " + item);
return item;
}
// 回显数据
@RequestMapping("editItem.do")
@ResponseBody
public ItemInfo editItem(String id) {
// 根据id查询游戏信息
ItemInfo item = itemService.selectItemInfoById(id);
return item;
}
// 获取所有的游戏名称
// 使用@RequestBody来绑定list
// @RequestMapping("getNameList.do")
// public void getNameList(@RequestBody List<String> nameList) {
// System.out.println("nameList size" + nameList.size());
//
// for (String string : nameList) {
// System.out.println(string);
// }
// }
//使用@RequestBody来接受前台发送的集合类型
// 使用@RequestBody来绑定array数组
@RequestMapping("getNameList.do")
public void getNameList(@RequestBody String[] array) {
System.out.println("nameList size" + array.length);
for (String string : array) {
System.out.println("array name=" +string);
}
}
}
前台页面
<%@ page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta charset="UTF-8">
<title>游戏管理后台</title>
<meta name="viewport" content="initial-scale=1.0,maximum-scale=1.0,user-scalable=no">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<!-- bootstrap framework -->
<link href="${pageContext.request.contextPath }/css/bootstrap.min.css" rel="stylesheet" media="screen">
<!-- main stylesheet -->
<link href="${pageContext.request.contextPath }/css/main.min.css" rel="stylesheet" media="screen" id="mainCss">
<!-- elegant icons -->
<link href="${pageContext.request.contextPath }/css/style.css" rel="stylesheet" media="screen">
<!-- datepicker -->
<link href="${pageContext.request.contextPath }/css/datepicker3.css" rel="stylesheet" media="screen">
<!-- jBox -->
<link href="${pageContext.request.contextPath }/css/jbox.css" rel="stylesheet" media="screen">
<link href="${pageContext.request.contextPath }/css/noticeborder.css" rel="stylesheet" media="screen">
</head>
<body class="side_menu_active side_menu_expanded">
<div id="page_wrapper">
<!-- header -->
<header id="main_header">
<div class="container-fluid">
<!--logo-->
<div class="brand_section">
<a href="#"><img src="${pageContext.request.contextPath }/picture/logo01.png" alt="site_logo" width="108" height="40" style="margin-top: 5px"></a>
</div>
<div class="header_user_actions dropdown">
<div data-toggle="dropdown" class="dropdown-toggle user_dropdown">
<div class="user_avatar">
<img src="${pageContext.request.contextPath }/picture/head01.png" width="38" height="38">
</div>
<span class="caret"></span>
</div>
<ul class="dropdown-menu dropdown-menu-right">
<li><a href="#">个人中心</a></li>
<li><a href="#">注销</a></li>
</ul>
</div>
</div>
</header>
<!-- main content -->
<div id="main_wrapper">
<div class="container-fluid">
<div class="row">
<div class="col-md-12">
<form action="${pageContext.request.contextPath }/item/selectByVo.do" method="post">
<input type="text" placeholder="id" name="itemInfo.item_id"/>
<input type="text" placeholder="名称" name="itemInfo.item_name"/>
<input type="text" placeholder="类型" name="itemInfo.item_type"/>
<input type="text" placeholder="原价" name="itemInfo.item_price"/>
<input type="submit" value="查询"/>
</form>
<div class="row">
<div class="col-md-10">
<!-- <form action="${pageContext.request.contextPath }/item/selectArrays.do" method="post"> -->
<!--<form action="${pageContext.request.contextPath }/item/selectVoArrays.do" method="post">-->
<form action="${pageContext.request.contextPath }/item/selectVoList.do" method="post">
<table class="table table-yuk2 toggle-arrow-tiny" id="footable_demo" data-filter="#textFilter" data-page-size="5">
<thead>
<tr>
<!--描述:商品数据标签-->
<th>ID</th>
<th>游戏名称</th>
<th>类型</th>
<th>原价</th>
</tr>
</thead>
<tbody>
<c:forEach items="${itemList }" var="item" varStatus="i">
<tr>
<td><input type="checkbox" name="ids" value="${item.item_id }" /></td>
<td>${item.item_id }</td>
<td><input type="text" class="input_item_name" value="${item.item_name }"></td>
<td>${item.item_type }</td>
<td><input type="text" name="priceList[${i.index}]" value="${item.item_price }"></td>
<!-- <td>${item.item_price }</td> -->
<td data-value="1">
<a herf="#" id="edit_btn" class="btn btn-xs btn-info" data-toggle="modal" data-target="#editLayer" οnclick="editItem('${item.item_id}')">修改</a>
<a herf="#" id="del_btn" class="btn btn-xs btn-danger" οnclick="deleteItem('${item.item_id}')">删除</a>
</td>
</tr>
</c:forEach>
</tbody>
<tfoot class="hide-if-no-paging">
<tr>
<td colspan="5">
<ul class="pagination pagination-sm"></ul>
</td>
</tr>
</tfoot>
</table>
<input type="submit" value="获取id数组">
<input type="submit" value="获取总价">
<input type="button" value="ajax提交json数据" οnclick="jsonData()">
<input type="button" value="获取所有name" οnclick="getNameList()">
</form>
</div>
</div>
</div>
</div>
</div>
</div>
<!-- edit layer -->
<div class="modal fade" id="editLayer">
<div class="modal-dialog modal-content">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">修改游戏信息</h4>
</div>
<div class="modal-body">
<!--游戏修改详情弹出层表单-->
<form class="form-horizontal" id="edit_item_form">
<!-- 游戏id隐藏域 -->
<input type="hidden" id="edit_item_id" name="item_id"/>
<!-- 游戏名称 -->
<div class="form-group">
<label for="edit_item_name" class="col-sm-2 control-label">游戏名称</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="edit_item_name" placeholder="游戏名称" name="item_name">
</div>
</div>
<!-- 游戏类型 -->
<div class="form-group">
<label for="edit_item_type" class="col-sm-2 control-label">类型</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="edit_item_type" placeholder="类型" name="item_type">
</div>
</div>
<!-- 游戏原价 -->
<div class="form-group">
<label for="edit_item_price" class="col-sm-2 control-label">原价</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="edit_item_price" placeholder="原价" name="item_price">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-sm" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary btn-sm" οnclick="updateItem()">确认修改</button>
</div>
</div>
</div>
</div>
<!-- add layer -->
<div class="modal fade" id="addLayer">
<div class="modal-dialog modal-content">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="close" data-dismiss="modal"><span aria-hidden="true">×</span><span class="sr-only">Close</span></button>
<h4 class="modal-title">新增游戏</h4>
</div>
<div class="modal-body">
<!--添加游戏弹出层表单-->
<form class="form-horizontal" id="add_item_form">
<!-- 游戏id -->
<div class="form-group">
<label for="add_item_id" class="col-sm-2 control-label">游戏id</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="add_item_id" placeholder="游戏id" name="item_id">
</div>
</div>
<!-- 游戏名称 -->
<div class="form-group">
<label for="add_item_name" class="col-sm-2 control-label">游戏名称</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="add_item_name" placeholder="游戏名称" name="item_name">
</div>
</div>
<!-- 游戏类型 -->
<div class="form-group">
<label for="add_item_type" class="col-sm-2 control-label">类型</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="add_item_type" placeholder="类型" name="item_type">
</div>
</div>
<!-- 游戏原价 -->
<div class="form-group">
<label for="add_item_price" class="col-sm-2 control-label">原价</label>
<div class="col-sm-10">
<input type="text" class="form-control" id="add_item_price" placeholder="原价" name="item_price">
</div>
</div>
</form>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-default btn-sm" data-dismiss="modal">取消</button>
<button type="button" class="btn btn-primary btn-sm" οnclick="addItem()">确认添加</button>
</div>
</div>
</div>
</div>
<!-- main menu -->
<nav id="main_menu">
<div class="menu_wrapper">
<ul>
<li class="first_level">
<a href="javascript:void(0)">
<span class="icon_document_alt first_level_icon"></span>
<span class="menu-title">游戏管理</span>
</a>
<ul>
<li class="submenu-title">游戏管理</li>
<li><a href="#" data-toggle="modal" data-target="#addLayer">商品添加</a></li>
<li><a href="${pageContext.request.contextPath }/item/myitemlist.do">游戏列表</a></li>
</ul>
</li>
</ul>
</div>
<div class="menu_toggle">
<span class="icon_menu_toggle">
<i class="arrow_carrot-2left toggle_left"></i>
<i class="arrow_carrot-2right toggle_right" style="display:none"></i>
</span>
</div>
</nav>
</div>
<!-- jQuery -->
<script src="${pageContext.request.contextPath }/js/jquery.min.js"></script>
<!-- jQuery Cookie -->
<script src="${pageContext.request.contextPath }/js/jquerycookie.min.js"></script>
<!-- Bootstrap Framework -->
<script src="${pageContext.request.contextPath }/js/bootstrap.min.js"></script>
<!-- retina images -->
<script src="${pageContext.request.contextPath }/js/retina.min.js"></script>
<!-- switchery -->
<script src="${pageContext.request.contextPath }/js/switchery.min.js"></script>
<!-- typeahead -->
<script src="${pageContext.request.contextPath }/js/typeahead.bundle.min.js"></script>
<!-- fastclick -->
<script src="${pageContext.request.contextPath }/js/fastclick.min.js"></script>
<!-- match height -->
<script src="${pageContext.request.contextPath }/js/jquery.matchheight-min.js"></script>
<!-- scrollbar -->
<script src="${pageContext.request.contextPath }/js/jquery.mcustomscrollbar.concat.min.js"></script>
<!-- moment.js (date library) -->
<script src="${pageContext.request.contextPath }/js/moment-with-langs.min.js"></script>
<!-- Yukon Admin functions -->
<script src="${pageContext.request.contextPath }/js/yukon_all.min.js"></script>
<!-- page specific plugins -->
<!-- footable -->
<script src="${pageContext.request.contextPath }/js/footable.min.js"></script>
<script src="${pageContext.request.contextPath }/js/footable.paginate.min.js"></script>
<script src="${pageContext.request.contextPath }/js/footable.filter.min.js"></script>
<!-- datepicker -->
<script src="${pageContext.request.contextPath }/js/bootstrap-datepicker.js"></script>
<!-- jBox -->
<script src="${pageContext.request.contextPath }/js/jbox.min.js"></script>
<script type="text/javascript">
$(function() {
//footable
yukon_footable.goodslist();
//datepicker
yukon_datepicker.p_forms_extended();
})
//修改弹框回显
function toEdit(id) {
$.ajax({
type:"post",
url:"${pageContext.request.contextPath }/item/toEdit",
data:{"id":id},
success:function(data) {
$("#edit_item_name").val(data.item_name);
$("#edit_item_type").val(data.item_type);
$("#edit_item_price").val(data.item_price);
},
dataType:"json"
});
}
//确认修改
function updateItem() {
$.post(
"${pageContext.request.contextPath }/item/update.do",
$("#edit_item_form").serialize(),
function(data){
alert("游戏信息更新成功!");
window.location.reload();
});
}
//确认删除
function deleteItem(id) {
if(confirm('确实要删除该游戏吗?')) {
$.post(
"${pageContext.request.contextPath }/item/delete.do",
{"id":id},
function(data){
window.location.reload();
});
}
}
//添加游戏
function addItem() {
$.post(
"${pageContext.request.contextPath }/item/save.do",
$("#add_item_form").serialize(),
function(data){
alert("游戏添加成功!");
window.location.reload();
});
}
function getNameList() {
//获取所有name值
//保存所有name值
var nameList = new Array();
$(".input_item_name").each(function() {
nameList.push($(this).val());
});
//发送到后台
$.ajax({
type:"post",
url:"${pageContext.request.contextPath}/item/getNameList.do",
contentType:"application/json;charset=utf-8",
data:JSON.stringify(nameList)
});
}
//修改弹性回显
function editItem(id) {
$.ajax({
type:"post",
url:"${pageContext.request.contextPath}/item/editItem.do",
data:{"id":id},
dataType:"json",
success:function(data){
//alert(data.item_type)
$('#edit_item_name').val(data.item_name);
$('#edit_item_type').val(data.item_type);
$('#edit_item_price').val(data.item_price);
}
});
}
//使用ajax发送和接受json格式的字符串
function jsonData() {
//json格式的字符串 要传输的数据
var jsondata = '{"item_id":"99","item_name":"超级玛丽","item_type":"横版过关","item_price":25}';
$.ajax({
type:"post",
url:"${pageContext.request.contextPath}/item/jsonData.do",
//发送的数据格式
contextType:"application/json;charset=utf-8",
//回调的格式
dataType:"json",
data:jsondata,
success:function(data){
alert(data.item_name);
}
});
}
</script>
</body>
</html>
页面效果
异常处理器
捕获自定义异常和运行时异常
在applicationContext.xml中配置异常处理器
<!-- 配置异常处理器 -->
<bean class="com.sikiedu.exception.MyHandlerExceptionResolver"/>
exception包
MyHandlerExceptionResolver.java
package com.sikiedu.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 MyHandlerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(
HttpServletRequest request,
HttpServletResponse response,
Object obj, //obj 异常对象的 全包名 + 类名+ 方法名
Exception e) {
ModelAndView mav = new ModelAndView();
//获取异常信息
String errorMsg = "";
//判断异常信息类型
if(e instanceof MyException) {
//执行自定义异常处理
errorMsg = "自定异常 " + ((MyException)e).getMsg() +" " + obj;
}else {
//运行时异常
errorMsg = "运行时异常 " + e.getMessage() +" " + obj;
}
//将异常信息输出到错误页面
mav.addObject("error", errorMsg);
//设置要跳转的视图名称
mav.setViewName("error");
return mav;
}
}
MyException.java
package com.sikiedu.exception;
/**
* 自定义 异常类
*
* @author
*/
public class MyException extends Exception {
//错误消息
private String msg;
public String getMsg() {
return msg;
}
public void setMsg(String msg) {
this.msg = msg;
}
public MyException(String msg) {
super();
this.msg = msg;
}
}
在service层中添加自定义异常和运行时异常
ItemServiceImpl.java
@Override
public List<ItemInfo> selectAll() throws MyException {
//制造运行时异常
int i = 1/0;
//制造自定义异常
if(true) {
throw new MyException("列表没有获取到");
}
return itemMapper.selectAll();
}
在Controller层的方法中抛出自定义异常
@RequestMapping("allList.do")
public ModelAndView list() throws MyException {
ModelAndView mav = new ModelAndView();
List<ItemInfo> itemList = itemService.selectAll();
// 查询 将结果赋值给mav
mav.addObject("itemList", itemList);
// 设置视图名
mav.setViewName("item_list");
return mav;
}
在WEB-INF/jsp文件夹下添加error.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<h1>${error }</h1>
</body>
</html>
使用注解式配置异常处理器
使用注解式不需要在applicationContext.xml中配置异常处理器
MyGlobalExceptionHandler.java
package com.sikiedu.exception;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
/**
* 自定义全局异常处理类
*
*/
@ControllerAdvice
public class MyGlobalExceptionHandler {
//处理运行时异常
@ExceptionHandler(RuntimeException.class)
@ResponseBody
String runtimeHandler(RuntimeException e) {
return e.getMessage();
}
//处理自定义异常
@ExceptionHandler(MyException.class)
String myHandler(MyException e, Model model) {
model.addAttribute("error", e.getMsg() + " " + e.getStackTrace()[0]);
//视图名
return "error";
}
}