当前位置:网站首页>Sort out the power node, Mr. Wang he's SSM integration steps
Sort out the power node, Mr. Wang he's SSM integration steps
2022-07-04 09:33:00 【Xiaogao who loves fitness】
1.SSM Integrate development steps
In general, it's SPringMVC Receive user requests -----Spring Medium Service object -----Mybatis Processing data
ssm Integration is also called ssi, There are containers in integration
1. First container SpringMVC Containers , management Controller Controller object .
2. The second container Spring Containers , management Service,dao, Utility class object
What we need to do is to give the used objects to the appropriate container to create , management . hold Controller also Web The relevant objects of development are handed over to Springmvc Containers ,
these web Unload with the object Springmvc(dispatcherServlet) In profile .
service,dao The object is defined in Spring In the configuration file , Give Way spring Manage the creation of these objects
3.springmvc The container is spring A child of a container , In a sub container Controller You can access... In the parent container Service object ,
Can be realized controller Use service object .
2. Implementation steps
1. Build a database , I use student A watch of (id,name,age), Only name yes String type , The other two are Int.
2 Join the rely on
Springmvc,spring,mybatis The dependencies of the three frameworks ,jackson rely on ,mysql drive ,druid Connection pool ,jsp,servlet rely on
<?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.gaodeng</groupId>
<artifactId>ssm-gao</artifactId>
<version>1.0-SNAPSHOT</version>
<packaging>war</packaging>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<maven.compiler.source>1.8</maven.compiler.source>
<maven.compiler.target>1.8</maven.compiler.target>
</properties>
<dependencies>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.11</version>
<scope>test</scope>
</dependency>
<!--servlet rely on -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<!-- jsp rely on -->
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>jsp-api</artifactId>
<version>2.2.1-b03</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-tx</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-jdbc</artifactId>
<version>5.2.5.RELEASE</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-core</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.9.0</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis-spring</artifactId>
<version>1.3.1</version>
</dependency>
<dependency>
<groupId>org.mybatis</groupId>
<artifactId>mybatis</artifactId>
<version>3.5.1</version>
</dependency>
<dependency>
<groupId>mysql</groupId>
<artifactId>mysql-connector-java</artifactId>
<version>5.1.9</version>
</dependency>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.12</version>
</dependency>
</dependencies>
<build>
<resources>
<resource>
<directory>src/main/java</directory><!-- directory -->
<includes><!-- Including... In the directory .properties,.xml All the files will be scanned -->
<include>**/*.properties</include>
<include>**/*.xml</include>
</includes>
<filtering>false</filtering>
</resource>
</resources>
<plugins>
<plugin>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
</configuration>
</plugin>
</plugins>
</build>
</project>
3. Write web.xml
(1) register DispatcherServlet, The goal is to create Spring Container object , Then you can create Controller Class object ; establish Servlet, To receive user requests .
(2) register spring Monitor :ContextLoaderListener, The purpose is to create Spring Container object , To create service,dao Objects such as
(3) Register the character set filter , solve post Asking for garbled code .
<?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">
<!--1.-->
<!-- Register the central scheduler -->
<!--init-param Belong to a servlet all ;
context-param Belongs to the entire application ,
Not just in servlet You can get ,jsp You can also get ,
stay jsp in application It's equivalent to servletContext. -->
<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:conf/dispatcherServlet.xml</param-value>
</init-param>
<!--1 It means that this... Is created when the server starts Servlet, Don't wait until you need to use it to create -->
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
<!--2-->
<!-- establish Spring Monitor of container -->
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:conf/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<!--3-->
<!-- Register the character set 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>
<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>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
<!-- Set to /* when , It will cover everything else servlet, Include servlet All provided by the container servlet-->
</filter-mapping>
</web-app>
4. Create a package ,Controller package ,service,dao, Entity class package name created
5.5. Write springmvc,spring,mybatis Configuration file for
1)springmvc The configuration file
<?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">
<!--Springmvc Configuration file for , Statement Controller And others Web Related objects -->
<context:component-scan base-package="com.gaodeng.controller"/>
<!-- view resolver -->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/JSP/"/>
<property name="suffix" value=".jsp"/>
</bean>
<mvc:annotation-driven/>
<!--
1. Respond to ajax request , return json
2. Solve the problem of static resource access .
-->
</beans>
2)spring The configuration file
<?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">
<!-- The information needed to connect to the database needs to be through <context:property-placeholder> Labels can only be used after importing -->
<context:property-placeholder location="classpath:conf/jdbc.properties"/>
<!-- Declare data source , Connect to database -->
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${jdbc.url}"/>
<property name="username" value="${jdbc.username}"/>
<property name="password" value="${jdbc.password}"/>
</bean>
<!--SqlSessionFactoryBean establish SqlSessionFactory-->
<bean id="SqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
<property name="dataSource" ref="dataSource"/>
<property name="configLocation" value="classpath:conf/mybatis.xml"/>
</bean>
<!-- Statement MyBatis Scanner for , establish Dao Implementation class object of interface -->
<bean class="org.mybatis.spring.mapper.MapperScannerConfigurer">
<property name="sqlSessionFactoryBeanName" value="SqlSessionFactory"/>
<property name="basePackage" value="com.gaodeng.dao"/>
</bean>
<!-- Statement service Annotations @Service Package name and location -->
<context:component-scan base-package="com.gaodeng.service"/>
<!-- Transaction configuration : Configuration of annotations , aspectj Configuration of -->
</beans>
3)mybatis Master profile
<?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>
<!--settings: control mybatis Global behavior -->
<!-- <settings>
<!– Set up mybatis Output log –>
<setting name="logImpl" value="STDOUT_LOGGING"/>
</settings>-->
<!-- Set alias -->
<typeAliases>
<!--name: The package name of the entity class ( Package names that are not entity classes can also )-->
<package name="com.gaodeng.domain"/>
</typeAliases>
<!-- sql mapper(sql The mapping file ) The location of -->
<mappers>
<!--
name: It's the name of the bag , Everything in this bag mapper.xml It can be loaded at one time
Use package The requirements of :
1. mapper Document name and dao The interface name must be exactly the same , Include case
2. mapper Document and dao Interfaces must be in the same directory
-->
<package name="com.gaodeng.dao"/>
</mappers>
</configuration>
4) Database property profile
jdbc.url=jdbc:mysql://localhost:3306/gaodeng
jdbc.username=root
jdbc.password=123456
6. Write code , dao Interface and mapper file , service And implementation classes ,controller, Entity class .
I mean, start with simple , First write the entity class , The attribute of the entity class should preferably be the same as the database field name , Prevent what is written later mybatis The mapping file deals with aliases .
Then write dao class ,service class . Last write controller class .
-------------------------------------------------------------------------- Structure diagram of package --------------------------------------------------------------------------------------------------------
Entity class
package com.gaodeng.domain;
public class Student {
private Integer id;
private String name;
private Integer age;
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 Integer getAge() {
return age;
}
public void setAge(Integer age) {
this.age = age;
}
public Student() {
}
@Override
public String toString() {
return "Student{" +
"id=" + id +
", name='" + name + '\'' +
", age=" + age +
'}';
}
}
dao class
package com.gaodeng.dao;
import com.gaodeng.domain.Student;
import java.util.List;
public interface StudentDao {
int insertStudent(Student student);
List<Student> selectStudent();
}
<?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.gaodeng.dao.StudentDao">
<select id="selectStudent" resultType="Student">
select id,name,age from student order by id desc
</select>
<insert id="insertStudent">
insert into student(name,age) values(#{name},#{age})
</insert>
</mapper>
service class
package com.gaodeng.service;
import com.gaodeng.domain.Student;
import java.util.List;
public interface StudentService {
int addStudent(Student student);
List<Student> findStudent();
}
package com.gaodeng.service.impl;
import com.gaodeng.dao.StudentDao;
import com.gaodeng.domain.Student;
import com.gaodeng.service.StudentService;
import org.springframework.stereotype.Service;
import javax.annotation.Resource;
import java.util.List;
@Service
public class StudentServiceImpl implements StudentService {
@Resource
private StudentDao studentdao;
@Override
public int addStudent(Student student) {
int i = studentdao.insertStudent(student);
return i;
}
@Override
public List<Student> findStudent() {
return studentdao.selectStudent();
}
}
controller class
package com.gaodeng.controller;
import com.gaodeng.domain.Student;
import com.gaodeng.service.StudentService;
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;
import javax.annotation.Resource;
import java.util.List;
@Controller
@RequestMapping("/student")
public class StudentController {
@Resource
private StudentService service;
@RequestMapping("/addStudent")
public ModelAndView addStudent(Student student) {
String result = " Add failure ";
int num = service.addStudent(student);
if(num>0){
result = " Student :"+student.getName()+" Data added successfully ";
}
ModelAndView mv = new ModelAndView();
mv.addObject("key1",result);
// Specified jump jsp View page
mv.setViewName("show");
return mv;
}
@RequestMapping("/listStudent")
@ResponseBody
//
public List<Student> listStudent(){
List<Student> student = service.findStudent();
return student;
}
}
7. Write jsp page
index.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title> Function entry </title>
<base href="<%=basePath%>" />
</head>
<body>
<div align="center">
<p>SSM A small chestnut integrated </p>
<table>
<tr>
<td><a href="addStudent.jsp"> Registered students </a></td>
</tr>
<tr>
<td><a href="listStudent.jsp"> Browse students </a></td>
</tr>
</table>
</div>
</body>
</html>
addStudent.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title> Registered students </title>
<base href="<%=basePath%>" />
</head>
<body>
<div align="center">
<form action="student/addStudent.do" method="post">
<table>
<tr>
<td> full name :</td>
<td><input type="text" name="name"></td>
</tr>
<tr>
<td> Age :</td>
<td><input type="text" name="age"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" value=" register "></td>
</tr>
</table>
</form>
</div>
</body>
</html>
ListStudent.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<%
String basePath = request.getScheme() + "://" +
request.getServerName() + ":" + request.getServerPort() +
request.getContextPath() + "/";
%>
<html>
<head>
<title> use ajax Search for student information </title>
<base href="<%=basePath%>" />
<script type="text/javascript" src="js/jquery-3.4.1.js"></script>
<script type="text/javascript">
$(function (){
// On the current page dom After the object is loaded , perform loadStudentData()
loadStudentData();
$("#btn1").click(function (){
loadStudentData();
})
})
function loadStudentData(){
$.ajax({url:"student/listStudent.do",
type:"get",
dataType:"json",
success:function (data){
// Clear old data
$("#tbody").html("");
// Add new data
$.each( data, function (i,n){
$("#tbody").append("<tr>")
.append("<td>"+n.id+"</td>")
.append("<td>"+n.name+"</td>")
.append("<td>"+n.age+"</td>")
.append("</tr>")
})
}
})
}
</script>
</head>
<body>
<div align="center">
<table>
<thead>
<tr> Student number </tr>
<tr> full name </tr>
<tr> Age </tr>
</thead>
<tbody id = "tbody">
</tbody>
</table>
<input type="button" id="btn1" value=" Query data ">
</div>
</body>
</html>
forward .jsp
<%--
Created by IntelliJ IDEA.
User: Brother Deng called me
Date: 2022/1/28
Time: 21:35
To change this template use File | Settings | File Templates.
--%>
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Title</title>
</head>
<body>
<h1> Results page </h1>
<div> ${key1}</div>
</body>
</html>
Encountered bug, There are also some mistakes , Abnormal operation
org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'SqlSessionFactory' defined in class path resource [conf/applicationContext.xml]: Invocation of init method failed; nested exception is org.apache.ibatis.builder.BuilderException: Error creating document instance. Cause: org.xml.sax.SAXParseException; lineNumber: 30; columnNumber: 1;
The exception is mybatis There is a problem in the configuration file , Check whether the label is correct , for example value and ref Need to distinguish .
Access static resources such as index.jsp When it comes to 404, The main reason is web.xml When creating a central scheduler in <url-pattern> The value of is written as "\", And there are no configuration related configurations .
The simplest is <url-pattern>*.xxx</url-pattern>.
边栏推荐
- Reading notes on how to connect the network - tcp/ip connection (II)
- C language - Introduction - Foundation - syntax - [variable, constant light, scope] (V)
- Ultimate bug finding method - two points
- Global and Chinese market of sampler 2022-2028: Research Report on technology, participants, trends, market size and share
- A subclass must use the super keyword to call the methods of its parent class
- Daughter love: frequency spectrum analysis of a piece of music
- What is permission? What is a role? What are users?
- Explanation of closures in golang
- Analysis report on the production and marketing demand and investment forecast of tellurium dioxide in the world and China Ⓣ 2022 ~ 2027
- Jianzhi offer 09 realizes queue with two stacks
猜你喜欢
Clion console output Chinese garbled code
How to batch change file extensions in win10
C语言-入门-基础-语法-数据类型(四)
2022-2028 global visual quality analyzer industry research and trend analysis report
2022-2028 global protein confectionery industry research and trend analysis report
HMS core helps baby bus show high-quality children's digital content to global developers
165 webmaster online toolbox website source code / hare online tool system v2.2.7 Chinese version
Sword finger offer 30 contains the stack of Min function
Solve the problem of "Chinese garbled MySQL fields"
2022-2028 global edible probiotic raw material industry research and trend analysis report
随机推荐
[on February 11, 2022, the latest and most fully available script library collection of the whole network, a total of 23]
Pueue data migration from '0.4.0' to '0.5.0' versions
How to batch change file extensions in win10
How should PMP learning ideas be realized?
Deadlock in channel
MySQL foundation 02 - installing MySQL in non docker version
Flutter tips: various fancy nesting of listview and pageview
C language - Introduction - Foundation - syntax - data type (4)
HMS core helps baby bus show high-quality children's digital content to global developers
C语言-入门-基础-语法-数据类型(四)
UML 时序图[通俗易懂]
Logstack configuration details -- elasticstack (elk) work notes 020
Global and Chinese markets of water heaters in Saudi Arabia 2022-2028: Research Report on technology, participants, trends, market size and share
Daughter love in lunch box
Solve the problem of "Chinese garbled MySQL fields"
Awk from getting started to digging in (11) detailed explanation of awk getline function
Langage C - démarrer - base - syntaxe - [opérateur, conversion de type] (vi)
What is permission? What is a role? What are users?
Latex download installation record
Solution to null JSON after serialization in golang