dao:不处理,抛异常;
service:不处理,抛异常;
controller/servlet:必须处理,否则错误信息将直接在浏览器显示给用户看。
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.azuregroupId>
<artifactId>day57projects_SpringMVC_ssmartifactId>
<version>1.0-SNAPSHOTversion>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
dependencies>
project>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.azure">context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/">property>
<property name="suffix" value=".jsp">property>
bean>
<mvc:annotation-driven>mvc:annotation-driven>
<mvc:resources mapping="/pages/**" location="/pages/">mvc:resources>
<mvc:resources mapping="/js/**" location="/pages/">mvc:resources>
beans>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>dispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springMVC.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>dispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
@Controller
public class ExpController {
/**
* 模拟异常
*/
@RequestMapping("/save")
public String save(){
int i = 1/0;
return "success";
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
error
出错啦~系统繁忙~
@Controller
public class ExpController {
/**
* 模拟异常
*/
@RequestMapping("/save")
public String save(ModelMap modelMap){
try {
int i = 1/0;
} catch (Exception e) {
e.printStackTrace();
//将异常信息发送给error.jsp页面,error页面获取并显示错误信息
modelMap.addAttribute("errorMsg","出错啦~系统繁忙~");
return "error";
}
return "success";
}
}
public class CustomerExceptionResolver implements HandlerExceptionResolver {
@Override
public ModelAndView resolveException(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) {
//1.打印异常信息
e.printStackTrace();
//2.保存异常信息并跳转到错误页面
ModelAndView mv = new ModelAndView();
mv.addObject("errorMsg", "出错啦~系统繁忙~");
mv.setViewName("error");
return mv;
}
}
<bean class="com.azure._01exception.CustomerExceptionResolver">
@Controller
public class HERController {
/**
* 模拟异常
*/
@RequestMapping("/saved")
public String saved(ModelMap modelMap) {
int i = 1 / 0;
return "success";
}
}
相同点:
区别:
/*
实现拦截所有访问请求;而拦截器只会拦截访问控制器方法的请求,不会对网页资源(html、jsp等)进行拦截。@Controller
public class HIDemoController {
//构造函数
public HIDemo1Controller(){
System.out.println("1.实例UserController");
}
@RequestMapping("/interceptor")
public ModelAndView testInterceptor(){ //存入数据并跳转页面
System.out.println("4.执行控制器的testInterceptor方法");
ModelAndView mv = new ModelAndView();
mv.addObject("username", "JoJo");
mv.setViewName("success");
return mv;
}
}
public class HandlerInterceptor1 implements HandlerInterceptor {
//构造函数
public HandlerInterceptor1(){
System.out.println("2.实例拦截器1号");
}
/**
* 编写请求拦截方法,包含业务逻辑控制校验代码
* 返回值为true:放行,进入拦截器链的下一个拦截器,如果是最后一个,则执行控制器的方法
* 返回值为false:不放行,请求不被处理
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("3.拦截器1号的preHandle方法已执行");
return true;
}
/**
* 编写响应拦截方法,在请求处理完返回响应前调用
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("5.拦截器1号的postHandle方法已执行");
}
/**
* 编辑资源清理方法,在preHandle返回true就会被调用
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("6.拦截器1号的afterCompletion方法已执行");
}
}
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.azure">context:component-scan>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/">property>
<property name="suffix" value=".jsp">property>
bean>
<mvc:annotation-driven>mvc:annotation-driven>
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.azure._02Interceptor.HandlerInterceptor1">bean>
mvc:interceptor>
mvc:interceptors>
beans>
@Component
public class HandlerInterceptor2 implements HandlerInterceptor {
//构造函数
public HandlerInterceptor2(){
System.out.println("实例拦截器2号");
}
/**
* 编写请求拦截方法,包含业务逻辑控制校验代码
* 返回值为true:放行,进入拦截器链的下一个拦截器,如果是最后一个,则执行控制器的方法
* 返回值为false:不放行,请求不被处理
*/
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
System.out.println("拦截器2号的preHandle方法已执行");
return true;
}
/**
* 编写响应拦截方法,在请求处理完返回响应前调用
*/
public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
System.out.println("拦截器2号的postHandle方法已执行");
}
/**
* 编辑资源清理方法,在preHandle返回true就会被调用
*/
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
System.out.println("拦截器2号的afterCompletion方法已执行");
}
}
<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**" />
<bean class="com.azure._02Interceptor.HandlerInterceptor1">bean>
mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<ref bean="handlerInterceptor2">ref>
mvc:interceptor>
mvc:interceptors>
xml和注解组合使用
配置方式的选择:
Spring整合Mybatis关键点:把Mybatis的SqlSessionFactory对象的创建交给Spring管理。
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0modelVersion>
<groupId>com.azuregroupId>
<artifactId>day57projects_SSMartifactId>
<version>1.0-SNAPSHOTversion>
<packaging>warpackaging>
<dependencies>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-contextartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.aspectjgroupId>
<artifactId>aspectjweaverartifactId>
<version>1.8.9version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-webmvcartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-txartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-jdbcartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatis-springartifactId>
<version>1.3.1version>
dependency>
<dependency>
<groupId>org.springframeworkgroupId>
<artifactId>spring-testartifactId>
<version>5.0.2.RELEASEversion>
dependency>
<dependency>
<groupId>junitgroupId>
<artifactId>junitartifactId>
<version>4.12version>
dependency>
<dependency>
<groupId>mysqlgroupId>
<artifactId>mysql-connector-javaartifactId>
<version>5.1.30version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>druidartifactId>
<version>1.1.10version>
dependency>
<dependency>
<groupId>org.mybatisgroupId>
<artifactId>mybatisartifactId>
<version>3.4.5version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>servlet-apiartifactId>
<version>2.5version>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jsp-apiartifactId>
<version>2.0version>
dependency>
<dependency>
<groupId>jstlgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
<dependency>
<groupId>log4jgroupId>
<artifactId>log4jartifactId>
<version>1.2.17version>
dependency>
dependencies>
project>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<context:component-scan base-package="com.azure.service">context:component-scan>
beans>
public class Account {
private int accountId;
private int uid;
private double money;
...
}
public interface IAccountService {
/*实现查询功能*/
List<Account> findAll();
}
@Service
public class AccountServiceImpl implements IAccountService {
@Override
public List<Account> findAll() {
System.out.println("测试。。。调用service的findAll查询全部账户");
return null;
}
}
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml") //指定容器类
public class TestDemo01 {
//注入service
@Autowired
private IAccountService accountService;
@Test
public void find(){
accountService.findAll();
}
}
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
version="2.5">
<servlet>
<servlet-name>DispatcherServletservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springMVC.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>DispatcherServletservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
web-app>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.azure.controller"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/pages/">property>
<property name="suffix" value=".jsp">property>
bean>
<mvc:annotation-driven>mvc:annotation-driven>
beans>
@Controller
public class AccountController {
@RequestMapping("/findAll")
public ModelAndView findAll(HttpServletRequest request) {
ModelAndView mv = new ModelAndView();
mv.addObject("name", "JoJo");
mv.setViewName("success");
return mv;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
success
success~~
@Controller
@RequestMapping("/account") //设置第一级目录,方便区分findAll方法
public class AccountController {
//注入service
@Autowired
private IAccountService accountService;
@RequestMapping("/findAll")
public ModelAndView findAll(HttpServletRequest request) {
List<Account> list = accountService.findAll();
ModelAndView mv = new ModelAndView();
mv.addObject("list", list);
mv.setViewName("success");
return mv;
}
}
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListenerlistener-class>
listener>
<context-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:applicationContext.xmlparam-value>
context-param>
<configuration>
<properties resource="jdbc.properties"/>
<environments default="mysql">
<environment id="mysql">
<transactionManager type="JDBC">transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
dataSource>
environment>
environments>
<mappers>
<package name="com.azure.dao">package>
mappers>
configuration>
public interface IAccountDao {
/**
* 查询功能
*/
@Select("select * from account") //使用注解方式实现查询
List<Account> findAll();
}
public class TestDemo02 {
@Test
public void findAll() throws IOException {
InputStream is = Resources.getResourceAsStream("SqlMapConfig.xml");
SqlSessionFactoryBuilder builder = new SqlSessionFactoryBuilder();
SqlSessionFactory factory = builder.build(is);
SqlSession session = factory.openSession();
//创建Dao实现类
IAccountDao accountDao = session.getMapper(IAccountDao.class);
List<Account> list = accountDao.findAll();
System.out.println(list);
session.close();
is.close();
}
}
思路:
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context" xmlns:tx="http://www.springframework.org/schema/tx"
xmlns:aop="http://www.springframework.org/schema/aop"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd">
<context:component-scan base-package="com.azure.service">context:component-scan>
<context:property-placeholder location="classpath:jdbc.properties"/>
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
<property name="driverClassName" value="${jdbc.driver}"/>
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
bean>
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
bean>
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.azure.dao"/>
bean>
<bean id="txManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"/>
bean>
<tx:advice id="txadvice" transaction-manager="txManager">
<tx:attributes>
<tx:method name="find*" propagation="SUPPORTS" read-only="true"/>
<tx:method name="*" propagation="REQUIRED" read-only="false"/>
tx:attributes>
tx:advice>
<aop:config>
<aop:pointcut id="pt" expression="execution(* com.azure.service.*.*(..))">aop:pointcut>
aop:config>
beans>
@Service
public class AccountServiceImpl implements IAccountService {
//注入Dao
@Autowired
private IAccountDao accountDao;
@Override
public List<Account> findAll() {
return accountDao.findAll();
}
}
分两部分:
@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration("classpath:applicationContext.xml") //指定容器类
public class TestDemo03 {
//注入service
@Autowired
private IAccountService accountService;
@Test
public void find(){
List<Account> accounts = accountService.findAll();
System.out.println(accounts);
}
}
success.jsp:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
success
查询所有账户
success~~
序号
账号编号
用户编号
账户余额
<%--遍历结果获取每个元素并打印--%>
<%--varStatus相当于遍历的i--%>
${num.count}
${account.accountId}
${account.uid}
${account.money}