2018 using idea to build the SSM framework (Spring+springmvc+mybatis)

Source: Internet
Author: User
Tags generator log4j

Using idea to build the SSM framework

Tools: Idea 2018.1

JDK version: jdk1.8.0_171

Maven version: apache-maven-3.5.3

Tomcat version: apache-tomcat-8.5.30

New MAVEN Project

Project Basic Display

Write the Pom.xml file and import the relevant jar package
    <dependencies> <!--Adding test classes--<dependency> &LT;GROUPID&GT;JUNIT&LT;/GROUPID&G            T <artifactId>junit</artifactId> <version>4.12</version> <scope>test< /scope> </dependency> <!--log4j--> <dependency> <groupid>log4j&        Lt;/groupid> <artifactId>log4j</artifactId> <version>1.2.17</version> </dependency> <!--springweb--> <dependency> <groupid>org.springframew Ork</groupid> <artifactId>spring-web</artifactId> <version>4.3.8.RELEASE< /version> </dependency> <!--springmvc--> <dependency> <groupId> Org.springframework</groupid> <artifactId>spring-webmvc</artifactId> &LT;VERSION&G T;4.3.7.reLease</version> </dependency> <!--Spring TX transaction---<dependency> & Lt;groupid>org.springframework</groupid> <artifactId>spring-tx</artifactId> &lt ;version>4.3.8.release</version> </dependency> <!--spring aop--> <dependency&            Gt <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> & lt;version>4.3.9.release</version> </dependency> <dependency> <groupid&gt ;org.aspectj</groupid> <artifactId>aspectjweaver</artifactId> <version>1.8.1 0</version> </dependency> <!--spring-jdbc--> <dependency> <grou Pid>org.springframework</groupid> <artifactId>spring-jdbc</artifactId> <vers Ion>4.2.5.release</version> </dependency> <!--jstl--> <dependency> <g Roupid>javax.servlet</groupid> <artifactId>jstl</artifactId> <version>1.2 </version> </dependency> <!--mybatis--> <dependency> &LT;GROUPID&G T;org.mybatis</groupid> <artifactId>mybatis</artifactId> <version>3.4.1</ Version> </dependency> <!--mybatis Reverse engineering--<dependency> <groupid&gt ;org.mybatis.generator</groupid> <artifactId>mybatis-generator-core</artifactId> & Lt;version>1.3.5</version> </dependency> <!--mybatis Spring Integration Pack--<dependency            > <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version&gT;1.3.0</version> </dependency> <!--hibernate Data Checker Pack---<dependency>            <groupId>org.hibernate</groupId> <artifactId>hibernate-validator</artifactId> <version>5.4.1.Final</version> </dependency> <!--c3p0 Link pool--<dependen            Cy> <groupId>com.mchange</groupId> <artifactId>c3p0</artifactId> <version>0.9.5.2</version> </dependency> <!--mysql database driver-<dependency&            Gt <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <v ersion>5.1.41</version> </dependency> <dependency> <groupid>org.jetbra Ins</groupid> <artifactId>annotations-java5</artifactId> <version>release&lt ;/version> </dependency> </dependencies> 
Create a variety of package packages, including:

Create the following files under the Java file:

Com.flyme.controller

Com.flyme.mapper

Com.flyme.po

Com.flyme.service

Com.flyme.service.impl

Add db.properties database configuration, and log log4j.properties configuration file

Create the following files under the resources file

Db.properties
jdbc.driver=com.mysql.jdbc.Driverjdbc.url=jdbc:mysql://localhost:3306/examination_systemjdbc.username=rootjdbc.password=root
Log4j.properties
### direct log messages to stdout ###log4j.appender.stdout=org.apache.log4j.ConsoleAppenderlog4j.appender.stdout.Target=.errlog4j.appender.stdout.layout=org.apache.log4j.PatternLayoutlog4j.appender.stdout.layout.ConversionPattern=%d{ABSOLUTE} %5p %c{1}:%L - %m%n### direct messages to file mylog.log ###log4j.appender.file=org.apache.log4j.FileAppenderlog4j.appender.file.File=../logs/mylog.loglog4j.appender.file.layout=org.apache.log4j.PatternLayoutlog4j.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=info, stdout
Add a mybatis configuration file

Create a new MyBatis folder under the resources file, and create the following file under it

Mybatis.cfg.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"><!--MyBatis主配置文件--><configuration>    <!--为java po类起类别名-->    <typeAliases>        <package name="com.flyme.po"/>    </typeAliases></configuration>
Add Spring configuration file

Create a new spring folder under the Recources file and create a new file under it

Applicationcontext-dao.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: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 http://www.springframework.org/schema/context/ Spring-context.xsd "> <!--Load Database configuration file--<context:property-placeholder location=" classpath:db.properties        "/> <!--configuration data source C3P0 connection pool--<bean id=" DataSource "class=" Com.mchange.v2.c3p0.ComboPooledDataSource ">         <property name= "Driverclass" value= "${jdbc.driver}"/> <property name= "Jdbcurl" value= "${jdbc.url}"/> <property name= "user" value= "${jdbc.username}"/> <property name= "password" value= "${jdbc.password} "/> </bean> <!--configuration Sqlsessionfactory--> <bean id= "sessionfactory" class= "Org.mybatis.spring.SqlSessionFactoryBean" > <!--loading mybatis configuration text        --<property name= "configlocation" value= "Classpath:mybatis/mybatis.cfg.xml"/> <!--data Source- <property name= "DataSource" ref= "DataSource"/> </bean> <!--mapper batch scan, scan interface from mapper packet, automatically create proxy object, and in S Pring container automatically registered with the Mybatis and Spring integration package of this Mapper scanner, Mybatis configuration file in the scanner, you can cancel out the following specifications are automatically scanned out of the Mapper Bean ID of the map Per class name (first letter lowercase)-<bean class= "Org.mybatis.spring.mapper.MapperScannerConfigurer" > <!--if you need to scan multiple reports Mapper, use half-width commas in the middle of each package--<property name= "Basepackage" value= "Com.flyme.mapper"/> <property name= "Sqlsessionfactorybeanname" value= "Sessionfactory"/> </bean></beans>
Applicationcontext-service.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: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    http://www.springframework.org/schema/context/spring-context.xsd">    <!--组件扫描,如果想要类被组件扫描,扫描到,并在Spring容器中注册的话    必须在类名上添加上注解 @Repository、@Service、@Controller、@Component (这四个注解功能一样,名字不同只是为了区分不同功能)    @Component 是通用组件    -->    <context:component-scan base-package="com.flyme.service.impl"></context:component-scan></beans>
Applicationcontext-trsaction.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" xsi:schemalocation= "Http://www.springframework.org/schema/beans http ://www.springframework.org/schema/beans/spring-beans.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP HTTP://WW W.springframework.org/schema/aop/spring-aop.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/TX/HTTP Www.springframework.org/schema/tx/spring-tx.xsd "> <bean id=" TransactionManager "class=" Org.springframework.jdbc.datasource.DataSourceTransactionManager "> <!--configuration data source-<property name="  DataSource "ref=" DataSource "></property> </bean> <!--opening annotations (notifications)--<tx:advice id=" Txadvice " Transaction-manager= "TransactionManager" > <tx:attributes>           <!--propagation behavior--<tx:method name= "save*" propagation= "REQUIRED"/> <tx:method na Me= "delete*" propagation= "REQUIRED"/> <tx:method name= "insert*" propagation= "REQUIRED"/> &L T;tx:method name= "update*" propagation= "REQUIRED"/> <tx:method name= "find*" propagation= "SUPPORTS" Read-o  Nly= "true"/> <tx:method name= "get*" propagation= "SUPPORTS" read-only= "true"/> <tx:method Name= "select*" propagation= "REQUIRED"/> </tx:attributes> </tx:advice> <!--aop--> &lt ;aop:config> <!--set Pointcuts--<aop:advisor advice-ref= "Txadvice" pointcut= "Execution (* com.flyme.ser Vice.impl.*.* (..)) " /> </aop:config></beans>
Add a SPRINGMVC configuration file

Under Resources/spring file, create a new Springmvc.xml file

Springmvc.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: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 Http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/ MVC http://www.springframework.org/schema/mvc/spring-mvc.xsd > <!--load static resources-&LT;MVC:    Default-servlet-handler/> <!--1. Component Scan, can scan controller, Service 、... and register add to spring container here Scan controller, specify controller's package--<context:component-scan base-package= "Com.flyme.contro Ller "/> <!--open annotation Callout driver-<mvc:annotation-driven/> <!--View Resolver--<bean class=" org.Springframework.web.servlet.view.InternalResourceViewResolver "> <property name=" prefix "value="/web-inf/jsp /"/> <property name=" suffix "value=". jsp "/> </bean></beans>
Re-writing the Web. xml file

Xml
<?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 "> <welcome-file-list> <welcome-fil        E>index.jsp</welcome-file> </welcome-file-list> <!--loading Spring containers--<context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/applicationconte Xt-*.xml</param-value> </context-param> <!--load Spring Listener--<listener> <listener -class>org.springframework.web.context.contextloaderlistener</listener-class> </listener> <!-- SPRINGMVC Front Controller load-<servlet> <servlet-name>springmvc</servlet-name> &LT;SERVLET-CLA Ss>org.springframework.web.servlet.dispatcherservlet</servlet-class> <!--contextconfiglocation configuration Springmvc loaded configuration files (configuration processor, mapper, etc.) if the context is not configured            Configlocation, the default load is:/web-inf/servlet name-servlet.xml (springmvc-servlet.xml)-<init-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:spring/springmvc.x Ml</param-value> </init-param> </servlet> <!--1. /* Block all JSP js PNG. CSS true full intercept recommendation does not use 2. *.action *.do intercept the request with the do action will definitely be able to use ERP 3. /intercept all (excluding JSP) (including. js. Png.css) It is strongly recommended to use front-facing consumer www.jd.com/search/release of static resources--<servlet-mappin g> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </se Rvlet-mapping> <!--Spring provides garbled filters--<filter> <filter-name>characterencodingfilter</f Ilter-name> <filter-class>org.springframework.web.filter.characterencodingfilter</filter-class> </filter> <filter-mapping> &L T;filter-name>characterencodingfilter</filter-name> <url-pattern>/*</url-pattern> </filt Er-mapping></web-app>
The SSM framework has been built, and the following tests are mybatis for reverse engineering.

Production of PO, mapper related documents, look at the picture.

How to generate by MyBatis reverse engineering, see links. Subsequent updates

Test class MyBatis Framework test

Create the package com.flyme.service below Src/test/java, where you create the Courseserviceimpltest test class to test the MyBatis framework for success.

Courseserviceimpltest.java
package com.flyme.service;import com.flyme.po.Course;import org.junit.Before;import org.junit.Test;import org.springframework.context.ApplicationContext;import org.springframework.context.support.ClassPathXmlApplicationContext;public class CourseServiceImplTest {    private ApplicationContext applicationContext;    @Before    public void setUp() throws Exception {        applicationContext = new ClassPathXmlApplicationContext(new String[]{"spring/applicationContext-dao.xml",                "spring/applicationContext-service.xml"});    }    @Test    public void findById() throws Exception {        CourseService courseService = (CourseService) applicationContext.getBean("courseServiceImpl");        Course course = courseService.findById(1);        System.out.println(course.toString());    }}

Run the FindByID () method, which appears to prove the success of the build

SPRINGMVC Framework Test Admincontroller.java

Create Admincontroller.java under the Src/main/java,com.flyme.controller package to measure the success of the SPRINGMVC framework.

package com.flyme.controller;import javax.servlet.ServletException;import javax.servlet.annotation.WebServlet;import javax.servlet.http.HttpServlet;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;@WebServlet("/myController")public class AdminController extends HttpServlet {    @Override    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        doPost(req, resp);    }    @Override    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {        String name = req.getParameter("name");        req.setAttribute("name", name);        System.out.println(name);        req.getRequestDispatcher("index.jsp").forward(req, resp);    }}
idex.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>

Run the project

Configure Tomcat

Finally select OK, you can.

Browser input http://localhost:8010/(because I changed the port number, flexible application)

Input: "I Am"

Results:

Configuration Success Issue Highlights

Welcome comments If you have questions
...

2018 using idea to build the SSM framework (Spring+springmvc+mybatis)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.