当前位置:网站首页>SSM framework integration
SSM framework integration
2022-07-03 04:52:00 【Bald talents】
SSM Framework integration
One 、 preparation
1. Integrate in the original way 
2. establish maven engineering 
3、 Import maven coordinate
4、 Write entity class
5、 Writing interface
6、 To write Service Interface
7、Service Interface implementation
8、 To write Controller
9、 Write add page
10、 Write a list page
11、 Write the corresponding configuration file 
12、 test
Two 、 Environment building


Create a itheima_ssm Of maven engineering
Import coordinates
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.itheima</groupId>
<artifactId>itheima_ssm</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<name>itheima_ssm Maven Webapp</name>
<!-- FIXME change it to the project's website -->
<url>http://www.example.com</url>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.7</maven.compiler.source>
<maven.compiler.target>1.7</maven.compiler.target>
</properties>
<dependencies>
<!--spring relevant -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.8.7</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-test</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.0.5.RELEASE</version>
</dependency>
<!--servlet and jsp-->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>servlet-api</artifactId>
<version>2.5</version>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.0</version>
</dependency>
<!--mybatis relevant -->
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.4.5</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.6</version>
</dependency>
<dependency>
<groupId>c3p0</groupId>
<artifactId>c3p0</artifactId>
<version>0.9.1.2</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
<dependency>
<groupId>jstl</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
</dependencies>
<build>
<finalName>itheima_ssm</finalName>
<pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
<plugins>
<plugin>
<artifactId>maven-clean-plugin</artifactId>
<version>3.0.0</version>
</plugin>
<!-- see http://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_war_packaging -->
<plugin>
<artifactId>maven-resources-plugin</artifactId>
<version>3.0.2</version>
</plugin>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.7.0</version>
</plugin>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>2.20.1</version>
</plugin>
<plugin>
<artifactId>maven-war-plugin</artifactId>
<version>3.2.0</version>
</plugin>
<plugin>
<artifactId>maven-install-plugin</artifactId>
<version>2.5.2</version>
</plugin>
<plugin>
<artifactId>maven-deploy-plugin</artifactId>
<version>2.8.2</version>
</plugin>
</plugins>
</pluginManagement>
</build>
</project>
Again main Create a file under the package com.domain.Account file
package com.com.domain;
public class Account {
private Integer id;
private String name;
private double money;
public Integer getId() {
return id;
}
public void setId(Integer id) {
this.id = id;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public double getMoney() {
return money;
}
public void setMoney(double money) {
this.money = money;
}
}
Create an interface com.mapper.AccountMapper
package com.mapper;
import com.domain.Account;
import java.util.List;
public interface AccountMapper {
// Save account data
void save(Account account);
// Query account data
List<Account> findAll();
}
establish com.service.AccountService Interface
package com.service;
import com.domain.Account;
import java.util.List;
public interface AccountService {
void save(Account account); // Save account data
List<Account> findAll(); // Query account data
}
Create files under this package impl.AccountImplService file
package com.service.impl;
import com.domain.Account;
import com.service.AccountService;
import java.util.List;
public class AccountImplService implements AccountService {
@Override
public void save(Account account) {
}
@Override
public List<Account> findAll() {
return null;
}
}
create a file com.controller.AccountController
package com.controller;
import com.domain.Account;
import com.service.AccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;
@Controller
@RequestMapping("/account")
public class AccountController {
@Autowired
private AccountService accountService;
@RequestMapping("/save")
@ResponseBody
public String save(Account account){
accountService.save(account);
return "save success";
}
@RequestMapping("/findAll")
public ModelAndView findAll(){
ModelAndView modelAndView = new ModelAndView();
modelAndView.setViewName("accountList");
modelAndView.addObject("accountList",accountService.findAll());
return modelAndView;
}
}
Again webapp Create a package named save Of jsp file
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1> Add account information form </h1>
<form name="accountForm" action="${pageContext.request.contextPath}/account/save" method="post">
title of account :<input type="text" name="name"><br>
Amount of account :<input type="text" name="money"><br>
<input type="submit" value=" preservation "><br>
</form>
</body>
</html>
Again WEB-INT The package creation name is page Project package , Create a accountList Of jsp file
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1> Show account data list </h1>
<table>
<tr>
<th> Account id</th>
<th> title of account </th>
<th> Amount of account </th>
</tr>
<tr>
<td>1</td>
<td>zhangsan</td>
<td>5000</td>
</tr>
</table>
</body>
</html>
Again resource Create jdbc.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test
jdbc.username=root
jdbc.password=011012
Then create the log file :log4j.properties
#
# Hibernate, Relational Persistence for Idiomatic Java
#
# License: GNU Lesser General Public License (LGPL), version 2.1 or later.
# See the lgpl.txt file in the root directory or <http://www.gnu.org/licenses/lgpl-2.1.html>.
#
### direct log messages to stdout ###
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.err
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### direct messages to file hibernate.log ###
#log4j.appender.file=org.apache.log4j.FileAppender
#log4j.appender.file.File=hibernate.log
#log4j.appender.file.layout=org.apache.log4j.PatternLayout
#log4j.appender.file.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n
### set log levels - for more verbose logging change 'info' to 'debug' ###
log4j.rootLogger=all, stdout
3、 ... and 、Mybatis The configuration file
stay resource Create project package under com/Mapper, Create the file again AccountMapper.xml(MyBatis The mapping file :AccountMapper.xml)
<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.mapper.AccountMapper">
<insert id="save" parameterType="account">
insert into account values(#{id},#{name},#{money})
</insert>
<select id="findAll" resultType="account">
select * from account
</select>
</mapper>
establish MyBatis Core documents :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>
<!-- load properties file -->
<properties resource="jdbc.properties"></properties>
<!-- Define an alias -->
<typeAliases>
<!--<typeAlias type="com.domain.Account" alias="account"></typeAlias>-->
<package name="com.domain"></package>
</typeAliases>
<!-- Environmental Science -->
<environments default="developement">
<environment id="developement">
<transactionManager type="JDBC"></transactionManager>
<dataSource type="POOLED">
<property name="driver" value="${jdbc.driver}"></property>
<property name="url" value="${jdbc.url}"></property>
<property name="username" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</dataSource>
</environment>
</environments>
<!-- Load map -->
<mappers>
<!--<mapper resource="com/mapper/AccountMapper.xml"></mapper>-->
<package name="com.mapper"></package>
</mappers>
</configuration>
Four 、Spring and SpringMvc To configure
Spring The configuration file :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:aop="http://www.springframework.org/schema/aop" xmlns:tx="http://www.springframework.org/schema/tx" 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/tx http://www.springframework.org/schema/tx/spring-tx.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- Component scan scanning service and mapper-->
<context:component-scan base-package="com">
<!-- exclude controller Scan -->
<context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"></context:exclude-filter>
</context:component-scan>
<!-- load propeties file -->
<context:property-placeholder location="classpath:jdbc.properties"></context:property-placeholder>
<!-- Configure data source information -->
<bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource">
<property name="driverClass" value="${jdbc.driver}"></property>
<property name="jdbcUrl" value="${jdbc.url}"></property>
<property name="user" value="${jdbc.username}"></property>
<property name="password" value="${jdbc.password}"></property>
</bean>
<!-- To configure sessionFactory-->
<bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"></property>
<!-- load mybatis Core documents -->
<property name="configLocation" value="classpath:sqlMapConfig.xml"></property>
</bean>
<!-- scanning mapper The bag where it is by mapper Create implementation classes -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="basePackage" value="com.mapper"></property>
</bean>
<!-- Declarative transaction control -->
<!-- Platform transaction manager -->
<bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
<property name="dataSource" ref="dataSource"></property>
</bean>
<!-- Configure transaction enhancements -->
<tx:advice id="txAdvice">
<tx:attributes>
<tx:method name="*"/>
</tx:attributes>
</tx:advice>
<!-- The transaction aop Weaving -->
<aop:config>
<aop:advisor advice-ref="txAdvice" pointcut="execution(* com.service.impl.*.*(..))"></aop:advisor>
</aop:config>
</beans>
SprngMVC The configuration file :spring-mvc.xml
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:mvc="http://www.springframework.org/schema/mvc" xmlns:context="http://www.springframework.org/schema/context" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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">
<!-- Component scan Primary scan controller-->
<context:component-scan base-package="com.controller"></context:component-scan>
<!-- To configure mvc Annotation driven -->
<mvc:annotation-driven></mvc:annotation-driven>
<!-- Internal resource view parser -->
<bean id="resourceViewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/page/"></property>
<property name="suffix" value=".jsp"></property>
</bean>
<!-- Develop static resource access -->
<mvc:default-servlet-handler></mvc:default-servlet-handler>
</beans>
5、 ... and 、web.xml To configure
modify webapp Under the WEB-INF Under the web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">
<!--spring Monitor -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--springmvc Front end controller for -->
<servlet>
<servlet-name>DispatcherServlet</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>DispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<!-- Random code filter -->
<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>
</web-app>
6、 ... and 、 Logic code
modify AccountImplService file
package com.service.impl;
import com.domain.Account;
import com.mapper.AccountMapper;
import com.service.AccountService;
import org.apache.ibatis.io.Resources;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;
import org.apache.ibatis.session.SqlSessionFactoryBuilder;
import org.springframework.stereotype.Service;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
@Service("accountService")
public class AccountImplService implements AccountService {
@Override
public void save(Account account) {
try {
InputStream resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
mapper.save(account);
sqlSession.commit();
sqlSession.close();
} catch (IOException e) {
e.printStackTrace();
}
}
@Override
public List<Account> findAll() {
InputStream resourceAsStream = null;
try {
resourceAsStream = Resources.getResourceAsStream("sqlMapConfig.xml");
SqlSessionFactory sqlSessionFactory = new SqlSessionFactoryBuilder().build(resourceAsStream);
SqlSession sqlSession = sqlSessionFactory.openSession();
AccountMapper mapper = sqlSession.getMapper(AccountMapper.class);
List<Account> accountList = mapper.findAll();
sqlSession.close();
return accountList;
} catch (IOException e) {
e.printStackTrace();
}
return null;
}
}
边栏推荐
- 雇佣收银员(差分约束)
- [set theory] relational representation (relational matrix | examples of relational matrix | properties of relational matrix | operations of relational matrix | relational graph | examples of relationa
- I've been in software testing for 8 years and worked as a test leader for 3 years. I can also be a programmer if I'm not a professional
- MC Layer Target
- C language self-made Games: Sanzi (tic tac toe chess) intelligent chess supplement
- [tools run SQL blind note]
- 文献阅读_基于多模态数据语义融合的旅游在线评论有用性识别研究(中文文献)
- Mount NFS in kubesphere
- Number of 1 in binary (simple difficulty)
- Use Sqlalchemy module to obtain the table name and field name of the existing table in the database
猜你喜欢

Analysis of proxy usage of ES6 new feature

论文阅读_中文NLP_ELECTRA

Games101 Lesson 9 shading 3 Notes

Network security textual research recommendation

Small sample target detection network with attention RPN and multi relationship detector (provide source code, data and download)

Shuttle + Alluxio 加速内存Shuffle起飞

Leetcode simple question: the key with the longest key duration

Leetcode simple question: check whether the array is sorted and rotated

论文阅读_清华ERNIE

LVS load balancing cluster of efficient multi-purpose cluster (NAT mode)
随机推荐
Integration of Android high-frequency interview questions (including reference answers)
7. Integrated learning
Oracle SQL table data loss
[PCL self study: filtering] introduction and use of various filters in PCL (continuously updated)
[SQL injection] joint query (the simplest injection method)
What is UUID
Number of uniform strings of leetcode simple problem
General undergraduate college life pit avoidance Guide
UiPath实战(08) - 选取器(Selector)
Market status and development prospect prediction of global fermented plant protein industry in 2022
Two drawing interfaces - 1 Matlab style interface
Web security - CSRF (token)
On typescript and grammar
关于开学的准备与专业认知
【PHP漏洞-弱类型】基础知识、php弱相等、报错绕过
C Primer Plus Chapter 10, question 14 3 × 5 array
LVS load balancing cluster of efficient multi-purpose cluster (NAT mode)
The least operation of leetcode simple problem makes the array increment
Handling record of electric skateboard detained by traffic police
2022 new examination questions for the main principals of hazardous chemical business units and examination skills for the main principals of hazardous chemical business units