Integrating Spring and Spring MVC

Posted by jfugate on Sun, 24 Nov 2019 15:36:31 +0100

1. The relationship between spring container and spring MVC container

Spring container is a parent container, and spring MVC container is a child container, which inherits from spring container. Therefore, in the spring MVC container, you can access the beans defined in the spring container, while in the spring container, you cannot access the beans defined in the spring MVC container. In Web development, all controllers are scanned in spring MVC, and all beans except Controller are scanned in spring container (Service, Dao). After scanning, the Controller can access the Service.

  1. Why not scan everything in Spring    because the processor mapper will only find the Controller in Spring MVC, if not, it will not find it in Spring, which determines that the Controller must be scanned in Spring MVC.
  2. Why not scan all in spring MVC    in SSM integration or spring + spring MVC + jdbctemplate, you can scan all of them in spring MVC, but in SSH integration, this method is not allowed.

Best practices:

  1. The Controller is scanned in spring MVC, and the view parser is configured in the spring MVC container
  2. Scan Service, Dao and other components in Spring. Transaction definition and data source definition are all configured in Spring container

case

Import jar package

Define bean layer

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 + "]";
	}
	
}

Define dao layer and implementation class

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));
	}

}

Define Service and its implementation class

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();
	}

}

Spring MVC configuration file

<!-- open SpringMVC How to annotate -->
	<mvc:annotation-driven >
	</mvc:annotation-driven>
		<!-- Open scan -->
	<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>

Configuration files for 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">
 			<!-- Information about the configuration database -->
		<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>

In the web.xml file

Load the configuration of spring and spring MVC respectively

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

Custom 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";
	}
}

Extract the data from the user page

<%@ 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>

Effect test

Topics: Programming Spring Java xml JDBC