avatar

目录
SpringMVC笔记(二)

[toc]

SSM整合

-- jar包
    spring(包括 springmvc)、mybatis、mybatis-spring 整合包、数据库驱动、第三方连接池

-- Dao
    -- 目标: spring 管理 SqlSessionFactory、mapper

    -- db.properties

        
Code
1
2
3
4
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/mybatis
jdbc.username=XXXX
jdbc.password=XXXX
-- log4j.properties
Code
1
2
3
4
5
6
# Global logging configuration,建议开发环境中要用debug
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
-- sqlMapConfig.xml -- 在 classpath 下创建 mybatis/sqlMapConfig.xml
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
<?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">

<typeAliases>
<!--扫描包,配置别名-->
<package name="com.machine.ms.po"/>
</typeAliases>

<configuration>
<!--
使用自动扫描器时,mapper.xml文件如果和mapper.java接口在一个目录则此处不用 定义mappers
<mappers>
<package name="cn.itcast.ssm.mapper" />
</mappers>
-->

</configuration>
-- applicationContext-dao.xml
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.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扫描器: 扫描包,自动生成mapper代理-->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="cn.itcast.springmvc.mapper"></property>
<property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
</bean>

</beans>
-- ItemsMapper.xml 逆向工程 -- ItemsMapper.java 逆向工程

-- Service
    -- 目标:
        1、Service 由 spring 管理
        2、spring 对 Service 进行事务控制。

    -- applicationContext-service.xml

    -- applicationContext-transaction.xml 

        
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
<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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.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"/>
<!--
* REQUIRED(默认值):若A中有事务,B使用A中的事务(不用再开).如果没有,B就会开启一个新的事务,并将A包含进来。
* SUPPORTS:若A中有事务,B使用A中的事务.如果A中没有事务.那么B也不使用事务.
-->
</tx:attributes>
</tx:advice>

<!-- 切面 -->
<aop:config>
<aop:advisor advice-ref="txAdvice"
pointcut="execution(* cn.itcast.springmvc.service.impl.*.*(..))"/>
</aop:config>

</beans>
-- OrderService.java
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
public interface OrderService {
//商品查询列表
public List<Items> findItemsList(QueryVo queryVo)throws Exception{

@Autowired
private ItemsMapper itemsMapper;
@Override
public List<Items> findItemsList(QueryVo queryVo) throws Exception {
//查询商品信息
return itemsMapper.findItemsList(queryVo);

}
}

-- Action

    -- springmvc.xml

        
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
<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-3.2.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.2.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.2.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">


<!-- 扫描controller注解,多个包中间使用半角逗号分隔 -->
<context:component-scan base-package="cn.itcast.ssm.controller"/>

<!--
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping"/>

<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMap pingHandlerAdapter"/>
-->
<!--
<mvc:annotation-driven>
自动加载RequestMappingHandlerMapping和RequestMappingHandlerAdapter
替代注解处理器和适配器的配置
-->

<mvc:annotation-driven />

<!-- 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>

</beans>
-- web.xml -- 加载 spring 容器,配置 springmvc 前置控制器
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">

<display-name>springmvc</display-name>

<!-- 加载spring容器 -->
<context-param>
<param-name>contextConfigLocation</param-name>
<!--
指定spring核心配置的位置
默认配置文件路径:WEB-INF/applicationContext.xml
-->
<param-value>/WEB-INF/classes/spring/applicationContext.xml,/WEB-INF/classes/spring/applicationContext-*.xml</param-value>
</context-param>

<!--配置监听器,在服务器启动时 启动Spring框架-->
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>


<!-- 解决post乱码 -->
<filter>
<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>


<!-- springmvc的前端控制器 -->
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>

<!-- contextConfigLocation不是必须的, 如果不配置 contextConfigLocation, springmvc的配置文件默认在:WEB-INF/servlet的 name+"-servlet.xml" -->
<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>springmvc</servlet-name>
<url-pattern>*.action</url-pattern>
</servlet-mapping>
<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>
</web-app>
-- OrderController
Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
@Controller
public class OrderController {
@Autowired
private OrderService orderService;

@RequestMapping("/queryItem.action")
public ModelAndView queryItem() throws Exception {
// 商品列表
List<Items> itemsList = orderService.findItemsList(null);
// 创建modelAndView准备填充数据、设置视图
ModelAndView modelAndView = new ModelAndView();
// 填充数据
modelAndView.addObject("itemsList", itemsList);
// 视图
modelAndView.setViewName("order/itemsList");
return modelAndView;
}
}
-- 测试 http://localhost:8080/springmvc_mybatis/queryItem.action

注解开发:基础

@RequestMapping

-- URL 路径映射
    -- @RequestMapping(value="/item")或@RequestMapping("/item)
    -- value 的值是数组,可以将多个 url 映射到同一个方法

-- 窄化请求映射
    -- 在 class 上添加@RequestMapping(url)指定通用请求前缀,限制此类下的所有方法请求url必须以请求前缀开头,通过此方法对url 进行分类管理

    -- 如下: 
        -- @RequestMapping 放在类名上边,设置请求前缀 

            @Controller 
            @RequestMapping("/item")
            class UserController{

            }

        -- 方法名上边设置请求映射 url:

            @RequestMapping("/queryItem ")
            public void add(){

            }

        -- 访问地址为:/item/queryItem


-- 请求方法限定

    1. 限定 GET 方法
        -- @RequestMapping(value="/editItem",method=RequestMethod.GET)
        -- 如果通过 Post 访问则报错:HTTP Status 405 - Request method 'POST' not supported

    2. 限定POST方法
        -- @RequestMapping(method = RequestMethod.POST)
        -- 如果通过 Post 访问则报错:HTTP Status 405 - Request method 'GET' not supported

    3. GET和POST都可以
        -- @RequestMapping(method={RequestMethod.GET,RequestMethod.POST})

controller方法返回值

返回 ModelAndView

controller 方法中定义 ModelAndView 对象并返回,对象中可添加 model 数据、指定 view。

返回 void

-- 在 controller 方法形参上可以定义 request 和 response,使用 request 或 response 指定响 应结果

    1、使用 request 转向页面,如下: request.getRequestDispatcher("页面路径").forward(request, response);
    2、也可以通过 response 页面重定向: response.sendRedirect("url")
    3、也可以通过 response 指定响应结果,例如响应 json 数据如下: 
        response.setCharacterEncoding("utf-8"); 
        response.setContentType("application/json;charset=utf-8"); 
        response.getWriter().write("json 串");

返回字符串

1. 逻辑视图名
    controller 方法返回字符串可以指定逻辑视图名,通过视图解析器解析为物理视图地址。
    return "item/editItem";

2. Redirect 重定向
    - Contrller 方法返回结果重定向到一个 url 地址,如下商品修改提交后重定向到商品查询方法, 参数无法带到商品查询方法中。

    
Code
1
2
3
4
5
6
7
/*
- 重定向到queryItem.action地址,request无法带过去
- redirect 方式相当于“response.sendRedirect()”
- 如果要传参数可以 /item/queryItem.action 后边加参数,如下:
return "redirect:queryItem.action?...&..."
*/
return "redirect:queryItem.action";
3. forward 转发 - controller 方法执行后继续执行另一个 controller 方法,如下商品修改提交后转向到商品修改页面,修改商品的 id 参数可以带到商品修改方法中。 /* - 结果转发到editItem.action,request可以带过去 - forward 方式相当于“request.getRequestDispatcher().forward(request,response)” - 和转发前的请求 共用一个 request 和 response。所以转发前请求的参数在转发后仍然可以读取到 */ return "forward:editItem.action";

参数绑定

参数绑定介绍

-- 处理器适配器在执行 Handler 之前需要把 http 请求的 key/value 数据绑定到 Handler 方 法形参数上。
    public void add(HttpServletRequest request){

    }

-- 注解适配器对RequestMapping标记的方法进行适配,对方法中的形参会进行参数绑定

-- 3.X 之后 springmvc 就开始使用 Converter 进行参数绑定。

默认支持的参数类型

1. HttpServletRequest
    通过 request 对象获取请求信息

2. HttpServletResponse
    通过 response 处理响应信息

3.  HttpSession
    通过 session 对象得到 session 中存放的对象

4. Model/ModelMap
    -- ModelMap 是 Model 接口的实现类,通过 Model 或 ModelMap 向页面传递数据,如下:

        
Code
1
2
3
4
5
6
Items item = itemService.findItemById(id); 
model.addAttribute("item", item);
/*
- 页面通过${item.XXXX}获取 item 对象的属性值
- 使用 Model 和 ModelMap 的效果一样,如果直接使用 Model,springmvc 会实例化 ModelMap
*/

简单类型

-- 当请求的参数名称和处理器形参**名称一致**时会将请求参数与形参进行绑定

-- 简单类型

    1. 整型

        public String editItem(Model model,Integer id) throws Exception{

        }

    2. 字符串
    3. 单精度/双精度
    4. 布尔型

        -- 处理器方法:
            public String editItem(Model model,Integer id,Boolean status) throws Exception

        -- 请求 url:
            http://localhost:8080/springmvc_mybatis/item/editItem.action?id=2&status=false
            说明:对于布尔类型的参数,请求的参数值为 true 或 false。

    -- @RequestParam
        -- 使用@RequestParam 常用于处理简单类型的绑定。

            value:参数名字,即入参的请求参数名字,如value=“item_id”表示请求的参数区中的名 字为item_id的参数的值将传入; required:是否必须,默认是true,表示请求中一定要有相应的参数,否则将报;
                TTP Status 400 - Required Integer parameter 'XXXX' is not present
            defaultV alue:默认值,表示如果请求中没有同名参数时的默认值

        --  定义如下:

             public String editItem(@RequestParam(value="item_id",required=true) String id) {
                /*
                    - 形参名称为 id,但是这里使用 value=" item_id"限定请求的参数名为 item_id,所以页面传递 参数的名必须为 item_id。
                    - required=true:如果请求参数中没有 item_id 将跑出异常

                    - 可以使用 defaultvalue 设置默认值,即使 required=true 也可以不传 item_id 参数值
                */
             }

pojo

1. 简单 pojo
    -- 将 pojo 对象中的属性名于传递进来的属性名对应,如果传进来的参数名称和对象中的属性名称一致则将参数值设置在 pojo 对象中

    -- 页面定义如下:
         <input type="text" name="name"/> 
         <input type="text" name="price"/>

    -- Contrller 方法定义如下:

        @RequestMapping("/editItemSubmit")
        public String editItemSubmit(Items items)throws Exception{ 

            /*
                请求的参数名称和 pojo 的属性名称一致,会自动将请求参数赋值给 pojo 的属性。
            */
            System.out.println(items);
        }


2. 包装 pojo

    -- 如果采用类似 struts 中[对象.属性]的方式命名,需要将 pojo 对象作为一个包装对象的属性, action 中以该包装对象作为形参。

    -- 包装对象定义如下:

        Public class QueryVo { 
            private Items items;
        }

    -- 页面定义:
        <input type="text" name="items.name" /> 
        <input type="text" name="items.price" />
    -- Controller 方法定义如下:

        public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{ 
            System.out.println(queryVo.getItems());
        }

自定义参数绑定

-- 需求: 根据业务需求自定义日期格式进行参数绑定 
-- 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;
            }
        }


    -- 配置方式 1

        <mvc:annotation-driven conversion-service="conversionService" />
        <!-- conversionService -->
        <bean id="conversionService" class="org.springframework.format.support.FormattingConversionServic eFactoryBean">
            <!-- 转换器 -->
            <property name="converters">
                <list> 
                    <bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/> 
                </list>
            </property>

        </bean>

    -- 配置方式 2

        <!--注解适配器 --> 
        <bean class="org.springframework.web.servlet.mvc.method.annotation.Request MappingHandlerAdapter">
            <property name="webBindingInitializer" ref="customBinder" />
        </bean>

        <!-- 自定义webBinder --> 
        <bean id="customBinder" class="org.springframework.web.bind.support.ConfigurableWebBindingIn itializer">
            <property name="conversionService" ref="conversionService" /> 
        </bean>
        <!-- conversionService -->
        <bean id="conversionService"
        class="org.springframework.format.support.FormattingConversionServic eFactoryBean">
        <!-- 转换器 -->
            <property name="converters">
                <list> 
                    <bean class="cn.itcast.ssm.controller.converter.CustomDateConverter"/> 
                </list>
            </property>
        </bean>            

集合类

-- 字符串数组

    -- 页面选中多个 checkbox 向 controller 方法传递
        <input type="checkbox" name="item_id" value="001"/> 
        <input type="checkbox" name="item_id" value="002"/> 
        <input type="checkbox" name="item_id" value="002"/>

    -- Controller 方法中可以用 String[]接收,定义如下:
        public String deleteitem(String[] item_id)throws Exception{ 
            System.out.println(item_id);
        }

-- List

    -- List中存放对象,并将定义的 List 放在包装类中,action 使用包装对象接收。

        Public class QueryVo {
            Private List<Items> itemList;//商品列表
            //get/set 方法.. 
        }

    -- 页面定义如下:

        <c:forEach items="${itemsList }" var="item" varStatus="s"> 
            <tr>
                <td><input type="text" name="itemsList[${s.index }].name" value="${item.name }"/></td>
                <td><input type="text" name="itemsList[${s.index }].price" value="${item.price }"/></td>
                .....
                .....
            </tr>
        </c:forEach>

    -- Contrller 方法定义如下:

        public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{ 
            System.out.println(queryVo.getItemList());
        }

-- Map

    -- 包装类中定义 Map 对象如下:

        Public class QueryVo {
            private Map<String, Object> itemInfo = new HashMap<String, Object>();
            //get/set 方法..
        }

    -- 页面定义如下:

        姓名:<inputtype="text"name="itemInfo['name']"/> 
        年龄:<inputtype="text"name="itemInfo['price']"/>

    -- Contrller 方法定义如下:
        public String useraddsubmit(Model model,QueryVo queryVo)throws Exception{ 
            System.out.println(queryVo.getStudentinfo());
        }

问题总结

中文乱码

-- POST乱码可在web.xml中配置
-- post 请求乱码解决方法有两个:
    1. 修改 tomcat 配置文件添加编码与工程编码一致
        <Connector URIEncoding="utf-8" connectionTimeout="20000" port="8080" protocol="HTTP/1.1" redirectPort="8443"/>
    2. 另外一种方法对参数进行重新编码:
         String userName new String(request.getParamter("userName").getBytes("ISO8859-1"),"utf-8")
         //ISO8859-1 是 tomcat 默认编码,需要将 tomcat 编码后的内容按 utf-8 编码

与 struts2 不同

1、 springmvc 的入口是一个 servlet 即前端控制器,而 struts2 入口是一个 filter 过虑器。
2、 springmvc 是基于方法开发(一个 url 对应一个方法),请求参数传递到方法的形参,可以     
    设计为单例或多例(建议单例),struts2是基于类开发,传递参数是通过类的属性,只能设计为多例。
3、 Struts 采用值栈存储请求和响应的数据,通过 OGNL 存取数据,
    springmvc 通过参数解 析器是将 request请求内容解析,并给方法形参赋值,将数据和视图封装成 ModelAndView 对象,
    最后又将 ModelAndView 中的模型数据通过 request域传输到页面。Jsp 视图解析 器默认使用 jstl。

注解开发:高级

Validation(了解)

数据回显

异常处理器

springmvc的异常处理采用:dao,service,action都不try catch处理异常,直接throw抛出,最后由统一异常处理器处理。用户自定义异常处理器实现系统的异常处理逻辑。

异常处理思路

两类异常:预期异常 和 运行时异常RuntimeException。

异常抛出,最后由 springmvc 前端控制器交由异常处理器进行异常处理,如下图:

15234605337603

自定义异常类

建一个自定义系统异常,如果抛出此异常 说明是系统预期处理的异常信息。否则就是运行时异常,需要改代码调试。

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
/**
* 系统自定义异常类
*/
public class CustomException extends Exception {
//错误信息描述
private String errorMessage;

public CustomException(String errorMessage) {
super(errorMessage);
this.errorMessage = errorMessage;
}

//get and set
}

自定义异常处理器

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
import org.springframework.web.servlet.HandlerExceptionResolver;
import org.springframework.web.servlet.ModelAndView;
/**
* 自定义异常处理器:若发生异常,将经过次处理器,统一处理系统抛出的异常
*/
public class CustomExceptionResolver implements HandlerExceptionResolver{


@Override
public ModelAndView resolveException
(javax.servlet.http.HttpServletRequest httpServletRequest,
javax.servlet.http.HttpServletResponse httpServletResponse,
Object o, Exception e) {

CustomException customException = null;

//首先打印错误
e.printStackTrace();

//判断错误类型
if(e instanceof CustomException){
//是系统自定义错误,转化即可
customException = (CustomException)e;
}else{
//是未知错误,定义一个 未知错误异常
customException = new CustomException("未知错误,请联系系统管理员!!");
}

//将错误信息返回给视图
ModelAndView modelAndView = new ModelAndView();
modelAndView.addObject("message",customException.getErrorMessage());
modelAndView.setViewName("errorPage");
return modelAndView;
}
}

异常处理器配置

自定义的异常处理器需要在 springmvc中申明

在 springmvc.xml 中添加:

Code
1
2
3
<!-- 自定义 系统异常处理器 代替springmvc默认异常处理器HandlerExceptionResolver -->
<bean id="handlerExceptionResolver"
class="hw.base.process.exception.CustomExceptionResolver"/>

异常测试

Code
1
2
3
4
5
6
7
8
9
10
11
12
13
14
@RequestMapping("/test")
public @ResponseBody SysUser test(String id) throws CustomException {


if(id ==null){
/*
输入校验失败,此处因该 抛出自定义异常,
然后此异常会在 自定义异常类 统一处理 再转到错误页面
*/
throw new CustomException("id值不能为空!");
}

//...
}

上传图片

json数据交互

@RequestBody

作用:

@RequestBody 注解用于读取 http 请求的内容(字符串),通过 springmvc 提供的 HttpMessageConverter 接口将读到的内容转换为 json、xml 等格式的数据并绑定到 controller 方法的参数上。

本例子应用:

@RequestBody 注解实现接收 http 请求的 json 数据,将 json 数据转换为 java 对象

@ResponseBody

作用:

该注解用于将 Controller 的方法返回的对象,通过 HttpMessageConverter 接口转换为指定格 式的数据如:json,xml 等,通过 Response 响应给客户端

本例子应用:

@ResponseBody 注解实现将 controller 方法返回对象转换为 json 响应给客户端

案例: 请求 json,响应 json 实现

环境准备

Springmvc 默认用 MappingJacksonHttpMessageConverter 对 json 数据进行转换,需要加入 jackson 的包,如下:

jackson-core-asl-1.9.11.jar
jackson-mapper-asl-1.9.11.jar

配置 json 转换器

在注解适配器中加入 messageConverters

<!--注解适配器 --> 
<bean class="org.springframework.web.servlet.mvc.method.annotation.RequestMap pingHandlerAdapter">
    <property name="messageConverters"> 
        <list>
            <bean class="org.springframework.http.converter.json.MappingJacksonHttpMessag eConverter"></bean>
        </list>
    </property>
</bean>

注意: 如果使用<mvc:annotation-driven /> 则不用定义上边的内容。

controller 编写

// 商品修改提交json信息,响应json信息     
@RequestMapping("/editItemSubmit_RequestJson")
public @ResponseBody Items editItemSubmit_RequestJson(@RequestBody
Items items) throws Exception {     
    System.out.println(items);
    //itemService.saveItem(items);
    return items; 
}

页面 js 方法编写:

//请求json响应json
function request_json(){
       $.ajax({
            type:"post",
            url:"${pageContext.request.contextPath}/item/editItemSubmit_Request Json.action",
            contentType:"application/json;charset=utf-8",
            data:'{"name":"测试商品","price":99.9}',     
            success:function(data){
                alert(data);
            }
        }); 
}

案例:请 key/value,响应 json 实现

表单默认请求 application/x-www-form-urlencoded 格式的数据即 key/value,通常有 post 和
get 两种方法,响应 json 数据是为了方便客户端处理,实现如下:

页面 js 方法编写:

//ContentType没指定将默认为:application/x-www-form-urlencoded
//其他代码和上例js一样

controller

// 商品修改提交,提交普通form表单数据,响应json 
@RequestMapping("/editItemSubmit_ResponseJson")
public @ResponseBody Items editItemSubmit_ResponseJson(Items items)
throws Exception { 
    System.out.println(items);
    //itemService.saveItem(items);
    return items; 
}

RESTful支持

拦截器

文章作者: Machine
文章链接: https://machine4869.gitee.io/2018/04/20/15326656335063/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 哑舍
打赏
  • 微信
    微信
  • 支付宝
    支付宝

评论