整合Spring和SpringMVC

15 篇文章 0 订阅
12 篇文章 0 订阅

1.Spring容器和SpringMVC容器的关系

Spring容器是一个父容器,SpringMVC容器是一个子容器,它继承自Spring容器。因此,在SpringMVC容器中,可以访问到Spring容器中定义的Bean,而在Spring容器中,无法访问SpringMVC容器中定义的Bean。在Web开发中,Controller全部在SpringMVC中扫描,除了Controller之外的Bean,全部在Spring容器中扫描(Service、Dao),按这种方式扫描,扫描完完成后,Controller可以访问到Service。

  1. 为什么不全部都在Spring中扫描
      因为处理器映射器只会去SpringMVC中查找到Controller,如果没有,就找不到,不会去Spring中找,这就决定了,Controller必须在SpringMVC中扫描。
  2. 为什么不全部在SpringMVC中扫描
      在SSM整合或者Spring+SpringMVC+JdbcTemplate中,可以全部在SpringMVC中扫描,但是,在SSH整合中,这种方式不允许。

最佳实践:

  1. Controller在SpringMVC中扫描,视图解析器等在SpringMVC容器中配置
  2. Spring中扫描Service、Dao已经其他组件,事务定义、数据源定义都在Spring容器中配置

案例

导入jar包

在这里插入图片描述

定义bean层

package com.sxt.bean;

public class User {
	private Integer id;
	
	private String username;
	
	private String password;

	public Integer getId() {
		return id;
	}

	public void setId(Integer id) {
		this.id = id;
	}

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public String getPassword() {
		return password;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	@Override
	public String toString() {
		return "User [id=" + id + ", username=" + username + ", password=" + password + "]";
	}
	
}

定义dao层与实现类

package com.sxt.dao;

import java.util.List;

import com.sxt.bean.User;

public interface UserDao {
	public List<User> query();
}

package com.sxt.dao.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Repository;

import com.sxt.bean.User;
import com.sxt.dao.UserDao;
@Repository
public class UserDaoImpl implements UserDao{
	@Resource
	private JdbcTemplate template;
	@Override
	public List<User> query() {
		String Sql="select * from t_user";
				
		return template.query(Sql, new BeanPropertyRowMapper(User.class));
	}

}

定义Service和它的实现类

package com.sxt.service;

import java.util.List;

import com.sxt.bean.User;

public interface UserService {
	public List<User> query();
}

package com.sxt.service.impl;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Service;

import com.sxt.bean.User;
import com.sxt.dao.UserDao;
import com.sxt.service.UserService;
@Service
public class UserServiceImpl implements UserService{
		@Resource
		private UserDao dao;
	@Override
	public List<User> query() {
		return dao.query();
	}

}

SpringMVC配置文件

<!-- 开启SpringMVC注解的方式 -->
	<mvc:annotation-driven >
	</mvc:annotation-driven>
		<!-- 开启扫描 -->
	<context:component-scan base-package="com.sxt.controller" use-default-filters="false">
			<context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
	</context:component-scan>

Spring的配置文件

<context:component-scan base-package="com.sxt.dao.impl,com.sxt.service.impl" use-default-filters="true">
 			<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
 	</context:component-scan>
 	<bean class="org.springframework.jdbc.datasource.DriverManagerDataSource" id="dataSource">
 			<!-- 配置数据库的相关信息 -->
		<property name="driverClassName" value="com.mysql.jdbc.Driver" />
		<property name="url"
			value="jdbc:mysql://localhost:3306/pms?characterEncoding=utf-8" />
		<property name="username" value="root" />
		<property name="password" value="123456" />
 	</bean>
 	<bean class="org.springframework.jdbc.core.JdbcTemplate" id="template">
 		<property name="dataSource" ref="dataSource"></property>
 	</bean>

web.xml文件中

分别加载spring和SpringMVC的配置

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
  <display-name>SpringMVC-01-hello</display-name>
  <welcome-file-list>
    <welcome-file>index.html</welcome-file>
    <welcome-file>index.htm</welcome-file>
    <welcome-file>index.jsp</welcome-file>
    <welcome-file>default.html</welcome-file>
    <welcome-file>default.htm</welcome-file>
    <welcome-file>default.jsp</welcome-file>
  </welcome-file-list>
  <context-param>
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:application.xml</param-value>
  </context-param>
  
	<listener>
		<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
	</listener>
 
	<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:Spring-MVC.xml</param-value>
		</init-param>
		<load-on-startup>1</load-on-startup>
	</servlet>
	<filter>
   <filter-name>encodingFilter</filter-name>
   <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
   <init-param>
       <param-name>encoding</param-name>
       <param-value>UTF-8</param-value>
   </init-param>
</filter>
<filter-mapping>
   <filter-name>encodingFilter</filter-name>
   <url-pattern>/*</url-pattern>
</filter-mapping>   
	<!-- Map all requests to the DispatcherServlet for handling -->
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		<url-pattern>/</url-pattern>
	</servlet-mapping>
	<servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.jpg</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.js</url-pattern>
    </servlet-mapping>
    <servlet-mapping>
        <servlet-name>default</servlet-name>
        <url-pattern>*.css</url-pattern>
    </servlet-mapping>

</web-app>

自定义Controller

package com.sxt.controller;

import java.util.List;

import javax.annotation.Resource;

import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import com.sxt.bean.User;
import com.sxt.service.UserService;

@Controller
public class UserController {
	@Resource
	private UserService userService;
	
	@RequestMapping("/query")
	public String query(Model m){
		 List<User> query = userService.query();
		 m.addAttribute("list",query);
		return "/user.jsp";
	}
}

在user页面将数据提取出来

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
    <%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
  <c:forEach items="${list}" var="user">
  	${user.id }--${user.username }--${user.password }<br>
  </c:forEach>
</body>
</html>

效果测试

在这里插入图片描述

Spring SpringMVC 简单整合(初学者参考) demo项目对应地址说明 :https://blog.csdn.net/tianyu00/article/details/89186404 SpringMVC流程 1、 用户发送请求至前端控制器DispatcherServlet。 2、 DispatcherServlet收到请求调用HandlerMapping处理器映射器。 3、 处理器映射器找到具体的处理器(可以根据xml配置、注解进行查找),生成处理器对象及处理器拦截器(如果有则生成)一并返回给DispatcherServlet。 4、 DispatcherServlet调用HandlerAdapter处理器适配器。 5、 HandlerAdapter经过适配调用具体的处理器(Controller,也叫后端控制器)。 6、 Controller执行完成返回ModelAndView。 7、 HandlerAdapter将controller执行结果ModelAndView返回给DispatcherServlet。 8、 DispatcherServlet将ModelAndView传给ViewReslover视图解析器。 9、 ViewReslover解析后返回具体View。 10、DispatcherServlet根据View进行渲染视图(即将模型数据填充至视图中)。 11、 DispatcherServlet响应用户。 组件说明: 以下组件通常使用框架提供实现: DispatcherServlet:作为前端控制器,整个流程控制的中心,控制其它组件执行,统一调度,降低组件之间的耦合性,提高每个组件的扩展性。 HandlerMapping:通过扩展处理器映射器实现不同的映射方式,例如:配置文件方式,实现接口方式,注解方式等。 HandlAdapter:通过扩展处理器适配器,支持更多类型的处理器。 ViewResolver:通过扩展视图解析器,支持更多类型的视图解析,例如:jsp、freemarker、pdf、excel等。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值