当前位置:网站首页>SSM project construction

SSM project construction

2022-06-23 06:02:00 php_ kevlin

Editor :idea( The configuration has been downloaded maven and tomcat)
The idea of integration

  • .1. First, build an integrated environment
  • .2. The first Spring The configuration of is completed
  • .3. Reuse Spring Integrate SpringMVC frame
  • .4. Finally using Spring Integrate MyBatis frame

1. To configure maven
 Insert picture description here

2. New projects
 Insert picture description here
 Insert picture description here
 Insert picture description here
3. Import dependency package , File is pom.xml ( The editor will prompt )

<?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>org.example</groupId>
    <artifactId>springmvc01</artifactId>
    <version>1.0-SNAPSHOT</version>

    <packaging>war</packaging>

    <dependencies>
        <!-- spring-webmvc -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-webmvc</artifactId>
            <version>5.1.6.RELEASE</version>
        </dependency>

        <!-- jstl -->
        <dependency>
            <groupId>javax.servlet.jsp.jstl</groupId>
            <artifactId>jstl</artifactId>
            <version>1.2</version>
        </dependency>
        <dependency>
            <groupId>org.glassfish.web</groupId>
            <artifactId>jstl-impl</artifactId>
            <version>1.2</version>
        </dependency>


        <!-- servlet Compile environment  -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>3.1.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- jsp Compile environment  -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jsp-api</artifactId>
            <version>2.0</version>
            <scope>provided</scope>
        </dependency>

        <!-- FastJson -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.54</version>
        </dependency>

        <!-- pagehelper  Pagination  -->
        <dependency>
            <groupId>com.github.pagehelper</groupId>
            <artifactId>pagehelper</artifactId>
            <version>5.1.2</version>
        </dependency>


        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-context</artifactId>
            <version>5.1.16.RELEASE</version>
        </dependency>

        <!-- Spring -->
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-aspects</artifactId>
            <version>5.1.16.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-test</artifactId>
            <version>5.1.16.RELEASE</version>
        </dependency>
        <dependency>
            <groupId>org.springframework</groupId>
            <artifactId>spring-jdbc</artifactId>
            <version>5.1.16.RELEASE</version>
        </dependency>

        <!-- spring Integrate mybatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis-spring</artifactId>
            <version>1.3.1</version>
        </dependency>
        <!-- MyBatis -->
        <dependency>
            <groupId>org.mybatis</groupId>
            <artifactId>mybatis</artifactId>
            <version>3.4.5</version>
        </dependency>

        <!-- mysql Driving dependency  -->
        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.6</version>
        </dependency>
        <!--  Connection pool  -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid</artifactId>
            <version>1.1.12</version>
        </dependency>

        <!-- Junit -->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.12</version>
        </dependency>

        <!-- log4j -->
        <dependency>
        <groupId>log4j</groupId>
        <artifactId>log4j</artifactId>
        <version>1.2.17</version>
        </dependency>

        <dependency>
            <groupId>commons-logging</groupId>
            <artifactId>commons-logging</artifactId>
            <version>1.2</version>
        </dependency>






    </dependencies>

    <build>
        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
<!-- <include>*.xml</include>-->
                    <include>**/*.xml</include>
                </includes>
                <filtering>true</filtering>
            </resource>
        </resources>
    </build>

</project>

4. The essence is tomcat The directory where the web site runs , So create the following directory
 Insert picture description here
among ,web.xml The contents are as follows :

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

    <!-- SpringMVC Front controller  1. front end : Accept all requests  2. start-up springMVC factory  mvc.xml 3.springmvc Process scheduling  -->

    <servlet>
        <servlet-name>my_shine</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:mvc.xml</param-value>
        </init-param>
        <!--  Lazy loading   Hungry loading   Optional  -->
        <load-on-startup>1</load-on-startup>
    </servlet>


    <servlet-mapping>
        <servlet-name>my_shine</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>


    <!--  solve post Request Chinese garbled code filter  -->
    <!--  At this time, the filter will :request.setCharactorEncoding("utf-8"); -->
    <filter>
        <filter-name>encoding</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>encoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

    <!--  start-up spring -->
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:applicationContext.xml</param-value>
    </context-param>

</web-app>

5. stay web.xml We'll quote springmvc Configuration file for mvc.xml and spring Configuration file for applicationContext.xml, The contents are as follows :

<!--suppress ALL -->
<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/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">

    <!--  Annotation scan   scanning controller Annotations , No other scanning -->
    <context:component-scan base-package="com.qf" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--  Annotation driven  -->
    <mvc:annotation-driven>
        <!--  install FastJson, converter  -->
        <mvc:message-converters>
            <bean class="com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter">
                <!--  Declare conversion type :json -->
                <property name="supportedMediaTypes">
                    <list>
                        <value>application/json</value>
                    </list>
                </property>

                <property name="features">
                    <array value-type="com.alibaba.fastjson.serializer.SerializerFeature">
                        <!--  Avoid circular references  -->
                        <value>DisableCircularReferenceDetect</value>
                        <!--  Whether the output value is null Field of  -->
                        <value>WriteMapNullValue</value>
                        <!-- <value>QuoteFieldNames</value>-->
                         <!--  If the value field is null, Output is 0, Instead of null -->
                        <!-- <value>WriteNullNumberAsZero</value>-->
                        <!--  If the character type field is null, Output is "", Instead of null -->
                        <value>WriteNullStringAsEmpty</value>
                        <!-- List If the field is null, Output is [], Instead of null -->
                        <value>WriteNullListAsEmpty</value>
                        <!-- Boolean If the field is null, Output is false, Instead of null -->
                        <!-- <value>WriteNullBooleanAsFalse</value>-->
                    </array>
                </property>
            </bean>
        </mvc:message-converters>
    </mvc:annotation-driven>

    <!--  view resolver   effect :1. Capture the return value of the back-end controller  =“hello” 2. analysis : Before and after the return value   Splicing  ==> "hello.jsp" -->
    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <!--  Prefix  -->
        <property name="prefix" value="/"></property>
        <!--  suffix  -->
        <property name="suffix" value=".jsp"></property>
    </bean>

    <mvc:default-servlet-handler />

</beans>

6. In the last step ,mvc.xml scanning controller Annotations , stay controller Set the route and controller correspondence in , newly build ·userControlller.java·, The table of contents is shown in the figure below :

 Insert picture description here

userController.java The contents are as follows :

package com.qf.web;

import com.github.pagehelper.PageInfo;
import com.qf.bean.BaseResultBean;
import com.qf.entiry.User;
import com.qf.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.text.SimpleDateFormat;
import java.util.List;

@Controller // Declare the back-end controller 
public class UserController {
    


    @Autowired
    @Qualifier("userServiceImpl")
    private UserService userService;
    @GetMapping("/userlist")
    public ModelAndView queryUsers(HttpServletRequest request){
     //service doGet doPost
        int page = Integer.parseInt(request.getParameter("page"));
        int size = Integer.parseInt(request.getParameter("size"));
        List<User> userlists = userService.queryUsers(page,size);
        PageInfo<User> pageInfo = new PageInfo<User>(userlists);
        System.out.println("queryUsers"+userlists);
        System.out.println("pageInfo"+pageInfo);

        ModelAndView modelAndView = new ModelAndView();
        modelAndView.addObject("users",userlists
        );
        modelAndView.setViewName("user");
//
        return modelAndView;
    }

    @RequestMapping("/user")
    @ResponseBody
    public Object queryOne(Integer id)
    {
    
        System.out.println("query user id:"+id);
        List<User> user = userService.queryOne(id);
        System.out.println(user);
        return user;
    }
    @PostMapping("/update")
    public BaseResultBean updateUser(User user)
    {
    
        System.out.println("update user" + user);
        userService.updateUser(user);
        BaseResultBean baseResultBean = new BaseResultBean();
        baseResultBean.setStatus(true);
        baseResultBean.setMessage(" success ");
        return  baseResultBean;
    }

    @RequestMapping("/add")
    public BaseResultBean addUser(User user)
    {
    
        System.out.println("add user" + user);
        userService.insertUser(user);
        BaseResultBean baseResultBean = new BaseResultBean();
        baseResultBean.setStatus(true);
        baseResultBean.setMessage(" success ");
        return  baseResultBean;
    }

    @RequestMapping("/deleteuser/{id}")
    public BaseResultBean deleteUser(@PathVariable Integer id)
    {
    
        System.out.println("delete user" + id);
        userService.deleteUser(id);
        BaseResultBean baseResultBean = new BaseResultBean();
        baseResultBean.setStatus(true);
        baseResultBean.setMessage(" success ");
        return  baseResultBean;
    }


}

7. In step five spring Configuration file for applicationContext.xml As shown below

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context" xmlns:aop="http://www.springframework.org/schema/aop" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 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/context http://www.springframework.org/schema/context/spring-context.xsd http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop.xsd http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd">

    <!-- Datasource -->
    <context:property-placeholder location="classpath:jdbc.properties" />
    <bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init">
        <property name="driverClassName" value="${jdbc.driverClass}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>

        <!--  Configure the timeout time for getting connection waiting  -->
        <property name="maxWait" value="60000"/>
        <!--  To configure a   Minimum lifetime of a connection in the pool  -->
        <property name="minEvictableIdleTimeMillis" value="300000" />
    </bean>

    <!-- SqlSessionFactory -->
    <bean id="sqlSessionFactory" class="org.mybatis.spring.SqlSessionFactoryBean">
        <!--  Inject the database connection pool  -->
        <property name="dataSource" ref="dataSource"></property>
        <!--  Inject dao-mapper file information , If mapping files and dao Interface   Same package and same name , This configuration can be ignored  -->
        <property name="mapperLocations">
            <list>
                <value>classpath:com/qf/dao/*.xml</value>
            </list>
        </property>

        <!--  Automatic scanning mybatis The configuration file , Print sql journal  -->
        <property name="configLocation" value="classpath:sqlLog.xml"></property>
        <!--  scanning entity package   Use the alias   by dao-mapper Entities in the file   Define the default package path   Such as :<select id="queryAll" resultType="User">  in User Classes may not define packages  -->
        <property name="typeAliasesPackage" value="com.qf.entiry"></property>

        <!--  Pagination  -->
        <property name="plugins">
            <array>
                <bean class="com.github.pagehelper.PageInterceptor">
                    <property name="properties">
                        <props>
                            <!--  Set page number , Adjust to a reasonable value  100 page -->
                            <prop key="reasonable">true</prop>
                        </props>
                    </property>
                </bean>
            </array>
        </property>

    </bean>

<!--  Configure scan Dao Interface package , Dynamic implementation Dao Interface , Injection into ioc In the container -->
    <!-- DAO MapperScannerConfigurer -->
    <bean id="mapperScannerConfigurer9" class="org.mybatis.spring.mapper.MapperScannerConfigurer">
        <!-- dao The package where the interface is located   If there are more than one bag   It can also be separated by commas or semicolons  -->
        <property name="basePackage" value="com.qf.dao"></property>
    <!--  If there is only one factory SqlSessionFactory Of bean,  This configuration can be ignored  -->
    <!-- <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"></property>-->
    </bean>

    <!--  Read annotation position   All classes should be scanned , however controller Class not scanned  -->
    <context:component-scan base-package="com.qf" use-default-filters="true">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>

    <!--  Introduce a transaction manager , It depends on DataSource, To get a connection , Then control the transaction logic  -->
    <bean id="tx" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"></property>
    </bean>
    <!-- @Transactional -->
    <tx:annotation-driven transaction-manager="tx" />
</beans>

The road is far , Yes, it will be

8.spring.xml Will read dao layer ,service layer The following notes , The contents are as follows :
 Insert picture description here

 Insert picture description here
Don't know how , I can't write …

原网站

版权声明
本文为[php_ kevlin]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/174/202206230404414052.html