# SpringMVC学习笔记

# 1.介绍SpringMVC

# 1.1介绍MVC模式

A) MVC模式介绍 1.M:model 模型,业务模型和数据模型. 2.C:controller 控制器 3.V:view 视图

B) 市场上较主流MVC框架 1.SpringMVC 2.Struts 3.JFinal

C) MVC开发模式 1.优点: 使用控制器C把视图V和业务模型M分离,从而使同一个程序可以使用不同的表现形式 2.使用场景:中大型项目 3.核心:控制器

D) 只要学习MVC框架,绝大多数的精力都放在控制器

# 1.2为什么学习SpringMVC框架

A) mybatis ---解决java代码和sql语句之间的耦合---代替DAO层 B) Spring ---解决了业务层和其他各层之间的耦合---优化Service层 C) SpringMVC---解决了java代码和servlet之间的耦合---代替servlet(SpringMVC本质还是Servlet,实现了对Servlet解耦)

D)为什么要学习SpringMVC呢?

​ 1.我们在使用servlet初期的时候发现,每一个请求都对应一个servlet ,如果有100个请求,这个时候就需要写100个servlet,这样一来就 会造成servlet的数量太多,尽管后期进行了Servlet合并,但是任然是手动进行的,耦合度太高了。

​ 2.使用servlet进行数据接受的时候,比较的麻烦 ​ 3.我们目前书写的代码没有办法实现java代码和servlet之间的解耦

# 1.3什么是SpringMVC框架

1.Spring MVC属于SpringFrameWork的后续产品,已经融合在Spring Web Flow里面。

​ SpringMVC和Spring关系

​ 1.SpringMVC是Spring framework的子框架.

​ 2.SpringMVC运行后形成自己的容器.Spring也有自己的容器. ​ 2.1 称Spring的容器和SpringMVC的容器是父子容器

​ 3.SpringMVC就是比直接使用Spring多了spring-webmvc-xxx.jar

​ 4.在环境搭建时,区分开父子容器. ​ 4.1 直观表现:Spring和SpringMVC的内容可以配置在一个配置文件中.区分不开父子容器.可能导致出现问题:例如声明式事务绑定无 效(不报错,还没有效果.) ​ 4.2 处理办法:Spring的东西配置一个配置文件中,SpringMVC的东西配在一个文件中.

2.Spring MVC是一个基于MVC的web框架,Spring MVC分离了控制器,模型对象,过滤器以及处理程序对象的角色,这种分离让他们更 容易进行定制。

3.Spring MVC 3.0 后全面超越Struts2,成为最优秀的MVC框架

2.Spring MVC通过一套MVC注解,让POJO成为处理请求的控制器,而无须实现任何接口

4.采用了松散耦合可插拔组件结构,比其他MVC框架更具扩展性和灵活性

5.进行更简洁的Web层的开发

6.天生与Spring框架集成(如:IOC容器,AOP等)

7.能简单的进行web层的单元测试

8.支持灵活的URL到页面控制器的映射

9.非常容易与其他试图技术集成,

# 1.4SpringMVC框架的执行流程

1

# 1.4.1流程描述:

2

3

# 1.4.2介绍SpringMVC的组件:

4

# 1.4.3SpringMVC流程的时序图

1 以时间点作为基本单位,观察每个时间点状态. 2 具体时序图

5

3.文字解释: 当用户发起请求后,执行DiapacherServlet,如果是JSP直接调用jsp页面.如果不是JSP,DiapacherServlet调用HandlerMapping判断请求URL是否合法,如果URL不存在报错,如果URL存在使用HandlerAdapter调用具体的HandlerMethod,当Handler执行完成后会返回ModelAndView,会被ViewResovler解析,调用具体的物理视图. 最终响应给客户端浏览器.

# 2.注解开发SpringMVC入门程序

# 2.1安装旗舰版idea平台

​ A.下载地址:https://www.jetbrains.com/idea/download/#section=windows

12

IDEA 分两个版本:旗舰版(Ultimate)和 社区版(Community)。旗舰版收费(限 30 天免费试用),社区版免费。 而要做web开发只能旗舰版

IDEA 官方提供的详细使用文档:https://www.jetbrains.com/help/idea/getting-started.html

​ B.安装:

# 2.2配置idea平台使用本地Tomcat

A.首先解压一份Tomcat到一个固定位置:如D盘。

B.点击平台Run---Edit Configurations---Templates---Tomcat Server---Local---点击右侧的Configure按钮选择上面解压后的tomcat路径---Apply

6

C.点击Templates 上方的”+“---选择Tomcat Server---Local---右侧设置Name值---点击下方的Deployment---点击”+“---选择Artifact---选择war exploded---Apply---OK!

6

# 2.3SpringMVC环境搭建 配置一

​ 实现步骤:

# A.创建maven web项目

1.New Project  点击Maven 先勾选Create from archetype 选择org.apache.maven.archetypes:maven-archetype-webapp
2.设置项目名称
3.创建完成后,手动添加resources和java目录
1
2
3

# B.添加依赖

  <dependencies>
    <!--进行junit单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

	<!--Spring的5大核心jar包 -->
    <!--依赖于commons-logging日志管理 -->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>

    <!--提供了框架的基本组成部分,包括IOC 和 DI-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!-- 提供了BeanFactory-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!--上下文配置对象,提供一个框架式的对象访问方式-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!--提供了强大的表达式语言-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!--springMVC的jar包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>
    
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>
    
    <!--java web依赖 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.3</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>

    <!-- jstl表达式 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

  </dependencies>
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

# C.编写web.xml

<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>Archetype Created Web Application</display-name>
    <!--设置欢迎页 -->
    <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

	<!--配置前端控制器,拦截的是以do结尾的url -->
    <servlet>
      <servlet-name>springmvc</servlet-name>
      <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
      <!-- 自启动-在启动tomcat时立即加载对应的Servlet -->
      <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
      <servlet-name>springmvc</servlet-name>
      <url-pattern>*.do</url-pattern>
    </servlet-mapping>

  </web-app>
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

# D.创建Spring核心配置文件

要求:

​ 1.在WEB-INF下

​ 2.新建名字叫:<servlet-name>-servlet.xml配置文件,并配置内容

​ ==说明:<servlet-name>-servlet.xml 的意思是:如果web.xml中,<servlet-name>springmvc</servlet-name>那么创建的Spring框架的核心配置文件名就叫做springmvc-servlet.xml。

<?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: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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 设置注解扫描路径 -->
    <context:component-scan base-package="com.msb.controller"></context:component-scan>
	<!-- 默认加载注解处理器映射器和处理器适配器及很多的参数绑定 -->
	<mvc:annotation-driven/>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# E.编写控制器

@Controller
public class UserController {

   @RequestMapping("reg.do")
    public ModelAndView show(HttpServletRequest request){
        ModelAndView mv=new ModelAndView();
        String name=request.getParameter("username");
        request.setAttribute("uname",name);
        mv.setViewName("ok.jsp");
        System.out.println("执行show");
        return mv;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# F.创建index.jsp页面

<body>
    <form action="reg.do" method="post">
        用户名:<input type="text" name="username"><br/>
        密码:<input type="password" name="password"/><br/>
        <input type="submit" value="提交">
    </form>
</body>
1
2
3
4
5
6
7

# G.创建success.jsp页面

<body>
	req:${uname}
</body>
1
2
3

# 2.4SpringMVC环境搭建 配置二

主要解决是方法一中.do和配置文件路径及名称问题.*

​ 实现步骤:

# A.创建maven web项目

1.New Project  点击Maven 先勾选Create from archetype 选择org.apache.maven.archetypes:maven-archetype-webapp
2.设置项目名称
3.创建完成后,手动添加resources和java目录
1
2
3

# B.添加依赖

  <dependencies>
    <!--进行junit单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

	<!--Spring的5大核心jar包 -->
    <!--依赖于commons-logging日志管理 -->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>

    <!--提供了框架的基本组成部分,包括IOC 和 DI-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!-- 提供了BeanFactory-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!--上下文配置对象,提供一个框架式的对象访问方式-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!--提供了强大的表达式语言-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!--springMVC的jar包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>
    
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>
    
    <!--java web依赖 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.3</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>

    <!-- jstl表达式 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

  </dependencies>
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85

# C.编写web.xml

<web-app version="2.5"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">

    <display-name>Archetype Created Web Application</display-name>
    <welcome-file-list>
      <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

  <servlet>
    <servlet-name>springmvc</servlet-name>
    <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
    <!--init-param 告诉ServletSpringMVC配置文件在哪里 -->
    <init-param>
      <param-name>contextConfigLocation</param-name>
      <param-value>classpath:applicationContext.xml</param-value>
    </init-param>
    <!-- 自启动-在启动tomcat时立即加载对应的Servlet -->
    <load-on-startup>1</load-on-startup>
  </servlet>
  
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <!-- /的意思是:除了JSP放行,其他全按照名称去找@RequestMapping() -->
    <url-pattern>/</url-pattern>
  </servlet-mapping>

</web-app>
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

# 说明:

关于在web.xml中<url-pattern>中配置/和/* 的区别 1 /表示除了jsp全拦截, /* 拦截全部 2 如果配置/* ,出现jsp无法访问. 2.1 在springmvc配置文件中通过<mvc:resources/>把jsp当作静态资源 2.2 会出现jsp源码被直接发送给浏览器客户端.中间没有tomcat解析编译的过程 2.3 所以认为/* 的配置办法是错误

# D.创建Spring核心配置文件

src/resources下创建applicationContext.xml

<?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: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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 设置注解扫描路径 -->
    <context:component-scan base-package="com.msb.controller"></context:component-scan>
   	   <!-- 默认加载注解处理器映射器和处理器适配器及很多的参数绑定 -->
	<mvc:annotation-driven/>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

# 补充:后面讲解

<mvc:resources/>告诉SpringMVC当请求中出现什么样格式的请求时,去哪里找对应的资源.(通俗说:配置放行静态资源)

    <!-- 如果碰见请求中/js/xx格式请求,去location配置的/js中去寻找, -->
    <!-- 如果没有配置mvc:resources去寻找@requestmappingg -->
    <!-- 静态资源放行  mapping:指的是网络中URL地址  location:放行本地的什么位置的资源-->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
<mvc:resources location="/images/" mapping="/images/**"></mvc:resources>
<mvc:resources location="/css/" mapping="/css/**"></mvc:resources>
1
2
3
4
5
6

# E.编写控制器

@Controller
public class UserController {

   @RequestMapping("reg.do")
    public ModelAndView show(HttpServletRequest request){
        ModelAndView mv=new ModelAndView();
        String name=request.getParameter("username");
        request.setAttribute("uname",name);
        mv.setViewName("ok.jsp");
        System.out.println("执行show");
        return mv;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13

# F.创建index.jsp页面

<body>
    <form action="reg.do" method="post">
        用户名:<input type="text" name="username"><br/>
        密码:<input type="password" name="password"/><br/>
        <input type="submit" value="提交">
    </form>
</body>
1
2
3
4
5
6
7

# G.创建success.jsp页面

<body>
	req:${uname}
</body>
1
2
3

# 3.优化SpringMVC的入门程序

​ 例子:再注册的基础上再添加登录功能:

编写login.jsp页面:

    <body>
        <form action="login.do" method="post">
            用户名:<input type="text" name="username"><br/>
            密码:<input type="password" name="password"/><br/>
            <input type="submit" value="提交">
        </form>
    </body>
1
2
3
4
5
6
7

# 3.1优化一:

SpringMVC的控制器都是基于方法的,一个方法是一个控制器单元.

所以不需要额外创建Controller类,在原来的Controller里添加一个方法就可以。

    @RequestMapping("login.do")
    public ModelAndView login(HttpServletRequest request){
        ModelAndView mv=new ModelAndView();
        String name=request.getParameter("username");
        String pwd=request.getParameter("password");
        if("admin".equals(name) && "123".equals(pwd)){
            request.setAttribute("uname",name);
            request.setAttribute("pwd",pwd);
            mv.setViewName("ok.jsp");
        }else{
            mv.setViewName("login.jsp");
        }
        System.out.println("login");
        return mv;
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 3.2优化二:

Controller类的方法里,参数的获得可以不借助HttpServletRequest了,SpringMVC帮我们做了参数的绑定。

要求:方法参数名 与 标签中name属性值相同就可以。

    @RequestMapping("login.do")
    public ModelAndView login(String username,String password,HttpServletRequest request){
        ModelAndView mv=new ModelAndView();

        if("admin".equals(username) && "123".equals(password)){
            request.setAttribute("uname",username);
            request.setAttribute("pwd",password);
            mv.setViewName("ok.jsp");
        }else{
            mv.setViewName("login.jsp");
        }
        System.out.println("login");
        return mv;
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 3.3优化三:

​ 针对上面的优化二,将HttpServletRequest 彻底优化掉!

    @RequestMapping("login.do")
    public ModelAndView login(String username,String password){
        ModelAndView mv=new ModelAndView();

        if("admin".equals(username) && "123".equals(password)){
            mv.addObject("name",username);
            mv.addObject("pwd",password);
            mv.setViewName("ok.jsp");
        }else{
            mv.setViewName("login.jsp");
        }
        System.out.println("login");
        return mv;
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14

​ 所以 mv.addObject("username",name);用的也是请求转发!

# 4.非注解开发SpringMVC入门程序(了解)

其他操作都一样,以下为不一样的地方:

# A.控制器不一样

通过实现的方式,而不是注解

public class UserCon implements Controller {

    @Override
    public ModelAndView handleRequest
            (HttpServletRequest request, HttpServletResponse response) throws Exception {
        ModelAndView mv=new ModelAndView();
        mv.setViewName("ok.jsp");
        System.out.println("使用非注解方式,进入UserCon 处理器里,页面将跳转到ok.jsp页面");
        return mv;
    }
}
1
2
3
4
5
6
7
8
9
10
11

# B.Spring配置文件不一样(1)

没有注解路径扫描 改为bean标签创建!

<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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

 <!-- 设置注解扫描路径 -->
  <!--  <context:component-scan base-package="com.msb.controller"></context:component-scan>-->
    <bean name="ucon.do" class="com.msb.controller.UserCon"/>
    
   
   <!-- 默认加载注解处理器映射器和处理器适配器及很多的参数绑定 -->
    <mvc:annotation-driven/>
</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# C.Spring配置文件不一样(2)

默认加载了,改为bean标签手动加载

<?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: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/mvc
        http://www.springframework.org/schema/mvc/spring-mvc.xsd
        http://www.springframework.org/schema/context
        http://www.springframework.org/schema/context/spring-context.xsd">

    <!-- 告诉SpringMVC的注解在哪里 -->
  <!--  <context:component-scan base-package="com.msb.controller"></context:component-scan>-->
    <bean name="/ucon.do" class="com.msb.controller.UserCon"/>
    <!-- 配置标签让SPringMVC注解生效,创建注解解析器. -->
 <!--   <mvc:annotation-driven/>-->
    <bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
    <bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>

</beans>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# D.准备index.jsp页面

注意:href里没有斜杠
<body>
	<a href="ucon.do">点击,调整到ok页面</a>
</body>
1
2
3
4

# E.准备ok.jsp页面

<body>
    欢迎进入ok页面!
</body>
1
2
3

# 5.复习九大内置对象和四大作用域

# 5.1九大内置对象

​ 类型 对象名 描述 获取对象 ​ HttpServletRequest request 请求对象 方法参数 ​ HttpServletResponse response 响应对象 方法参数 ​ HttpSession session 会话对象 req.getSession(); ​ ServletContext application 应用程序对象 getServletContext() ​ PrintWriter out 输出对象 res.getWriter(); ​ Exception exception 异常对象 ​ PageContext pageContext 页面上下文对象 ​ ServletConfig config 配置对象 ​ Object page 当前页面对象

输出对象(2):

​ out , response

作用域对象(4):

​ pageContext ,request , session , application

打酱油对象(3):

​ exception , config , page

# 5.2 四大作用域对象

​ 1.九大内置对象中可以在特定情况下传递内容 ​ 2.四大作用域对象: ​ 1 application: 整个应用程序任何时间内容 ​ 2 session:一次会话 ​ 浏览器关闭无效 ​ 超过默认tomcat中设置的Session时间 ​ 代码手动设置的有效时间 session.setMaxInactiveInterval(123); ​ 3 request:一次请求,只要跳转必须使用转发才能继续传递 ​ 4 pageContext : 当前页面内 ​ 3.常用方法 ​ 1 setAttribute();设置值 ​ 2 getAttribute();获取值 ​ 3 removeAttribute();删除某个值 ​ 4.其他可能使用方法: ​ 1 application.getRealPath(“/”);获取到参数的真实全路径(发布到tomcat后的路径) ​ 2 request.getRequestURL();获取请求路径. ​ 3 request.getPrameter();获取请求参数 ​ 4 request.setCharacterEncoding(“utf-8”);设置请求编码 ​ 5 response.setContentType(“text/html;charset=utf-8”);设置响应头中响应内容.

# 6.SpringMVC映射请求

SpringMVC 使用 @RequestMapping 注解为控制器指定可以处理哪些URL请求

8

# 6.1@RequestMapping修饰类

注解@RequestMapping修饰类,提供初步的请求映射信息,相对于WEB应用的跟目录。

9

# 注意:

如果在类名前,使用了注解@RequestMapping,那么在处理器的方法里,在进行页面跳转的时候:

如果不经过视图解析器,那就要在跳转页面名的前面 加上“ / ”,表示页面的跳转位置从项目根目录开始;

如果没加“ /” 的意思是,以上面的例子来说,那么页面的跳转位置是从items这个逻辑文件夹开始!

# 6.2@RequestMapping修饰方法

10

11

# 详细说明:

1.@RequestMapping("/show.do")

​ ===加 / 是当前工程下,不加默认也是当前工程下

2.@RequestMapping(value={"show.do",”reg.do“})

​ ===表示两个url请求都可以进入此控制器的此方法里。

​ ===如果value的值只有一个的话,不需要加{}

​ ===如果@RequestMapping注解里只有value这一个属性的话,并且该value属性还只有一个值的话,value也可以省去。如 上面的1。

3.@RequestMapping(value={"show.do",”reg.do“} ,method={RequestMethod.POST})

​ ===value 和method两个属性之间使用 逗号,隔开

​ ===method={RequestMethod.POST} 表示当前方法只能处理POST请求,若缺省,则get/post都可以处理。

4.对请求的参数加以限制:

@RequestMapping(value={"show.do",”reg.do“} ,params={”参数名1“,”参数名2“})

​ ===表示当前方法请求参数中,必须有参数名叫 参数名1 和 参数名2 这两个参数。

@RequestMapping(value={"show.do",”reg.do“} ,params={”参数名1=value1“,”参数名2“})

​ ===表示当前方法请求参数中,必须有参数名叫 参数名1 和 参数名2 这两个参数,并且参数1的值必须为value1。

5.headers属性:作为了解

​ 指定request中必须包含某些指定的header值,才能让该方法处理请求。

@RequestMapping(value = "/pets", method = RequestMethod.GET, headers="Referer=http://www.ifeng.com/")

===表示仅处理request的header中包含了指定“Refer”请求头和对应值为“http://www.ifeng.com/”的请求;

# 7.SpringMVC返回值类型

controller 方法的返回值有三种:

A.ModelAndView

B.String

C.void

# 7.1返回ModelAndView

方法返回值定义为ModelAndView时,对象可添加model数据也可以指定view。

@RequestMapping("show.do")
    public ModelAndView show(){
        ModelAndView mv=new ModelAndView();
        List<Product> list=new ArrayList<Product>();
        list.add(new Product(1,"华为","手机",2888.8));
        list.add(new Product(2,"华为","电脑",4888.8));
        mv.addObject("list",list);
        mv.setViewName("show.jsp");
        return mv;
    }
1
2
3
4
5
6
7
8
9
10

说明:

mv.addObject("list",list); 相当于request.setAttribute("list",list);在jsp页面中通过items获得集合数据。

# 7.2返回String

方法返回值为String时,字符串内容不是随意的,而是要遵守一定的格式!有三种方式:

A.字符串内容==>表示逻辑视图名,以请求转发方式进行页面跳转,也可以是controller控制器。

​ 如:return “index.jsp”;

B.字符串内容==>以“forward:”开头,表示以请求转发方式进行页面跳转,也可以是controller控制器。

​ 如:return “forward:index.jsp”;

C.字符串内容==>以“redirect:”开头,表示以重定向方式进行页面跳转,跳转的路径可以是jsp页面,也可以是controller控制器。

​ 如:return “redirect:index.jsp”;

​ 注意: 如果applicationContext.xml里配置了视图解析器,该方法不进入【视图解析器】的。

# 7.3返回void

方法返回值为void时,有以下两种方式:

A. request.getRequestDispatcher("main.action").forward(request, response);表示请求转发方式进行页面跳转

B. response.sendRedirect("main.action");表示重定向方式进行页面跳转

# 7.4处理器形参中的数据传递对象

涉及到数据的传递时,处理器形参中添加如下类型的参数,处理器适配器会默认识别并进行赋值。

A. HttpServletRequest

​ 通过request对象进行数据的传递

B. HttpSession

​ 通过session对象进行数据的传递

C. Model/ModelMap

​ ModelMap是Model接口的实现类,将model数据填充到request作用域里,进行数据的传递。

13

# 注意:

如果使用model进行传值的时候,controller方法的返回值只能是 ModelAndView 和 String;不能是void!

# 8.SpringMVC参数绑定

# 8.1参数绑定的过程

14

从客户端请求key / value数据,经过参数绑定,将key / value数据绑定到controller方法的形参上。

springMVC中,接收页面提交的数据是通过方法形参来接收,为不是在controller类定义成员变量接收。

# 8.2参数获得的两种方式

# 8.2.1 和ServletAPI紧耦方法

(使用原生ServletAPI) SpringMVC会对所有控制器方法参数进行注入.

	@RequestMapping("demo")
	public String demo(HttpServletRequest request){
		System.out.println(request.getParameter("id"));
		System.out.println(request.getParameter("name"));
		return "index.jsp";
	}
1
2
3
4
5
6

# 8.2.2 和ServletAPI解耦方式.

# 8.2.2.1默认类型绑定

处理器形参中添加如下类型的参数,处理器适配器会默认识别并进行赋值

A. HttpServletRequest

​ 通过request对象进行数据的传递

B. HttpServletResponse

​ 通过response处理响应信息

C. HttpSession

​ 通过session对象进行数据的传递

D. Model/ModelMap

​ ModelMap是Model接口的实现类,将model数据填充到request作用域里,进行数据的传递。

model.addAttribute("list",list);
return "show.jsp"; //注意,返回值类型可以是  string  或者 ModelAndView 不可以是void!
					jsp页面使用el表达式获得model里存储的数据!
1
2
3

# 8.2.2.2简单类型绑定

简单类型支持:整型,字符串,单精度 / 双精度,布尔型

当请求的参数名称 和 处理器形参名称一致时,会将请求参数与形参进行绑定。如下:

<form action="login.do" method="post">
    登录用户名:<input type="text" name="username"/><br/>
    登录密码:<input type="password" name="password"/><br/>
    <input type="submit" value="登录提交">
    <span>${info}</span>
</form> 

//---------------------------- 

 @RequestMapping("login.do")
 public ModelAndView login(String username,String password){
        ModelAndView mv=new ModelAndView();
        if("admin".equals(username) && "123".equals(password)){ 
            mv.setViewName("success.jsp");
        }else{
            mv.setViewName("login.jsp");
        }
        return mv;
 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

如果请求的参数名称 和 处理器形参名称不一致时使用注解**@RequestParam**

注解@RequestParam 有三个属性:

​ value:请求的参数名称

​ 如:@RequestParam(value=”username”)

​ required:表示指定的参数是否必须要传入,默认为true 必须传入

​ 如:@RequestParam(required=true)

​ 注意:如果需要使用required=true ,我们要把defaultValue 默认值属性去掉!

​ defaultValue:默认值,表示如果请求中没有同名参数时的默认值

​ @RequestParam(defaultValue=”admin”)

<form action="login.do" method="post">
    登录用户名:<input type="text" name="username"/><br/>
    登录密码:<input type="password" name="password"/><br/>
    <input type="submit" value="登录提交">
    <span>${info}</span>
</form> 

//---------------------------- 

 @RequestMapping("login.do")
 public ModelAndView login(@RequestParam(value="username", defaultValue="admin")  String uname,String password){
        ModelAndView mv=new ModelAndView();
        if("admin".equals(uname) && "123".equals(password)){ 
            mv.setViewName("success.jsp");
        }else{
            mv.setViewName("login.jsp");
        }
        return mv;
 }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19

# 8.2.2.3POJO类型绑定

只要请求参数名和对象中属性名相同,自动赋值

# 8.2.2.3.1 简单POJO绑定

将pojo对象中的属性名 与 传递进来的参数名对应。

实体类:

public class Student {
    private Integer stuid;
    private String stuname;
    private double stuheight;
    private boolean isbiye;
//---get/set方法,有参/无参构造,toString()
}
1
2
3
4
5
6
7

jsp页面:

<form action="add.do" method="post">
    学生编号:<input type="text" name="stuid"/><br/>
    学生姓名:<input type="text" name="stuname"/><br/>
    学生身高:<input type="text" name="stuheight"/><br/>
    是否毕业:<input type="radio" name="isbiye" value="true"/>毕业
            <input type="radio" name="isbiye" value="false"/>未毕业<br/>
    <input type="submit" value="添加">
</form>
1
2
3
4
5
6
7
8

处理器:

    @RequestMapping("add.do")
    public ModelAndView addStu(Student stu){
        ModelAndView mv=new ModelAndView();
        mv.addObject("stu",stu);
        mv.setViewName("stuok.jsp");
        return mv;
    }
1
2
3
4
5
6
7

ok页面:

<body>
    ${stu}
</body>
1
2
3
# 8.2.2.3.2 包装POJO绑定

将pojo对象作为一个包装对象的属性,controller方法中以该包装对象作为形参。

实体类:

public class Teacher {
    private Integer teaid;
    private String teaname;
	//---get/set方法,有参/无参构造,toString()
}

public class Student {
    private Integer stuid;
    private String stuname;
    private double stuheight;
    private boolean isbiye;
    private Teacher tea;
//---get/set方法,有参/无参构造,toString()
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14

jsp页面:

<form action="add.do" method="post">

    学生编号:<input type="text" name="stuid"/><br/>
    学生姓名:<input type="text" name="stuname"/><br/>
    学生身高:<input type="text" name="stuheight"/><br/>
    是否毕业:<input type="radio" name="isbiye" value="true"/>毕业
            <input type="radio" name="isbiye" value="false"/>未毕业<br/>
    教师编号:<input type="text" name="tea.teaid"/><br/>
    教师姓名:<input type="text" name="tea.teaname"/><br/>
    <input type="submit" value="添加">
</form>
1
2
3
4
5
6
7
8
9
10
11

处理器:

    @RequestMapping("add.do")
    public ModelAndView addStu(Student stu){
        ModelAndView mv=new ModelAndView();
        mv.addObject("stu",stu);
        mv.setViewName("stuok.jsp");
        return mv;
    }
1
2
3
4
5
6
7

ok页面:

<body>
    ${stu}
</body>
1
2
3

# 8.2.2.4集合类型绑定

集合类型绑定:支持字符串数组,List,Map

【字符串数组】

实体类:

public class Student {
    private Integer stuid;
    private String stuname;
    private double stuheight;
    private boolean isbiye;
    private Teacher tea;
    private String[] likes;
    //---get/set方法,有参/无参构造,toString()
}
1
2
3
4
5
6
7
8
9

jsp页面:

<form action="add.do" method="post">

    学生编号:<input type="text" name="stuid"/><br/>
    学生姓名:<input type="text" name="stuname"/><br/>
    学生身高:<input type="text" name="stuheight"/><br/>
    是否毕业:<input type="radio" name="isbiye" value="true"/>毕业
            <input type="radio" name="isbiye" value="false"/>未毕业<br/>
    教师编号:<input type="text" name="tea.teaid"/><br/>
    教师姓名:<input type="text" name="tea.teaname"/><br/>
    你最喜欢的爱好是:<input type="checkbox" name="likes" value="book"/>图书<br/>
                    <input type="checkbox" name="likes" value="food"/>美食<br/>
                    <input type="checkbox" name="likes" value="sport"/>运动<br/>

    <input type="submit" value="添加">

</form>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16

处理器:

    @RequestMapping("add.do")
    public ModelAndView addStu(Student stu){
        ModelAndView mv=new ModelAndView();
        mv.addObject("stu",stu);
        mv.setViewName("stuok.jsp");
        return mv;
    }
1
2
3
4
5
6
7

ok页面:

<body>
    ${stu}
</body>
1
2
3

【List集合】

通常在需要批量提交数据时,将提交的数据绑定到list<pojo>中,比如:批量教师信息修改,在页面输入多个教师信息,将多个教师信息提交到controller方法中,即一次性更新多个教师信息。

实体类里:

public class Student {

    private Integer stuid;
    private String stuname;
    private double stuheight;
    private boolean isbiye;
    private Teacher tea;
    private String[]likes ;
    private List<Teacher> teas;
      //---get/set方法,有参/无参构造,toString()
}  
1
2
3
4
5
6
7
8
9
10
11

处理登录的Controller:

@Controller
public class StudentController {
    @RequestMapping("add.do")
    public ModelAndView addStu(Student stu){
        ModelAndView mv=new ModelAndView();
        mv.addObject("stu",stu);
        mv.setViewName("teashow.do");
        return mv;
    }
}

@Controller
public class TeacherController {
    @RequestMapping("teashow.do")
    public ModelAndView show(){
        ModelAndView mv=new ModelAndView();
        List<Teacher> list=new ArrayList<Teacher>();
        list.add(new Teacher(234,"zhangsan"));
        list.add(new Teacher(345,"lisi"));
        list.add(new Teacher(456,"wagnwu"));
        mv.addObject("list",list);
        mv.setViewName("teashow.jsp");
        return mv;
    }

    @RequestMapping("teaupd.do")
    public String upd(Student stu){
        System.out.println(stu);
        return "teashow.jsp";
    }
}

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

show.jsp页面:

<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

<body>
<form action="teaupd.do" method="post">
    <c:forEach items="${list}" var="tea" varStatus="status">
        教师编号:<input type="text" name="teas[${status.index}].teaid" value="${tea.teaid}"><br/>
        教师姓名:<input type="text" name="teas[${status.index}].teaname" value="${tea.teaname}"><br/>
    </c:forEach>
    <input type="submit" value="批量修改">
</form>
</body>
1
2
3
4
5
6
7
8
9
10
11

【Map集合】

Map的绑定其实和List的绑定是差不多的,首先也是在包装的pojo中新添加一个Map类型的属性

实体类:

public class Student {

    private Integer stuid;
    private String stuname;
    private double stuheight;
    private boolean isbiye;
    private Teacher tea;
    private String[]likes ;
    private List<Teacher> teas;
    private Map<Integer,Teacher> maps;
//---get/set方法,有参/无参构造,toString()
}  
1
2
3
4
5
6
7
8
9
10
11
12

控制器:

@Controller
public class StudentController {

    @RequestMapping("add.do")
    public ModelAndView addStu(Student stu){
        ModelAndView mv=new ModelAndView();
        mv.addObject("stu",stu);
        mv.setViewName("teashow.do");
        return mv;
    }
}

@Controller
public class TeacherController {


   /* @RequestMapping("teashow.do")
    public ModelAndView show(){
        ModelAndView mv=new ModelAndView();
        List<Teacher> list=new ArrayList<Teacher>();
        list.add(new Teacher(234,"zhangsan"));
        list.add(new Teacher(345,"lisi"));
        list.add(new Teacher(456,"wagnwu"));
        mv.addObject("list",list);
        mv.setViewName("teashow.jsp");
        return mv;
    }*/

    @RequestMapping("teashow.do")
    public ModelAndView show(){
        ModelAndView mv=new ModelAndView();
        Map<String,Teacher> maps=new HashMap<String,Teacher>();
        Teacher tea1=new Teacher(234,"zhangsan");
        Teacher tea2=new Teacher(345,"lisi");
        Teacher tea3=new Teacher(456,"wagnwu");

        maps.put(tea1.getTeaid().toString(),tea1);
        maps.put(tea2.getTeaid().toString(),tea2);
        maps.put(tea3.getTeaid().toString(),tea3);
        mv.addObject("maps",maps);
        mv.setViewName("teashowmap.jsp");
        return mv;
    }


    @RequestMapping("teaupd.do")
    public String upd(Student stu){
        System.out.println(stu);
        return "teashow.jsp";
    }
}
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

关键是前台传参的时候和List不太一样,Map是这样传的

jsp页面:

<body>
<form action="teaupd.do" method="post">
    <c:forEach items="${maps}" var="tea" >
        教师编号:<input type="text" name="maps[${tea.value.teaid}].teaid" value="${tea.value.teaid}"><br/>
        教师姓名:<input type="text" name="maps[${tea.value.teaid}].teaname" value="${tea.value.teaname}"><br/>
    </c:forEach>
    <input type="submit" value="批量修改">

</form>
</body>
1
2
3
4
5
6
7
8
9
10

我们可以看到,Map的参数绑定传来的是Map中的key,然后value会自动绑定到Map中的那个对象的属性中。在controller中的方法里,形参就直接使用Student接收即可,也很简单。

# 8.2.2.5自定义类型绑定

自定义类型转换器的使用步骤:

字符串没办法--直接通过构造方法转换为时间类型。所以需要手动创建类型转换器

第一步:创建一个类型转换器

public class MyDateConverter implements Converter<String, Date> {///把 S---转成T

	@Override
	public Date convert(String str) {
		
		Date dt=null;
		SimpleDateFormat sdf=new SimpleDateFormat("yyyy-MM-dd");
		try {
			dt=sdf.parse(str);
		} catch (ParseException e) {
		
			e.printStackTrace();
		}
		
		return dt;
	}  
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

第二步:在核心配置文件里配置类型转换器:

    <!-- 配置 处理器映射器  和 处理器适配器 .....器 -->
    <mvc:annotation-driven conversion-service="formatc"/>
    
    <!-- 配置 类型转换器 -->
    <bean id="formatc" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
       <property name="converters">
          <list>
             <bean class="com.msb.util.MyDateConverter"/>
          </list>
       </property>
    </bean>
1
2
3
4
5
6
7
8
9
10
11

# 8.2.2.6解决:请求参数乱码问题

SpringMVC框架已经为我们准备好了过滤器,我们只需要进行配置就可以。

<!-- 配置过滤器:用来设置字符编码,防止乱码! -->
<filter>
   <filter-name>charset</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>
   <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>charset</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

相当于servlet中的:

request.setCharacterEncoding("UTF-8");
response.setCharacterEncoding("UTF-8");
1
2

# 9.SpringMVC使用拦截器

1.拦截器和 过滤器的区别和联系:

联系:都是在进入目标代码前,提前做一些其他的事情。

区别:过滤器:----依赖于Servlet,在web.xml中进行配置

​ ----函数回调实现的。

​ 拦截器: ----依赖于MVC框架,在ApplicationContext.xml中进行配置

​ ----本质拦截器是反射实现的。

​ -----过滤器能做的活,拦截器都能完成。----使用拦截器比较多。

执行顺序: 过滤器 拦截器 控制器

2.使用拦截器的步骤:

# 第一步:自定义拦截器类型

​ 实现拦截器接口HandlerInterceptor

# 第二步:重写3个方法

public class MYHandler implements HandlerInterceptor {

@Override
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {
		System.out.println("执行完控制器的方法后,执行的拦截器方法。。。。");
	
}
	
@Override
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		
		System.out.println("请求已经进入到控制器了,但是还没有执行完控制器的时候,回到拦截器里来,执行该方法。");
}
	
@Override
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
	
		System.out.println("进入控制器方法前,要执行的拦截器方法。。。。。");
		//返回值:返回值为true----说明,符合通过条件,可以进行进入到控制器里。
		//      返回值为 false----说明:不符合通过条件,拦截此次请求。  不在继续进入控制器。     
		return false;
}
}
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

# 第三步:配置拦截器

  <!-- 配置拦截器 -->
  <mvc:interceptors>
  	<mvc:interceptor>
  	  <mvc:mapping path="/**"/>  <!-- /表示项目根目录;** 项目下任意路径以及任意子路径; 拦截所有请求路径 -->
 	  <mvc:exclude-mapping path="/index.do"/>   <!-- 放行请求路径 -->
 	  <mvc:exclude-mapping path="/reg.do"/>
 	  <mvc:exclude-mapping path="/login.do"/>
  	  <bean class="com.msb.handler.MYHandler"></bean>
  	</mvc:interceptor>
  </mvc:interceptors>
1
2
3
4
5
6
7
8
9
10

# 10.SpringMVC使用文件上传

实现步骤:

# A.创建Maven web项目

1.New Project  点击Maven 先勾选Create from archetype 选择org.apache.maven.archetypes:maven-archetype-webapp
2.设置项目名称
3.创建完成后,手动添加resources和java目录
1
2
3

# B.添加依赖

  <dependencies>
    <!--进行junit单元测试 -->
    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>

	<!--Spring的5大核心jar包 -->
    <!--依赖于commons-logging日志管理 -->
    <dependency>
      <groupId>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>

    <!--提供了框架的基本组成部分,包括IOC 和 DI-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!-- 提供了BeanFactory-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!--上下文配置对象,提供一个框架式的对象访问方式-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!--提供了强大的表达式语言-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>

    <!--springMVC的jar包-->
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>
    
    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-webmvc</artifactId>
      <version>4.1.6.RELEASE</version>
    </dependency>
    
    <!--java web依赖 -->
    <dependency>
      <groupId>javax.servlet</groupId>
      <artifactId>servlet-api</artifactId>
      <version>2.3</version>
    </dependency>

    <dependency>
      <groupId>javax.servlet.jsp</groupId>
      <artifactId>jsp-api</artifactId>
      <version>2.2</version>
    </dependency>

    <!-- jstl表达式 -->
    <dependency>
      <groupId>jstl</groupId>
      <artifactId>jstl</artifactId>
      <version>1.2</version>
    </dependency>
    
    <dependency>
      <groupId>taglibs</groupId>
      <artifactId>standard</artifactId>
      <version>1.1.2</version>
    </dependency>

	<!--添加用于上传的jar包依赖 -->
    <dependency>
      <groupId>commons-fileupload</groupId>
      <artifactId>commons-fileupload</artifactId>
      <version>1.2.2</version>
    </dependency>
    
    <dependency>
      <groupId>commons-io</groupId>
      <artifactId>commons-io</artifactId>
      <version>2.4</version>
    </dependency>

  </dependencies>
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98

# C.准备Spring核心配置文件

    <!--配置上传文件解析器 5242880=1024*1024*5  ;不写乘法表达式的原因是:配置文件中*有特殊意义。-->
<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <property name="maxUploadSize" value="5242880"/>

</bean>

    <!--配置放行静态资源 -->
    <!-- 如果没有配置mvc:resources去寻找@requestmappingg -->
    <!-- 静态资源放行  mapping:指的是网络中URL地址  location:放行本地的什么位置的资源-->
    <mvc:resources location="/imgs/" mapping="/imgs/**"></mvc:resources>

</beans>
1
2
3
4
5
6
7
8
9
10
11
12

# D.准备上传页面

	<body>
	<form action="upload.do" method="post" enctype="multipart/form-data">
	
	    上传人姓名:<input type="text" name="uploadname"/><br/>
	    上传文件:<input type="file" name="upfile"><img src="${url}"/><br/>${url}
	    <input type="submit" value="上传文件">
	
	</form>
	</body>
1
2
3
4
5
6
7
8
9

# E.编写控制器

	@Controller
	public class UpLoadController {
	
	    @RequestMapping("upload.do")
	    public ModelAndView upload(String uploadname, HttpServletRequest request, MultipartFile upfile) throws IOException {
	
	        ModelAndView mv=new ModelAndView();
	        //1.获得文件名:
	        String filename=upfile.getOriginalFilename();
	
	        //2.获得上传的路径:
	        String url=request.getSession().getServletContext().getRealPath("/imgs/"); //要求imgs里要存有其他图片
	        File file=new File(url+filename);
	        System.out.println(url+filename);
	        upfile.transferTo(file);
	
	        mv.addObject("url","imgs/"+filename);
	        mv.setViewName("fileupload.jsp");
	        return mv;
	    }
	}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21

# 11.SpringMVC使用文件下载

# 11.1获得所有可下载的文件列表

@RequestMapping("getDownList.do")
    public String getDownList(HttpServletRequest request){
        String url=request.getSession().getServletContext().getRealPath("/upload");
        File file=new File(url);
        File[] tempList = file.listFiles();
        List<String> list=new ArrayList<String>();
        for(int i=0;i<tempList.length;i++){
            list.add(tempList[i].getName());
        }
        request.setAttribute("list",list);
        return "fileList.jsp";
    }
1
2
3
4
5
6
7
8
9
10
11
12

# 11.2编写下载的jsp页面

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<c:forEach items="${list}" var="s">

    <a href="down.do?name=${s}">${s}</a>
</c:forEach>
</body>
</html>

1
2
3
4
5
6
7
8
9
10
11
12
13
14

# 11.3下载指定文件

    @RequestMapping("down.do")
    public void down(String name, HttpServletResponse response, HttpServletRequest request) throws IOException {
        System.out.println("进入down.do里。。。。");

        String realPath = request.getSession().getServletContext().getRealPath("/upload");//获取下载文件的路径
        File file = new File(realPath, name);//把下载文件构成一个文件处理   filename:前台传过来的文件名称

        //设置响应类型  ==》 告诉浏览器当前是下载操作,我要下载东西
        response.setContentType("application/x-msdownload");
        //设置下载时文件的显示类型(即文件名称-后缀)   ex:txt为文本类型
        response.setHeader("Content-Disposition", "attachment;filename=" + name);

        //下载文件:将一个路径下的文件数据转到一个输出流中,也就是把服务器文件通过流写(复制)到浏览器端
        Files.copy(file.toPath(), response.getOutputStream());//Files.copy(要下载的文件的路径,响应的输出流)
    }
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15

# 12.SpringMVC使用Ajax

# 12.1返回JSON字符串

例子:进入jsp页面输入用户名后,光标离开 触发ajax异步请求,controller里根据获得的用户名进行判断,从而返回不同的结果!

A.添加 jquery-1.8.3.jswebapp/js文件夹下

B.编写jsp页面

<script type="text/javascript"  src="js/jquery-1.8.3.js"></script>
<script type="text/javascript">
        function fcheck(){
            var uname=$("#uname").val();
            $.ajax({
                url:"check.do",
                contentType:'application/json', //设置请求参数以Json格式传递到Controller里
                type:"post",
                data:{"uname":uname},
                success:function (info){
                    $("#msg").html(info);
                }
            });
        }
 </script>
    
    

<body>
<form action="regajax.do" method="post">
    用户名:<input type="text" name="uname" id="uname" autofocus onblur="fcheck()"/><span id="msg"></span><br/>
    密码:<input type="password" name="pwd" id="pwd" ><br/>
    <input type="submit" value="提交"/>
</form>
</body>
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

C.编写Controller方法

@Controller
public class AjaxController {

    @RequestMapping(value={"check.do"},produces = "text/html;charset=utf-8")
    public @ResponseBody String check(String uname){
        if("admin".equals(uname)){
            return "用户名已存在!no";
        }else{
            return "用户名可以使用!yes";
        }
    }
}
1
2
3
4
5
6
7
8
9
10
11
12

D.配置applicationContext.xml文件

<!--配置放行静态资源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
1
2

# 12.2返回JSON集合

例子:页面加载后,触发ajax异步请求,controller里设置返回模拟集合数据,返回到前台页面使用js代码进行展示!

A.添加 jquery-1.8.3.jswebapp/js文件夹下

B.添加jar依赖

    <!--依赖gson-2.1.jar -->
   <dependency>
      <groupId>com.google.code.gson</groupId>
      <artifactId>gson</artifactId>
      <version>2.1</version>
    </dependency>
1
2
3
4
5
6

C.编写jsp页面

    <script type="text/javascript"  src="js/jquery-1.8.3.js"></script>
    <script type="text/javascript" >
        $(function (){
            $.ajax({
                url:"find.do",
                context:"application/json;charset=utf-8",
                type:"post",
                success:function(info){
                    eval("var list="+info);
                    for(var i in list){
                        var createobj = $("<div class='abc'>"+list[i].teaname+"</div>");
                        $("body").append(createobj);
                    }
                }
            });
        });

    </script>

<body>

</body>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

D.编写Controller方法

    @RequestMapping("find.do")
    public @ResponseBody String find(HttpServletResponse response){
        response.setContentType("application/json;charset=utf-8");
        List<Teacher> list=new ArrayList<Teacher>();
        list.add(new Teacher(234,"zhangsan"));
        list.add(new Teacher(345,"lisi"));
        list.add(new Teacher(456,"wagnwu"));

        String str=new Gson().toJson(list);
        System.out.println(str);
        return str;

    }
1
2
3
4
5
6
7
8
9
10
11
12
13

E.配置applicationContext.xml文件

<!--配置放行静态资源 -->
<mvc:resources location="/js/" mapping="/js/**"></mvc:resources>
1
2

# 13.SSM框架整合

实现步骤:

# 1.创建maven web项目

1.New Project  点击Maven 先勾选Create from archetype 选择org.apache.maven.archetypes:maven-archetype-webapp
2.设置项目名称
3.创建完成后,手动添加resources和java目录
1
2
3

# 2.添加依赖

 <properties>
	<org.springframework.version>4.0.3.RELEASE</org.springframework.version>
  </properties>
  <dependencies>
	<dependency>
		<groupId>junit</groupId>
		<artifactId>junit</artifactId>
		<version>3.8.1</version>
		<scope>test</scope>
	</dependency>
	 
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-aop</artifactId>
		<version>${org.springframework.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-beans</artifactId>
		<version>${org.springframework.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-context</artifactId>
		<version>${org.springframework.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-core</artifactId>
		<version>${org.springframework.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-web</artifactId>
		<version>${org.springframework.version}</version>
	</dependency>
	<dependency>
		<groupId>org.springframework</groupId>
		<artifactId>spring-webmvc</artifactId>
		<version>${org.springframework.version}</version>
	</dependency>
    
    <!-- spring校验 start -->
		<dependency>
			<groupId>org.hibernate</groupId>
			<artifactId>hibernate-validator</artifactId>
			<version>4.3.0.Final</version>
		</dependency>
		<dependency>
			<groupId>javax.validation</groupId>
		    <artifactId>validation-api</artifactId>
		    <version>1.0.0.GA</version>
		</dependency>
		<dependency>
			<groupId>org.jboss.logging</groupId>
		    <artifactId>jboss-logging</artifactId>
		    <version>3.1.0.CR2</version>
		</dependency>
		<!-- spring校验 end -->
		
		<!-- jstl标签库 start -->
		<dependency>
			<groupId>jstl</groupId>
			<artifactId>jstl</artifactId>
			<version>1.2</version>
		</dependency>
		<dependency>
			<groupId>taglibs</groupId>
			<artifactId>standard</artifactId>
			<version>1.1.2</version>
		</dependency>
		<!-- jstl标签库 end -->
		<!-- 文件上传 start -->
		<dependency>
			<groupId>commons-fileupload</groupId>
			<artifactId>commons-fileupload</artifactId>
			<version>1.2.2</version>
		</dependency>
		<dependency>
			<groupId>commons-io</groupId>
			<artifactId>commons-io</artifactId>
			<version>2.4</version>
		</dependency>
		<!-- 文件上传 end -->
		<!-- json数据交互 start -->
		<dependency>
		    <groupId>org.codehaus.jackson</groupId>
		    <artifactId>jackson-core-asl</artifactId>
		    <version>1.9.13</version>
		</dependency>
		<dependency>
		    <groupId>org.codehaus.jackson</groupId>
		    <artifactId>jackson-mapper-asl</artifactId>
		    <version>1.9.13</version>
		</dependency>
		<!-- <dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-databind</artifactId>
			<version>2.7.4</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-core</artifactId>
			<version>2.7.4</version>
		</dependency>
		<dependency>
			<groupId>com.fasterxml.jackson.core</groupId>
			<artifactId>jackson-annotations</artifactId>
			<version>2.7.4</version>
		</dependency> -->
		<!-- json数据交互 end -->
		<dependency>
	      	<groupId>org.mybatis</groupId>
	    	<artifactId>mybatis</artifactId>
	  		<version>3.4.2</version>
	    </dependency>
	
		<dependency>
			<groupId>mysql</groupId>
			<artifactId>mysql-connector-java</artifactId>
			<version>5.1.36</version>
		</dependency>
	
		<dependency>
			<groupId>org.slf4j</groupId>
			<artifactId>slf4j-log4j12</artifactId>
			<version>1.7.2</version>
		</dependency>
	
		<dependency>
			<groupId>org.mybatis.generator</groupId>
			<artifactId>mybatis-generator-core</artifactId>
			<version>1.3.2</version>
		</dependency>
	
		<dependency>
			<groupId>org.mybatis.caches</groupId>
			<artifactId>mybatis-ehcache</artifactId>
			<version>1.0.2</version>
		</dependency>
		<dependency>
			<groupId>net.sf.ehcache</groupId>
			<artifactId>ehcache</artifactId>
			<version>2.10.1</version>
		</dependency>
		
		<!--mybatis-spring整合包,这样就可以通过spring配置bean的方式进行mybatis配置了,
        不然需要单独使用mybatis的配置-->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.0</version>
        </dependency>
        <!-- 导入dbcp的jar包,用来在spring-mybatis.xml中配置数据库 -->
        <dependency>
            <groupId>commons-dbcp</groupId>
            <artifactId>commons-dbcp</artifactId>
            <version>1.4</version>
        </dependency>
        <!--对Spring 对JDBC 数据访问进行封装的所有类-->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>4.1.6.RELEASE</version>
        </dependency>

		<!-- spring切面使用(事务)需要的包 -->
		<dependency>
			<groupId>aspectj</groupId>
			<artifactId>aspectjweaver</artifactId>
			<version>1.5.4</version>
		</dependency>
  </dependencies>
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
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173

# 3.创建jdbc.properties

mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://127.0.0.1:3306/test
mysql.username=root
mysql.password=root
1
2
3
4

# 4.引入log4j.properties

将log4j.properties 放到项目的resources文件夹下!

# 5.创建SqlMapConfig.xml

改变:A.数据库环境不在mybatis里进行配置,改为在Spring的配置文件里。 B. Mapper 映射文件也不在 mybatis里进行配置,改为在Spring的配置文件里。

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE configuration
        PUBLIC "-//mybatis.org//DTD Config 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-config.dtd">

<configuration>
    <!-- 设置类的别名 -->
    <typeAliases>
        <package name="com.msb.pojo"/>
    </typeAliases>

</configuration>

# 6.创建ApplicationContext.xml

<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: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.xsd
       http://www.springframework.org/schema/context
       http://www.springframework.org/schema/context/spring-context.xsd
       http://www.springframework.org/schema/aop
       http://www.springframework.org/schema/aop/spring-aop.xsd
       http://www.springframework.org/schema/tx
       http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- 加载jdbc的属性文件: -->
    <context:property-placeholder location="classpath:jdbc.properties"/>

    <!-- 配置数据源 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource">
        <property name="driverClassName" value="${mysql.driver}"/>
        <property name="url" value="${mysql.url}"/>
        <property name="username" value="${mysql.username}"/>
        <property name="password" value="${mysql.password}"/>
        <property name="maxActive" value="30"/>
        <property name="maxIdle" value="3"/>  <!-- 闲置的连接对象个数! -->
    </bean>

    <!--配置 mybatis框架里的sqlSessionFactory  -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <property name="dataSource" ref="dataSource"/>
        <property name="configLocation" value="classpath:SqlMapConfig.xml"/>
    </bean>

    <!--加载Mapper映射文件:  -->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="com.msb.mapper"/>
        <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/>
    </bean>



    <!-- 配置事务管理器 -->
    <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="add*" propagation="REQUIRED"/>
            <tx:method name="remove*" propagation="REQUIRED"/>
            <tx:method name="update*" propagation="REQUIRED"/>
            <tx:method name="find*" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>

    <!--配置 :整合事务和切入点  -->
    <aop:config>
        <aop:pointcut expression="execution(* com.msb.service.impl.EmpServiceImpl.*(..))" id="txpointcut"/>
        <aop:advisor advice-ref="txadvice" pointcut-ref="txpointcut"/>
    </aop:config>
</beans>
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

# 7.使用逆向工程创建实体类,Mapper接口和映射文件

​ 实现例子: 【查询所有员工的所有信息!(信息里包括部门的信息)】

# 7.1修改Emp实体类:

@Conpont
Emp实体类添加private Dept dept; 并进行get/set方法
public class Emp {
    private Integer empno;

    private String ename;

    private String job;

    private Integer mgr;

    private Date hiredate;

    private Double sal;

    private Double comm;

  /*  private Integer deptno;*/

    private Dept dept;
===get/set
}


public class Dept {
    private Integer deptno;

    private String dname;

    private String loc;
===get/set
}
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

# 7.2EmpMapper 接口添加方法:

public interface EmpMapper {
	public List<Emp> selectAllEmpAndDept();
}
1
2
3

# 7.3编写EmpMapper映射文件:

<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.msb.mapper.EmpMapper">

  <resultMap type="emp" id="empAndDept">
    <id column="empno" property="empno"/>
    <result column="ename" property="ename"/>
    <result column="job" property="job"/>
    <result column="mgr" property="mgr"/>
    <result column="hiredate" property="hiredate"/>
    <result column="sal" property="sal"/>
    <result column="comm" property="comm"/>
    <result column="deptno" property="deptno"/>
    <association property="dept" javaType="dept">
      <id column="deptno" property="deptno"/>
      <result column="dname" property="dname"/>
      <result column="loc" property="loc"/>
    </association>
  </resultMap>

  <select id="selectAllEmpAndDept" resultMap="empAndDept" >
     select e.*,d.*
     from emp e inner join dept d
                on e.deptno=d.deptno
  </select>
</mapper>
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

# 7.4编写EmpService 接口添加方法:

public interface EmpService {
	public List<Emp> findAll();
}
1
2
3

# 7.5编写EmpService 接口实现类:

@Service("empService")
public class EmpServiceImpl implements EmpService {

    @Autowired
    EmpMapper empMapper;
    public List<Emp> findAll(){
        return empMapper.selectAllEmpAndDept();
    }
}
1
2
3
4
5
6
7
8
9

# 8.创建Springmvc.xml

<?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: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:annotation-config/>-->
    <!-- 启动扫描组件器 -->
    <context:component-scan base-package="com.msb"/>

    <!-- 配置处理器映射器和处理器适配器 -->
    <mvc:annotation-driven/>

    <!-- 配置视图解析器 -->
<!--    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>-->
</beans>
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

# 9.配置web.xml

 <!DOCTYPE web-app PUBLIC
 "-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
 "http://java.sun.com/dtd/web-app_2_3.dtd" >

<web-app>
  <display-name>Archetype Created Web Application</display-name>
  <welcome-file-list>
    <welcome-file>index.jsp</welcome-file>
  </welcome-file-list>
  <!-- 1.配置前端控制器 -->
  <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:Springmvc.xml</param-value>
    </init-param>
  </servlet>
  <servlet-mapping>
    <servlet-name>springmvc</servlet-name>
    <url-pattern>*.do</url-pattern>
  </servlet-mapping>

  <!-- 2.配置:防止乱码的过滤器 -->
  <filter>
    <filter-name>charset</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>
    <init-param>
      <param-name>forceEncoding</param-name>
      <param-value>true</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>charset</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

  <!-- 3.加载Spring核心配置文件 (希望项目启动的时候,立刻加载ApplicationContext-*.xml配置文件,在Application应用对象的初始化参数里加载)-->
  <context-param>
    <param-name>contextConfigLocation</param-name>
    <param-value>classpath:applicationContext-dao.xml</param-value>
  </context-param>


  <!-- 4,配置监听器,监听bean对象的创建 -->
  <listener>
    <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
  </listener>
</web-app>
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

# 10.编写Controller 控制器:

@Controller
public class EmpController {
    @Autowired
    private EmpService empService;

    public EmpService getEmpService() {
        return empService;
    }
    public void setEmpService(EmpService empService) {
        this.empService = empService;
    }

    @RequestMapping("show.do")
    public ModelAndView show(){
        System.out.println("进入show.do里");
        ModelAndView mv=new ModelAndView();
        List<Emp> list=empService.findAll();
        mv.addObject("list", list);
        mv.setViewName("/jsp/show.jsp");
        return mv;
    }
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22

# 11.编写index.jsp页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <a href="show.do">查询全部信息</a>
</body>
</html>
1
2
3
4
5
6
7
8
9

# 12.编写show.jsp页面:

<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
<c:forEach items="${list}" var="e">
    ${e.empno}
    ${e.ename}
    ${e.job}
    ${e.hiredate}
    ${e.dept.deptno}
    ${e.dept.dname}
    ${e.dept.loc}<br/>
</c:forEach>
</body>
</html>
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18