SpringMVC重点内容

1.什么是SpringMVC

它是基于MVC开发模式的框架,用来优化控制器.它是Spring家族的一员.它也具备IOC和AOP.

什么是MVC?
它是一种开发模式,它是模型视图控制器的简称.所有的web应用都是基于MVC开发.
M:模型层,包含实体类,业务逻辑层,数据访问层
V:视图层,html,javaScript,vue等都是视图层,用来显现数据
C:控制器,它是用来接收客户端的请求,并返回响应到客户端的组件,Servlet就是组件

2.SpringMVC框架的优点

1)轻量级,基于MVC的框架
2)易于上手,容易理解,功能强大
3)它具备IOC和AOP
4)完全基于注解开发

3.基于注解的SpringMVC框架开发的步骤

1)新建项目,选择webapp模板.
2)修改目录,添加缺失的test,java,resources(两套),并修改目录属性
3)修改pom.xml文件,添加SpringMVC的依赖,添加Servlet的依赖

<dependency>
  <groupId>org.springframework</groupId>
  <artifactId>spring-webmvc</artifactId>
  <version>5.2.5.RELEASE</version>
</dependency>
<!--添加servlet的依赖-->
<dependency>
  <groupId>javax.servlet</groupId>
  <artifactId>javax.servlet-api</artifactId>
  <version>3.1.0</version>
</dependency>

4)添加springmvc.xml配置文件,指定包扫描,添加视图解析器.

  <!--添加包扫描-->
    <context:component-scan base-package="com.bjpowernode.controller"></context:component-scan>
    <!--添加视图解析器-->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--配置前缀-->
        <property name="prefix" value="/admin/"></property>
        <!--配置后缀-->
        <property name="suffix" value=".jsp"></property>
    </bean>

5)删除web.xml文件,新建web.xml
6)在web.xml文件中注册springMVC框架(所有的web请求都是基于servlet的)

  <!--注册SpringMVC框架-->
    <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>
        <!--
          指定拦截什么样的请求
          http://localhost:8080/one
          http://localhost:8080/index.jsp
          http://localhost:8080/demo.action
          <a href="${pageContext.request.contextPath}/demo.action">访问服务器</a>
        -->
        <url-pattern>*.action</url-pattern>
    </servlet-mapping>

7)在webapp目录下新建admin目录,在admin目录下新建main.jsp页面,删除index.jsp页面,并新建,发送请求给服务器
8)开发控制器(Servlet),它是一个普通的类.

  @Controller  //交给Spring去创建对象
	public class DemoAction {
	    /**
	     * 以前的Servlet的规范如下,现在都可以自己命名等,加注解就好!
	     * protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {}
	     * action中所有的功能实现都是由方法来完成的
	     * action方法的规范
	     * 1)访问权限是public
	     * 2)方法的返回值任意
	     * 3)方法名称任意
	     * 4)方法可以没有参数,如果有可是任意类型
	     * 5)要使用@RequestMapping注解来声明一个访问的路径(名称)
	     *
	     */
	    @RequestMapping("/demo")
	    public String demo(){
	    	//写一步测试一步
	        System.out.println("服务器被访问到了.......");
	        
	        return "main";  //可以直接跳到/admin/main.jsp页面上
	    }
	}

9)添加tomcat进行测试功能

4.分析web请求

web请求执行的流程
核心处理器
index.jsp<--------------->DispatcherServlet<------------------->SpringMVC的处理器是一个普通的方法
one.jsp <--------------->DispatcherServlet<------------------->SpringMVC的处理器是一个普通的方法

DispatcherServlet要在web.xml文件中注册才可用.

为什么地址栏输入对应的地址就能够在controller层中被映射到方法上进行处理呢?
-----实际上是通过DispatcherServlet核心处理器进行调度的!它拿着浏览器那边的请求消息,和控制层中@RequestMapping中的信息进行匹配,匹配成功就调用对应的方法。

5.@RequestMapping注解详解

此注解就是来映射服务器访问的路径.
1)此注解可加在方法上,是为此方法注册一个可以访问的名称(路径)

  @RequestMapping("/demo")
    public String demo(){
        System.out.println("服务器被访问到了.......");
        return "main";  //可以直接跳到/admin/main.jsp页面上
    }
  <a href="${pageContext.request.contextPath}/demo.action">访问服务器</a>

2)此注解可以加在类上,相当于是包名(虚拟路径),区分不同类中相同的action的名称

  @RequestMapping("/user")
  public class DemoAction1 {..}
  <a href="${pageContext.request.contextPath}/user/demo.action">访问服务器</a>

3)此注解可区分get请求和post请求

@Controller
	public class ReqAction {
	    @RequestMapping(value = "/req",method = RequestMethod.GET)
	    public String req(){
	        System.out.println("我是处理get请求的........");
	        return "main";
	    }
	    @RequestMapping(value = "/req" ,method = RequestMethod.POST)
	    public String req1(){
	        System.out.println("我是处理post请求的........");
	        return "main";
	    }
	}

6.五种数据提交方式的优化

大多数数据提交给服务器后,都是直接在action类中对应方法,通过形式参数中来拿到的。
(但是日期类不行!需要加注解,将字符串转换为日期)
拿前端提交的数据后端拿到后,如何再发给前端其他界面呢?(详情看15节)
1)HttpServletRequest
2)HttpServletResponse (不传送数据)
3)HttpSession(如果使用的是重定向,相当于挂断了电话,最后只有它有值,其他都取不到数据)
4)Model
5)Map
6)ModelMap

1)单个提交数据
如果前端提交的是同名的数据,比如chexbox,name=hobby,value有多个不同的值,那提交过去,在controller方法里面:
可以使用String类型接住,输出的多个不同value自动使用","隔开。
如果使用String[] 的形参来接,那就会自动类型转换为String数组。

  <form action="${pageContext.request.contextPath}/one.action">
      姓名:<input name="myname"><br>
      年龄:<input name="age"><br>
      <input type="submit" value="提交">
  </form>
  action:
  @RequestMapping("/one")
    public String one(String myname,int age){  ===>自动注入,并且类型转换
        System.out.println("myname="+myname+",age="+(age+100));
        return "main";
    }
   

2)对象封装提交数据
在提交请求中,保证请求参数的名称与实体类中成员变量的名称一致,则可以自动创建对象,则可以自动提交数据,自动类型转换,自动封装数据到对象中.
实体类:

public class Users {
private String name;
private int age;}
页面:
<form action="${pageContext.request.contextPath}/two.action" method="post">
    姓名:<input name="name"><br>
    年龄:<input name="age"><br>
    <input type="submit" value="提交">
</form>
action:
@RequestMapping("/two")
public String two(Users u){
    System.out.println(u);
    return "main";
}

3)动态占位符提交
SpringMVC路径中的占位符常用于RESTful风格中,当请求路径中将某些数据通过路径的方式传输到服务器中,就可以在相应的@RequestMapping注解的value属性中通过占位符{xxx}表示传输的数据,在
通过@PathVariable注解,将占位符所表示的数据赋值给控制器方法的形参

简单的来说:仅限于超链接或地址拦提交数据.它是一杠一值,一杠一大括号,使用注解@PathVariable来解析.

<a href="${pageContext.request.contextPath}/three/张三/22.action">动态提交</a> @RequestMapping("/three/{uname}/{uage}") 
public String three(
        @PathVariable("uname")  ===>用来解析路径中的请求参数
        String name,
        @PathVariable("uage")
        int age){
    System.out.println("name="+name+",age="+(age+100));
    return "main"; }

4)映射名称不一致
提交请求参数与action方法的形参的名称不一致,使用注解@RequestParam来解析

 /**
     *  姓名:<input name="name"><br>
     *  年龄:<input name="age"><br>
     */
    @RequestMapping("/four")
    public String four(
            @RequestParam("name")  ===>专门用来解决名称不一致的问题
            String uname, //形参uname,请求参数 name不一致
            @RequestParam("age")
            int uage){
        System.out.println("uname="+uname+",uage="+(uage+100));
        return "main";
    }

5)手工提取数据
(SpringMVC已经封装好了对应的Servlet原生API,所以还是多使用SpringMVC的好,比如使用之前的形参)

  /**
     *  姓名:<input name="name"><br>
     *  年龄:<input name="age"><br>
     */
  @RequestMapping("/five")
    public String five(HttpServletRequest request){
        String name = request.getParameter("name");
        //request.getParameterValues()用于获取多个同名的value,组合为一个字符串,比如复选框name=hobby有多个value值
        int age = Integer.parseInt(request.getParameter("age"));
        System.out.println("name="+name+",age="+(age+100));
        return "main";
    }

7.域对象共享数据

7.1、使用ServletAPI向request域对象共享数据
7.2、使用ModelAndView向request域对象共享数据
7.3、使用Model向request域对象共享数据
7.4、使用map向request域对象共享数据
5.5、使用ModelMap向request域对象共享数据
5.6、Model、ModelMap、Map的关系
Model、ModelMap、Map类型的参数其实本质上都是 BindingAwareModelMap 类型的
5.7、向session域共享数据
5.8、向application域共享数据
6、SpringMVC的视图
SpringMVC中的视图是View接口,视图的作用渲染数据,将模型Model中的数据展示给用户
@RequestMapping(“/testModel”)
public String testModel(Model model){
model.addAttribute(“testScope”, “hello,Model”);
return “success”;
} @
RequestMapping(“/testMap”)
public String testMap(Map<String, Object> map){
map.put(“testScope”, “hello,Map”);
return “success”;
} @
RequestMapping(“/testModelMap”)
public String testModelMap(ModelMap modelMap){
modelMap.addAttribute(“testScope”, “hello,ModelMap”);
return “success”;
} p
ublic interface Model{}
public class ModelMap extends LinkedHashMap<String, Object> {}
public class ExtendedModelMap extends ModelMap implements Model {}
public class BindingAwareModelMap extends ExtendedModelMap {}
@RequestMapping(“/testSession”)
public String testSession(HttpSession session){
session.setAttribute(“testSessionScope”, “hello,session”);
return “success”;
} @
RequestMapping(“/testApplication”)
public String testApplication(HttpSession session){
ServletContext application = session.getServletContext();
application.setAttribute(“testApplicationScope”, “hello,application”);
return “success”;
}

中文乱码解决方案

  配置过滤器.
  <filter>
        <filter-name>encode</filter-name>
        <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
        <!--
          配置参数
            private String encoding;
            private boolean forceRequestEncoding;
            private boolean forceResponseEncoding;
        -->
        <init-param>
            <param-name>encoding</param-name>
            <param-value>UTF-8</param-value>
        </init-param>
        <init-param>
            <param-name>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encode</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

8.action方法的返回值

1)String:客户端资源的地址,自动拼接前缀和后缀.还可以屏蔽自动拼接字符串,可以指定返回的路径.
2)Object:返回json格式的对象.自动将对象或集合转为json.使用的jackson工具进行转换,必须要添加jackson依赖.一般用于ajax请求.
3)void:无返回值,一般用于ajax请求.
4)基本数据类型,用于ajax请求.
5)ModelAndView:返回数据和视图对象,现在用的很少.

9.完成ajax请求访问服务器,返回学生集合.

1)添加jackson依赖(pom文件中添加)

  <dependency>
      <groupId>com.fasterxml.jackson.core</groupId>
      <artifactId>jackson-databind</artifactId>
      <version>2.9.8</version>
    </dependency>

2)在webapp目录下新建js目录,添加jQuery函数库
3)在index.jsp页面上导入函数库

	<%--导入函数库--%>
    <script src="js/jquery-3.3.1.js"></script>

以下就是ajax+jquery的写法

  <%--
  Created by IntelliJ IDEA.
  User: PC
  Date: 2022/10/2
  Time: 15:47
  To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
    <%--导入函数库--%>
    <script src="js/jquery-3.3.1.js"></script>
    <script type="text/javascript">
         $(function () {//相当于window.onload
             $("#btn").click(function (){
                 show();
             })
         })

         function getData(list) {
             var s = "";
             $.each(list,function (i,stu){
                 s += stu.name + " | " + stu.age + "<br>";
             });
             //类似innerHtml
             $("#div").html(s);
         }

         function show(){
             //{里面是参数}  ${pageContext.request.contextPath}是获取项目发布出去的公路径
             //.action的尾巴能够被好汉dispatcherServlet处理
             $.ajax({
                 url:"${pageContext.request.contextPath}/ajax.action",
                 dataType:"json",
                 type:"get",
                 success:function (list){
                     //要把list传给这个函数,否则报错
                     getData(list);
                 }
             })
         }
    </script>
</head>
<body>
    <h2>SpringMVC下的ajax/jQuery请求(使用json)</h2><br><br><br>
    <input type="button" value="获取数据" id="btn"><br><br>
    <div id="div">加载数据...</div>
</body>
</html>


4)在action上添加注解@ResponseBody,用来处理ajax请求

@Controller
public class AjaxAction {
    //处理ajax请求,一定要加@ResponseBody
    @ResponseBody //@ResponseBody的作用其实是将java对象转为json格式的数据。
    @RequestMapping("/ajax")
    public List<Student> ajax(){
        Student stu1 = new Student("张三",22);
        Student stu2 = new Student("李四",24);
        Student stu3 = new Student("王五",23);
       List<Student> list = new ArrayList<>();
       list.add(stu1);
       list.add(stu2);
       list.add(stu3);
        //调用json转换工具ObjectMapper进行转换
        return list;  //===>springmvc负责转换成json
    }
}

5)在springmvc.xml文件中添加注解驱动<mvc:annotationdriven/>,它用来解析@ResponseBody注解

 <mvc:annotation-driven></mvc:annotation-driven>

10.四种跳转方式

本质还是两种跳转:请求转发和重定向,衍生出四种是请求转发页面,转发action,重定向页面,重定向action

 @RequestMapping("/one")
    public String one(){
        System.out.println("这是请求转发页面跳转.........");
        return "main";  //默认是请求转发,使用视图解析器拼接前缀后缀进行页面跳转
    }

    @RequestMapping("/two")
    public String two(){
        System.out.println("这是请求转发action跳转.........");
        //  /admin/  /other.action  .jsp
        //forward: 这组字符串可以屏蔽前缀和后缀的拼接.实现请求转发跳转
        return "forward:/other.action";  //默认是请求转发,使用视图解析器拼接前缀后缀进行页面跳转
    }

    @RequestMapping("/three")
    public String three(){
        System.out.println("这是重定向页面.......");
        //redirect:  这组字符串可以屏蔽前缀和后缀的拼接.实现重定向跳转
        return "redirect:/admin/main.jsp";
    }

    @RequestMapping("/four")
    public String four(){
        System.out.println("这是重定向action.......");
        //redirect:  这组字符串可以屏蔽前缀和后缀的拼接.实现重定向跳转
        return "redirect:/other.action";
    }

    @RequestMapping("/five")
    public String five(){
        System.out.println("这是随便跳.......");

        return "forward:/fore/login.jsp";
    }

11.SpringMVC默认的参数类型

传递数据的步骤:

  1. 前端发起请求(可以带参数,也可以不带)比如写个超链接,或者表单等。
  2. 前端对应的url找到controller对应的xxx.action,在action中连接下层数据库的访问,取到数据,再发给指定的sjp
  3. 在接收的前端jsp中,如何获取数据? ajax的请求类型中,返回json 在success:function(resp){} 使用resp取到了数据。如果是普通获取,并打印到显示器,可以用el表达式:${键值对中的key的名字}

不需要去创建,直接拿来使用即可.
1)HttpServletRequest
2)HttpServletResponse (不传送数据)
3)HttpSession(如果使用的是重定向,相当于挂断了电话,最后只有它有值,其他都取不到数据)
4)Model
5)Map
6)ModelMap

//做一个数据,传到main.jsp页面上
@Controller
public class DataAction {
    //六种参数类型
    @RequestMapping("/data")
    public String Data(HttpServletRequest request,
                       HttpServletResponse response, //相应流的数据,不能携带数据
                       HttpSession session,
                       Model model,
                       Map map,
                       ModelMap modelMap
    ){
        System.out.println("用于测试,看到这说明服务器已经成功访问该DataAction");
        User user = new User(22,"张三");
        //把数据传输到前端,之前使用的是ajax,用 pintStream 下的println就行了(没学springmvc)
        // 学完springmvc后直接return就能自动封装为ajax(复习)@ResponseBody的作用其实是将java对象转为json格式的数据。
        request.setAttribute("request",user);
        session.setAttribute("session",user);
        model.addAttribute("model",user);
        modelMap.addAttribute("modelMap",modelMap);

        return "/main";//默认的请求转发方式,自动拼接前后缀。又漏了斜杆
    }
}

前端转发到的页面拿数据:

requestUsers:${request}<br><br>
    这是session:${session};<br><br>
    这是model:${model};<br><br>
    这是modelMap:${modelMap};<br><br>

    <%--
        如何从最初始的页面拿数据,下面是格式
        前端:    <a href="${pageContext.request.contextPath}/data.action?name=zhangsan">访问服务器,进行数据携带跳转</a>
        通过服务器转发到该页面后使用:${param. }的形式拿数据
    --%>
    这是param.的方式拿数据:${param.name}

注意:Map,Model,ModelMap和request一样,都使用请求作用域进行数据传递.所以服务器端的跳转必须是请求转发.

12.日期处理

1)日期的提交处理

A.单个日期处理
要使用注解@DateTimeFormat,此注解必须搭配springmvc.xml文件中的<mvc:annotationdriven标签>
B.类中全局日期处理
注册一个注解,用来解析本类中所有的日期类型,自动转换.
 @InitBinder
public void initBinder(WebDataBinder dataBinder){
    dataBinder.registerCustomEditor(Date.class,new CustomDateEditor(sf,true));
}

2)日期的显示处理
在页面上显示好看的日期,必须使用JSTL.
步骤:

A)添加依赖jstl
  <dependency>
  <groupId>jstl</groupId>
  <artifactId>jstl</artifactId>
  <version>1.2</version>
</dependency>

B)在页面上导入标签库
如果是单个日期对象,直接转为好看的格式化的字符串进行显示.
如果是list中的实体类对象的成员变量是日期类型,则必须使用jstl进行显示.

<%--导入jstl核心标签库--%>
<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%--导入jstl格式化标签库--%>
<%@taglib prefix="fmt" uri="http://java.sun.com/jsp/jstl/fmt" %>
C)使用标签显示数据
  <table width="800px" border="1">
    <tr>
        <th>姓名</th>
        <th>生日</th>
    </tr>
    	<c:forEach items="${list}" var="stu">
    <tr>
            <td>${stu.name}</td>
            <td>${stu.birthday}------ <fmt:formatDate value="${stu.birthday}" pattern="yyyy-MM-dd"></fmt:formatDate></td>
    </tr>
    	</c:forEach>
	</table>

13.资源在WEB-INF目录下

此目录下的动态资源,不可直接访问,只能通过请求转发的方式进行访问 .

  @Controller
	public class WebInfAction {
	    @RequestMapping("/showIndex")
	    public String showIndex(){
	        System.out.println("访问index.jsp");
	        return "index";
	    }
	    @RequestMapping("/showMain")
	    public String showMain(){
	        System.out.println("访问main.jsp");
	        return "main";
	    }
	    @RequestMapping("/showLogin")
	    public String showLogin(){
	        System.out.println("访问login.jsp");
	        return "login";
	    }
	    //登录的业务判断
	    @RequestMapping("/login")
	    public String login(String name, String pwd, HttpServletRequest request){
	        if("zar".equalsIgnoreCase(name) && "123".equalsIgnoreCase(pwd)){
	            return "main";
	        }else{
	            request.setAttribute("msg","用户名或密码不正确!");
	            return "login";
	        }
	    }
	}

14.SpringMVC的拦截器Interceptor

针对请求和响应进行的额外的处理.在请求和响应的过程中添加预处理,后处理和最终处理.

15.拦截器执行的时机

1)preHandle():在请求被处理之前进行操作,预处理
2)postHandle():在请求被处理之后,但结果还没有渲染前进行操作,可以改变响应结果,后处理
3)afterCompletion:所有的请求响应结束后执行善后工作,清理对象,关闭资源 ,最终处理.

16.拦截器实现的两种方式

1)继承HandlerInterceptorAdapter的父类
2)实现HandlerInterceptor接口,实现的接口,推荐使用实现接口的方式

17.拦截器实现的步骤

1)改造登录方法,在session中存储用户信息,用于进行权限验证

  @RequestMapping("/login")
    public String login(String name, String pwd, HttpServletRequest request){
        if("zar".equalsIgnoreCase(name) && "123".equalsIgnoreCase(pwd)){
            //在session中存储用户信息,用于进行权限验证
            request.getSession().setAttribute("users",name);
            return "main";
        }else{
            request.setAttribute("msg","用户名或密码不正确!");
            return "login";
        }
    }

2)开发拦截器的功能.实现HandlerInterceptor接口,重写preHandle()方法

 if(request.getSession().getAttribute("users") == null){
            //此时就是没有登录,打回到登录页面,并给出提示
            request.setAttribute("msg","您还没有登录,请先去登录!");
            request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
            return false;
        }
        return true;//放行请求

2)在springmvc.xml文件中注册拦截器

<mvc:interceptors>
    <mvc:interceptor>
        <!--映射要拦截的请求-->
        <mvc:mapping path="/**"/>
        <!--设置放行的请求-->
        <mvc:exclude-mapping path="/showLogin"></mvc:exclude-mapping>
        <mvc:exclude-mapping path="/login"></mvc:exclude-mapping>
        <!--配置具体的拦截器实现功能的类-->
        <bean class="com.bjpowernode.interceptor.LoginInterceptor"></bean>
    </mvc:interceptor>
</mvc:interceptors>

18.SSM整合的步骤

0)建库,建表
1)新建Maven项目,选择webapp模板
2)修改目录
3)修改pom.xml文件(cv)
4)添加jdbc.properties属性文件
5)添加SqlMapConfig.xml文件(使用模板)
6)添加applicationContext_mapper.xml文件(数据访问层的核心配置文件)
7)添加applicationContext_service.xml文件(业务逻辑层的核心配置文件)
8)添加spirngmvc.xml文件
9)删除web.xml文件,新建,改名,设置中文编码,并注册spirngmvc框架,并注册Spring框架
10)新建实体类user
11)新建UserMapper.java接口
12)新建UserMapper.xml实现增删查所有功能,没有更新
13)新建service接口和实现类
14)新建测试类,完成所有功能的测试
15)新建控制器,完成所有功能
16)浏览器测试功能

5、添加SqlMapConfig.xml文件(使用模板)

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


    <!--设置日志输出语句,显示相应操作的sql语名-->
    <settings>
        <setting name="logImpl" value="STDOUT_LOGGING"/>
    </settings>

</configuration>

6、添加applicationContext_mapper.xml文件(数据访问层的核心配置文件)

需要在这里把UserMapper这个接口,以及UserMapper.xml(mybatis具体的sql语句在这里)进行导入。(mapper肯定就要把mybatis那一层的导入,在applicationContext_service中也对service层的文件进行导入,别名注册等等)

SqlMapConfig.xml也在这里面进行了导入(spring容器将其整合)。本来很多配置都写着SqlMapConfig中,但是spring框架将其整合,尤其是sqlSessionFactoryBean这个配置原来在SqlMapConfig.xml中对应的是<environment> 里面的<dataSource type="POOLED">

<?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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context https://www.springframework.org/schema/context/spring-context.xsd">

    <!--读取属性文件,注意要加classpath,现在是要交给tomcat-->
    <context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>

    <!--配置数据源-->
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource">
        <property name="driverClassName" value="${jdbc.driverClassName}"></property>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
    </bean>

    <!--配置sqlSessionFactoryBean,上面的数据源就是配给这里的-->
    <bean class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--配置数据源-->
        <property name="dataSource" ref="dataSource"></property>
        <!--配置SqlMapConfig.xml核心配置-->
        <property name="configLocation" value="classpath:SqlMapConfig.xml"></property>
        <!--注册实体类-->
        <property name="typeAliasesPackage" value="cn.edu.uestc.pojo"></property>
    </bean>

    <!--注册mapper.xml-->
    <bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <property name="basePackage" value="cn.edu.uestc.mapper"/>
    </bean>
</beans>

7、添加applicationContext_service.xml文件(业务逻辑层的核心配置文件)

既然是applicationContext_service.xml,做的大部分就是业务逻辑层的事情,service.impl的包扫描等等
在这里添加事务管理器;配置事务切面;service.impl的包扫描

<?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: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 https://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 https://www.springframework.org/schema/aop/spring-aop.xsd">

	<!--添加包扫描-->
    <context:component-scan base-package="cn.edu.uestc.service.impl"></context:component-scan>
    <!--添加事务管理器-->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <!--切记切记:配置数据源-->
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!--配置事务切面-->
    <tx:advice id="myadvice" transaction-manager="transactionManager">
        <tx:attributes>
            <tx:method name="*select*" read-only="true"/>
            <tx:method name="*find*" read-only="true"/>
            <tx:method name="*search*" read-only="true"/>
            <tx:method name="*get*" read-only="true"/>

            <tx:method name="*insert*" propagation="REQUIRED"/>
            <tx:method name="*add*" propagation="REQUIRED"/>
            <tx:method name="*save*" propagation="REQUIRED"/>
            <tx:method name="*set*" propagation="REQUIRED"/>
            <tx:method name="*update*" propagation="REQUIRED"/>
            <tx:method name="*change*" propagation="REQUIRED"/>
            <tx:method name="*modify*" propagation="REQUIRED"/>
            <tx:method name="*delete*" propagation="REQUIRED"/>
            <tx:method name="*drop*" propagation="REQUIRED"/>
            <tx:method name="*remove*" propagation="REQUIRED"/>
            <tx:method name="*clear*" propagation="REQUIRED"/>
            <tx:method name="*" propagation="SUPPORTS"/>
        </tx:attributes>
    </tx:advice>
    <!--配置切入点+绑定-->
    <aop:config>
        <aop:pointcut id="mycut" expression="execution(* cn.edu.uestc.service.impl.*.*(..))"/>
        <aop:advisor advice-ref="myadvice" pointcut-ref="mycut"/>
    </aop:config>
</beans>

8、添加springmvc.xml文件

springmvc.xml看作界面层,在这里添加controller的包扫描(上了注解);

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

    <!--添加包扫描-->
    <context:component-scan base-package="cn.edu.uestc.controller"></context:component-scan>
    <!--添加注解驱动-->
    <mvc:annotation-driven></mvc:annotation-driven>
    <!--本项目全部是ajax请求,因此不需要配置视图解析器-->

</beans>

9、删除web.xml文件,新建,改名,设置中文编码,并注册spirngmvc框架,并注册Spring框架

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
         version="4.0">
    <!--添加中文编码过滤器
      private String encoding;
      private boolean forceRequestEncoding;
      private boolean forceResponseEncoding;
    -->
    <filter>
        <filter-name>encode</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>forceRequestEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
        <init-param>
            <param-name>forceResponseEncoding</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>encode</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--注册SpringMVC框架-->
    <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>/</url-pattern>
    </servlet-mapping>

    <!--注册Spring框架,目的就是启动spring容器-->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext_*.xml</param-value>
    </context-param>
</web-app>
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值