Integrating SSM's Demo

Article catalog 1. Version selection 2. Using maven to create a project (project structure) image-20200626115714873 3.p...
Configuration files for spring( applicationContext.xml)
springmvc-config.xml
mybatis-config.xml
jdbc.properties
log4j.properties
mapper/mapper.xml
web.xml
page
controller
Mapper
service
entity

Article catalog

1. Version selection
<!--Unified management version--> <spring.version>5.2.1.RELEASE</spring.version> <aspectjweaver.version>1.9.4</aspectjweaver.version> <aopalliance.version>1.0</aopalliance.version> <mybatis.version>3.5.3</mybatis.version> <mybatis-spring.version>2.0.1</mybatis-spring.version> <mysql-connector-java.version>5.1.32</mysql-connector-java.version> <jackson.version>2.9.10</jackson.version> <slf4j.version>1.7.25</slf4j.version> <log4j.version>1.2.17</log4j.version> <java.version>1.8</java.version>
2. Using maven to create a project (project structure) 3.pom.xml
<dependencies> <!-- Begin: spring rely on --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>$</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>$</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>$</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>$</version> </dependency> <!-- End: spring rely on --> <!-- START Spring AOP--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>$</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>$</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>$</version> </dependency> <dependency> <groupId>aopalliance</groupId> <artifactId>aopalliance</artifactId> <version>$</version> </dependency> <!-- END Spring AOP--> <!-- Begin: springmvc rely on --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>$</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>$</version> </dependency> <!-- End: springmvc rely on --> <!-- Begin: mybatis rely on --> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>$</version> </dependency> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>$</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>$</version> </dependency> <!-- End: mybatis rely on --> <!--START : jackson--> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-core</artifactId> <version>$</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>$</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-annotations</artifactId> <version>$</version> </dependency> <!--END : jackson--> <!-- START log4j Log file management package--> <!-- http://php-note.com/article/1111.html --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>$</version> </dependency> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-log4j12</artifactId> <version>$</version> </dependency> <dependency> <groupId>log4j</groupId> <artifactId>log4j</artifactId> <version>$</version> </dependency> <!--END log4j--> <!--junit package--> <dependency> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <dependency> <groupId>org.junit.jupiter</groupId> <artifactId>junit-jupiter-api</artifactId> <version>RELEASE</version> <scope>compile</scope> </dependency> </dependencies>
4. Configuration file (under resources)

Configuration files for spring( applicationContext.xml)

  • Annotation scanning configuration of spring's bean

  • Configuration of mybatis

    1) Data source (Note: key value pair in configuration file, key usage jdbc.driver Form)

    2) Starting alias (for mapper.xml Convenient parameter transfer / return value)

    3) Scanning mapper.xml

    4) Scanning mapper.java dao

  • Configuration of transactions

  • At web.xml Load in

<?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:tx="http://www.springframework.org/schema/tx" xmlns:aop="http://www.springframework.org/schema/aop" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.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 "> <!--1.open bean Annotation scan,adopt package How --> <context:component-scan base-package="com.yuan.service"/> <!--2. mybatis Related configuration: 1)data source 2)Starting alias 3)scanning mapper.xml (Scan by package) 4)scanning mapper.java Namely dao --> <!--Configure data sources--> <!--Load profile first--> <context:property-placeholder location="classpath:jdbc.properties"/> <bean id="dataSource"> <property name="driverClassName" value="$"/> <property name="url" value="$"/> <property name="username" value="$"/> <property name="password" value="$"/> </bean> <!--conduct mybatis SqlSessionFactoryBean Related configuration of --> <bean id="sessionFactoryBean"> <property name="dataSource" ref="dataSource"/> <!--mybatis Profile for--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!--Take alias to facilitate parameter passing and specified return value--> <property name="typeAliasesPackage" value="com.yuan.entity"/> <!--scanning mapper.xml position--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!--mybatis and spring Consolidation configuration, Scan all dao --> <bean id="mapperScannerConfigurer"> <!-- https://www.jb51.net/article/110729.htm https://blog.csdn.net/weixin_44678295/article/details/91472284 --> <property name="sqlSessionFactoryBeanName" value="sessionFactoryBean"/> <property name="basePackage" value="com.yuan.dao"/> </bean> <!-- START->END This configuration has not been used,I don't know what it means for the time being --> <!--START START START START START START START--> <!-- send AOP Note effective,Note out before use --> <!--<aop:aspectj-autoproxy/>--> <!--open jdbc Transaction manager --> <bean id="transactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- Configure transactions, specify which methods require transactions, and configure the propagation behavior and isolation level of transactions--> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="get*" read-only="true"/> <tx:method name="save*" propagation="REQUIRED"/> <tx:method name="update*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="delete*" propagation="REQUIRED" rollback-for="Exception"/> <tx:method name="*" propagation="NOT_SUPPORTED"/> </tx:attributes> </tx:advice> <!-- Configuration entry point--> <aop:config> <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.yuan.service.impl..*.*(..))"/> </aop:config> <!-- Enable transaction annotation --> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> <!--END END END END END END END END END END END END END END END--> <!--springmvc The configuration of is placed in its own configuration file--> </beans>

springmvc-config.xml

  • Scan Controller comments
  • view resolver
  • jackson (used to transform json data)
  • The relevant dispatcher servlet is in the web.xml Medium configuration
  • At web.xml Load in
<?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:mvc="http://www.springframework.org/schema/mvc" 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/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 "> <!-- springmvc Things to configure 1)scanning controller Annotated package 2)Configure view resolver 3)to configure jackson ,For parsing json data --> <context:component-scan base-package="com.yuan.controller"/> <!--https://www.cnblogs.com/escctrl22222/p/11362656.html--> <mvc:annotation-driven/> <!--to configure springmvc view resolver --> <bean> <property name="prefix" value="/WEB-INF/views/"/> <property name="suffix" value=".jsp"/> </bean> <!--jackson to configure--> <bean> <property name="messageConverters"> <bean></bean> </property> </bean> </beans>

mybatis-config.xml

  • Configuration moved to spring's profile applicationContext.xml Yes
  • At applicationContext.xml But there is no configuration here. They all move to the spring configuration file applicationContext.xml Yes
<?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> <!--&lt;!&ndash;These configurations are transferred to spring Profile for applicationContext.xml Yes, adopt org.mybatis.spring.SqlSessionFactoryBean to configure &ndash;&gt; &lt;!&ndash;Load profile&ndash;&gt; <properties resource=""></properties> &lt;!&ndash;Starting alias&ndash;&gt; <typeAliases> <package name=""/> </typeAliases> &lt;!&ndash;Configure data sources&ndash;&gt; <environments default=""> <environment id=""> <transactionManager type=""></transactionManager> <dataSource type=""></dataSource> </environment> </environments> &lt;!&ndash;Configure scan mapper.xml&ndash;&gt; <mappers> <package name=""/> </mappers>--> </configuration>

jdbc.properties

jdbc.driver=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://localhost:3306/mybatis_day01?useUnicode=true&amp;characterEncoding=utf8 jdbc.username=root jdbc.password=Enter your own password

log4j.properties

# Global logging configuration log4j.rootLogger=DEBUG, stdout # Console output... log4j.appender.stdout=org.apache.log4j.ConsoleAppender log4j.appender.stdout.layout=org.apache.log4j.PatternLayout log4j.appender.stdout.layout.ConversionPattern=%5p [%t] - %m%n

mapper/mapper.xml

  • Will mapper.xml Reasons for putting it under resources
  • https://blog.csdn.net/xingxiupaioxue/article/details/77854288
  • In addition to the method mentioned in the blog, it is to directly mapper.xml File under resources

web.xml

  • Configuring listeners and loading configuration files for spring applicationContext.xml
  • Configure request forwarding for spring MVC dispatcher servlet and load spring MVC- config.xml configuration file
  • Configure filter to solve the problem of 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_3_1.xsd" version="3.1"> <!-- 1)Load profile-> spring Profile for 2)to configure spring monitor 3)to configure springmvc Of DispatcherServlet (include springmvc Loading configuration files) ,Forward request 4)Configure filters,Solve the problem of garbled code --> <!--load spring Profile for applicationContext.xml --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param> <!-- spring monitor https://www.jianshu.com/p/523bfddf0810 https://blog.csdn.net/lkforce/article/details/81781031 --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!--to configure springmvc Of DispatcherServlet --> <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:springmvc-config.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>dispatcherServlet</servlet-name> <url-pattern>*.do</url-pattern> </servlet-mapping> <!--Filter to solve the problem of garbled code--> <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> </web-app>
5. Testing
  • Write a Controller +jsp to test spring MVC (including jsckson)
  • Call the service method in the Controller, and the service calls dao
  • Code cloud address -->Learning with code

page

user.jsp

  • Through localhost/user/login.do Access, set the virtual directory to /, port 80
<%-- Created by IntelliJ IDEA. User: yuan Date: 2020-06-25 Time: 21:33 To change this template use File | Settings | File Templates. --%> <%@ page contentType="text/html;charset=UTF-8" language="java" %> <html> <head> <title>Title</title> <script src="$/js/jquery-1.8.3.js"></script> </head> <body> $<br> //User name: < input type = "text" name = "pname" id = "pname" / > < br > //Password: < input type = "password" name = "password" id = "password" / > < br > //Age: < input type = "text" name = "page" id = "page" > < br > <input type="button" value="test" οnclick="testJson()" /> <script> function testJson() { //Get the input value pname as id alert($("#pname").val()); var pname = $("#pname").val(); var password = $("#password").val(); var page = $("#page").val(); console.log("$/user/send.do"); var temp = JSON.stringify({ "pname" : pname, password : password, page : page }); console.log("json:"+temp); /* pname Can be quoted or not "pname":pname json:{"pname":"11","password":"22","page":"33"}*/ $.ajax({ //Request path url : "$/user/send.do", //Request type type : "post", //Data indicates the data sent data : JSON.stringify({ pname : pname, password : password, page : page }), //Define the data format of sending request as JSON string contentType : "application/json;charset=utf-8", //The data format of the defined callback response is JSON string, which can be omitted dataType : "json", //Results of successful response success : function(data) { if (data != null) { alert("User name entered:" + data.pname + ",password:" + data.password + ", Age:" + data.page); } } }); } </script> </body> </html>

controller

UserLoginController.java

package com.yuan.controller; import com.yuan.dao.UserMapper; import com.yuan.entity.Person; import com.yuan.service.IUserService; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.RequestBody; import org.springframework.web.bind.annotation.RequestMapping; import org.springframework.web.bind.annotation.ResponseBody; import org.springframework.web.servlet.ModelAndView; @Controller @RequestMapping("/user") public class UserLoginController { @Autowired private IUserService userService; @Autowired private UserMapper userMapper; @RequestMapping("/login") public ModelAndView login(ModelAndView modelAndView){ System.out.println("login"); modelAndView = new ModelAndView("/user"); modelAndView.addObject("username","yuan Yuan"); return modelAndView; } @RequestMapping("send") @ResponseBody public Person receiveJson(@RequestBody Person person){ //Method to call service userService.findUser(); System.out.println("-----------"); System.out.println("receive json date"); System.out.println(person); return person; } }

Mapper

UserMapper.java

package com.yuan.dao; import com.yuan.entity.User; public interface UserMapper { public User findUserById(int id); }

UserMapper.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"> <!--Namespace to use full name, alias is to parameterType and resultType Used --> <mapper namespace="com.yuan.dao.UserMapper"> <select id="findUserById" parameterType="int" resultType="user"> select * from user where id = # </select> </mapper>

service

UserServiceImpl.java

package com.yuan.service.impl; import com.yuan.dao.UserMapper; import com.yuan.entity.User; import com.yuan.service.IUserService; 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.junit.jupiter.api.Test; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import java.io.IOException; import java.io.InputStream; @Service public class UserServiceImpl implements IUserService { @Autowired private UserMapper userMapper; @Override public void findUser() { System.out.println("find user"); User user = userMapper.findUserById(1); System.out.println(user); System.out.println(user.getUsername()); System.out.println("findUser Method end, pass test"); } }

entity

Person.java

package com.yuan.entity; public class Person { private String pname; private String password; private Integer page; public Person() { } public String getPname() { return pname; } public void setPname(String pname) { this.pname = pname; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; } public Integer getPage() { return page; } public void setPage(Integer page) { this.page = page; } }

User.java

package com.yuan.entity; import java.util.Date; public class User { private int id; private String username; private String sex; private Date birthday; private String address; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String getSex() { return sex; } public void setSex(String sex) { this.sex = sex; } public Date getBirthday() { return birthday; } public void setBirthday(Date birthday) { this.birthday = birthday; } public String getAddress() { return address; } public void setAddress(String address) { this.address = address; } }
6. References

SSM three framework series: Spring 5 + Spring MVC 5 + MyBatis 3.5 integration (source code attached)

An SSMDemo on the code cloud

"Access denied for user..."

26 June 2020, 01:06 | Views: 1912

Add new comment

For adding a comment, please log in
or create account

0 comments