The whole process of building the SSM framework

1. Create a project

Create Maven Project, check Create a simple project, Group id is cn.tedu.spring, Artifact id is SpringMVC-02, Packaging select war.

When the project is created, first generate the web.xml file; right-click on the project to set the properties, check the Tomcat in Targeted Runtimes; add spring-webmvc dependency in pom.xml (recommended to use version 4.2 or above https:// blog.csdn.net/qq_37669050/article/details/102384613); Copy the Spring configuration file in the previous project to the current new project (https://blog.csdn.net/qq_37669050/article/details/102594279).

2. Configure DispatcherServlet

First of all, you need to configure DispatcherServlet in web.xml. The basic configuration is as follows:

    <servlet-mapping>
    	<servlet-name>SpringMVC</servlet-name>
    	<url-pattern>*.do</url-pattern>
    </servlet-mapping>
    <servlet>
  	<servlet-name>SpringMVC</servlet-name>
  	<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
  	<init-param><!-- param:参数 -->
  		<param-name>contextConfigLocation</param-name>
  		<param-value>classpath:spring-ajax.xml</param-value>
  	</init-param>
  	<load-on-startup>1</load-on-startup>
  </servlet>
  <servlet-mapping>
  	<servlet-name>SpringMVC</servlet-name>
  	<url-pattern>*.do</url-pattern>
  </servlet-mapping>
  <!-- 解决SpringMVC中文乱码问题的过滤器 -->
  <filter>
  	<filter-name>CharacterEncodingFilter</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>CharacterEncodingFilter</filter-name>
  	<url-pattern>/*</url-pattern>
  </filter-mapping>

The SpringMVC framework is based on Spring and will be configured in Spring's configuration file (spring-mvc.xml) in the future. It is hoped that the Spring configuration file will be loaded when the project starts. Yes: In the above configuration, configure the initialization parameter contextConfigLocation for DispatcherServlet. The value of this parameter is the location of the Spring configuration file. Once this parameter is configured, when the DispatcherServlet is initialized, the Spring configuration file will be automatically loaded! Then, configure DispatcherServlet to start by default, that is, when Tomcat starts, it will initialize DispatcherServlet, which will cause spring-mvc.xml to be read and loaded.

The supplementary configuration is:

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

<servlet-mapping>
	<servlet-name>SpringMVC</servlet-name>
	<url-pattern>*.do</url-pattern>
</servlet-mapping>

Note: The order of the above configuration and nodes are distinguished!

If you need to test whether the above configuration is successful, you can first configure component scanning in spring-mvc.xml:

<!-- 组件扫描 -->
<context:component-scan base-package="cn.tedu.spring"/>

Then, create any class under the scanned package, add Compontent annotations to the class, customize the construction method, and output a string, for example:

package cn.tedu.spring;

import org.springframework.stereotype.Component;

@Component
public class User {
	
	public User() {
		System.out.println("创建了User类的对象!");
	}

}

Finally, start the project and you should be able to see the output in the construction method in the Eclipse console!

3. Receive requests submitted by users through the controller

Through the @RequestMapping annotation, you can set the mapping relationship between the request path and the method of processing the request, so in actual programming, there is no need to explicitly use HandlerMapping.

Therefore, you can directly create the cn.tedu.spring.HelloController controller class, and add the @Controller annotation to the class, so that the Spring framework will create the object of the controller class, and finally, it will be recognized and used by the SpringMVC framework.

Then, add a method to process the request in the controller class, about the design of the method:

  1. Should use public permissions;
  2. Temporarily use String as the return value type;
  3. The method name can be customized;
  4. The parameter list of the method is temporarily empty.

You can add methods:

public String showHello() {
	return null;
}

Need to use @RequestMapping before the method to configure the mapping relationship, then:

@RequestMapping("hello.do")
public String showHello() {
	System.out.println("HelloController.showHello()");
	return null;
}

Note: The above controller classes must be placed in the cn.tedu.spring package, because the component scan was previously set up in this package! Generally, the control class should use the word Controller as the name suffix. Controller class can only use @Controller annotation, not @Component or other annotations.

After completion, restart the project, open the browser, and test through http://localhost:8080/SpringMVC-02/hello.do. The correct result should be: In the Eclipse console, you can see the output of the above method ! If the page has not been processed, a 404 error may occur.

4. Display page

By default, if the method in the controller returns String type data, it means "view name", and the framework needs to determine which view component is responsible for the display of the final response based on the view name. You need to configure in spring-mvc.xml:

<!-- 模版解析器:ServletContextTemplateResolver -->
<!-- 配置ServletContextTemplateResolver时,HTML文件应该以webapp文件夹为参考 -->
<!-- 配置ClassLoaderTemplateResolver时,HTML文件应该以项目的resources文件夹为参考 -->
<bean id="templateResolver"
	class="org.thymeleaf.templateresolver.ServletContextTemplateResolver">
	<property name="prefix" 
		value="/WEB-INF/templates/" />
	<property name="suffix" 
		value=".html" />
	<property name="characterEncoding" 
		value="utf-8" />
	<property name="templateMode" 
		value="HTML" />
	<property name="cacheable" 
		value="false" />
</bean>

<!-- Spring模版引擎:SpringTemplateEngine -->
<bean id="templateEngine"
	class="org.thymeleaf.spring4.SpringTemplateEngine">
	<property name="templateResolver"
		ref="templateResolver" />
</bean>

<!-- 视图解析器:ThymeleafViewResolver -->
<bean class="org.thymeleaf.spring4.view.ThymeleafViewResolver">
	<property name="templateEngine"
		ref="templateEngine" />
</bean>

Then, change the return value of the method that handles the request in the controller to "hello".

Finally, create hello.html under the webapp/WEB-INF/templates/ folder, and design the page content yourself in HTML. Test through http://localhost:8080/SpringMVC-02/hello.do.
To create a Maven Project, use cn.tedu.mybatis for Group Id, MyBatis for Artifact Id, and war for Packaing (you can also choose jar).

MyBatis

After the project is created, you need to: generate a web.xml file; add dependencies in pom.xml; copy spring-mvc.xml from the previous project to the current project; add the Tomcat operating environment (this case may not be needed); open the previous In the web.xml of the project, copy the configuration of DispatcherServlet and CharacterEncodingFilter to the current project.

This time you need to add dependencies:

<!-- MyBatis -->
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis</artifactId>
	<version>3.5.1</version>
</dependency>

<!-- MyBatis整合Spring -->
<dependency>
	<groupId>org.mybatis</groupId>
	<artifactId>mybatis-spring</artifactId>
	<version>2.0.1</version>
</dependency>

<!-- SpringJDBC -->
<!-- 注意:与当前项目使用的其它spring依赖保持相同的版本号 -->
<dependency>
	<groupId>org.springframework</groupId>
	<artifactId>spring-jdbc</artifactId>
	<version>4.3.10.RELEASE</version>
</dependency>

<!-- mysql连接 -->
<!-- 可选版本号:8.0.12~8.0.16,5.1.4~5.1.6 -->
<dependency>
	<groupId>mysql</groupId>
	<artifactId>mysql-connector-java</artifactId>
	<version>8.0.16</version>
</dependency>

<!-- 数据库连接池 -->
<dependency>
	<groupId>commons-dbcp</groupId>
	<artifactId>commons-dbcp</artifactId>
	<version>1.4</version>
</dependency>

<!-- 单元测试 -->
<dependency>
	<groupId>junit</groupId>
	<artifactId>junit</artifactId>
	<version>4.12</version>
</dependency>

Then, copy spring-mvc.xml to get spring-dao.xml, delete the configuration in spring-dao.xml file!

  1. Database Connectivity

Create a db.properties file under src/main/resources to configure related information about the database connection:

url=jdbc:mysql://localhost:3306/tedu_ums?useUnicode=true&characterEncoding=utf-8&serverTimezone=Asia/Shanghai
driver=com.mysql.cj.jdbc.Driver
username=root
password=root
initialSize=2
maxActive=10

When configuring the driver attribute, you need to pay attention to the version of mysql-connector-java used. If you are using version 5.x, the attribute value should be com.mysql.jdbc.Driver, if you are using 6.x or higher Version, the attribute value should be com.mysql.cj.jdbc.Driver, if you are not sure which value should be used, you can expand the jar file of mysql-connector-java to observe! In addition, there is a META-INF/services/java.sql.Driver file in the jar package, which records the Driver class that should be used when using the jar package.

If you are using mysql-connector-java of version 6.x or above, you must explicitly set the value of the serverTimezone parameter when configuring the URL to connect to the database! Available values ​​in Mainland China are Asia/Shanghai and Asia/Chongqing.

Need to add configuration in spring-dao.xml, read the configuration information in the above db.properties:

<util:properties id="config" location="classpath:db.properties" />

Then, when connecting to the database, the data source used will be BasicDataSource, you need to inject the database connection information read above into the properties of BasicDataSource:

<!-- 配置数据源,保证其能够连接数据库 -->
<bean id="dataSource"
	class="org.apache.commons.dbcp.BasicDataSource">
	<property name="url" value="#{config.url}" />
	<property name="driverClassName" value="#{config.driver}" />
	<property name="username" value="#{config.username}" />
	<property name="password" value="#{config.password}" />
	<property name="initialSize" value="#{config.initialSize}" />
	<property name="maxActive" value="#{config.maxActive}" />
</bean>

Then, you can write and execute unit tests in the test class to check whether the configuration is correct:

public class Tests {
	
	ClassPathXmlApplicationContext ac;
	
	@Before
	public void doBefore() {
		ac = new ClassPathXmlApplicationContext(
				"spring-dao.xml");
	}
	
	@After
	public void doAfter() {
		ac.close();
	}
	
	@Test
	public void getConnection() throws SQLException {
		BasicDataSource dataSource = ac.getBean("dataSource", BasicDataSource.class);
		Connection conn = dataSource.getConnection();
		System.out.println(conn);
	}

}
  1. Interface and abstract method

Tentative goal: Use MyBatis to insert new user data into the data table.

When using MyBatis, you need to define the abstract methods corresponding to each function, and these abstract methods must be defined in the interface!

First, you should create the cn.tedu.mybatis.UserMapper interface file, and then define the abstract method of "inserting user data" in the interface. The design principle of the abstract method:

  • If you need to perform an operation of adding, deleting, or modifying types, use Integer as the return value of the method, which will indicate the "number of rows affected", which can be used to judge the success of the operation, or it can be designed as an int, or it can be designed Void means don't care about the number of rows affected;
  • The method name can be customized and cannot be overloaded;
  • The parameter list is determined according to the required parameters. You can refer to the question marks in SQL when learning JDBC before, and write which parameters.

The SQL statement that needs to be executed for "insert user data" is roughly:

insert into (username, password, age, phone, email) values (?,?,?,?,?)

The abstract method needs to write 5 parameters. If more fields are added to the data table later, more parameters need to be written. This approach is flawed. These parameters should be encapsulated in the cn.tedu.mybatis.User class. in:

public class User {

	private Integer id;
	private String username;
	private String password;
	private Integer age;
	private String phone;
	private String email;

}

The abstract method can be designed as:

Integer insert(User user);

Next, you need to configure "Where is the interface file" to ensure that the interface can be found when the MyBatis framework works:

<!-- 配置MapperScannerConfigurer -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
	<!-- 配置接口文件在哪里 -->
	<property name="basePackage"
		value="cn.tedu.mybatis" />
</bean>
  1. Configure SQL mapping

Download the XML file compression package for writing configuration files from http://doc.tedu.cn/config/mybatis-mapper.zip.

Create a folder named mappers under src/main/resources and copy SomeMapper.xml in the compressed package to this folder.

Note: The XML file used to configure SQL statements in MyBatis must include the following statement, otherwise it will not work properly!

<!DOCTYPE mapper PUBLIC "-//ibatis.apache.org//DTD Mapper 3.0//EN" "http://ibatis.apache.org/dtd/ibatis-3-mapper.dtd">

When configuring the XML file, first, you need to add a root node, and you must configure the namespace attribute. The attribute value indicates which interface file corresponds to:

<!-- namespace:对应哪个接口 -->
<mapper namespace="cn.tedu.mybatis.UserMapper">

</mapper>

Then, according to the type of SQL statement that needs to be executed, select the child node from,,, and. The id attribute of the node is the name of the abstract method. Then, write the SQL statement that needs to be executed in the content of the node. Use #{} in the parameter part. Format placeholder, the name inside the placeholder is the attribute name in the method parameter User class:

<!-- id:抽象方法的名称 -->
<insert id="insert">
	INSERT INTO t_user (
		username, password, 
		age, phone, 
		email
	) VALUES (
		#{username}, #{password},
		#{age}, #{phone},
		#{email}
	)
</insert>

Then, you need to configure "Where is the XML file" and "Which data source is used to connect to the database" when the framework is executed! Therefore, you need to add configuration in spring-dao.xml:

<!-- 配置SqlSessionFactoryBean -->
<bean class="org.mybatis.spring.SqlSessionFactoryBean">
	<!-- 配置XML文件在哪里 -->
	<property name="mapperLocations" 
		value="classpath:mappers/*.xml" />
	<!-- 配置使用哪个数据源连接数据库 -->
	<property name="dataSource"
		ref="dataSource" />
</bean>

Finally, write and execute unit tests:

@Test
public void insert() {
	User user = new User();
	user.setUsername("zhaoqi");
	user.setPassword("888999");
	user.setPhone("010-88888888");
	Integer rows = userMapper.insert(user);
	System.out.println("rows=" + rows);
}

Guess you like

Origin blog.csdn.net/qq_37669050/article/details/102594166