IDEA搭建Spring+SpringMVC环境 xml方式以及Java纯代码方式

本文主要介绍Idea中搭建Spring+SpringMVC过程,主要分为两种(XML、JAVA配置)方式

一、XML配置方式

首先创建一个普通的Maven项目,Maven项目创建成功后,这是一个JavaSE项目,将JavaSE项目改造成web项目;

1.在pom.xml中加入如下配置

<packaging>war</packaging>

2.选中工程,按F4快捷键,按如下图做配置

3.pom.xml中加入如下配置:

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

4.resource目录下,创建spring配置文件(applicationContext.xml)与springmvc(spring-servlet.xml)配置文件

5.配置applicationContext.xml,其中排除springmvc中的Controller注解扫描

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

    <context:component-scan base-package="com.gy" use-default-filters="true">
        <context:exclude-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
</beans>

6.配置spring-servlet.xml,其中引入SpringMVC中的Controller注解扫描

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

    <context:component-scan base-package="com.gy" use-default-filters="false">
        <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>
    </context:component-scan>
    <mvc:annotation-driven/>
</beans>

7.配置web.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">
    <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>

    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:spring-servlet.xml</param-value>
        </init-param>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

8.新建Controller与Service测试环境是否配置正确

package com.gy.controller;

import com.gy.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {
    @Autowired
    HelloService helloService;

    @GetMapping("/hello")
    public String hello(){
        return helloService.hello();
    }
}



package com.gy.service;

import org.springframework.stereotype.Service;

@Service
public class HelloService {
    public String hello(){
        return "hello world";
    }
}

9.配置Tomcat,选择Edit Configurations

 

10.启动项目,访问 http://localhost:8080/hello ,结果如下,spring+springmvc环境搭建成功

 

二、JAVA纯代码配置方式

package com.gy.config;

import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.stereotype.Controller;

@Configuration
@ComponentScan(basePackages = "com.gy",useDefaultFilters = true,excludeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Controller.class)})
public class SpringConfig {
}


package com.gy.config;

import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.gy.inter.HelloInterceptor;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.FilterType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.stereotype.Controller;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.ResourceHandlerRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurationSupport;

import java.nio.charset.Charset;
import java.util.List;

@Configuration
@ComponentScan(basePackages = "com.gy",useDefaultFilters = false,includeFilters = {@ComponentScan.Filter(type = FilterType.ANNOTATION,
        value = Controller.class),@ComponentScan.Filter(type = FilterType.ANNOTATION,value = Configuration.class)})
public class SpringMvcConfig extends WebMvcConfigurationSupport {

    /**
     * 在这里配置静态资源访问
     * @param registry
     */
    @Override
    protected void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**").addResourceLocations("/");
    }

    /**
     * 配置拦截器
     * @param registry
     */
    @Override
    protected void addInterceptors(InterceptorRegistry registry) {
        registry.addInterceptor(new HelloInterceptor()).addPathPatterns("/**");
    }

    @Override
    protected void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        converter.setDefaultCharset(Charset.forName("UTF-8"));
        FastJsonConfig config = new FastJsonConfig();
        converter.setFastJsonConfig(config);
        converters.add(converter);
    }
}


package com.gy.config;

import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;

import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;

/**
 * 这个类用来代替web.xml,在项目启动时,将自动加载这个类
 */
public class WebInit implements WebApplicationInitializer {

    /**
     * 项目启动时这个方法将会自动执行
     * @param sc
     * @throws ServletException
     */
    public void onStartup(javax.servlet.ServletContext sc) throws ServletException {
        //在这个类中手动加载springmvc
        AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
        context.register(SpringMvcConfig.class);
        context.setServletContext(sc);
        ServletRegistration.Dynamic springmvc = sc.addServlet("springmvc", new DispatcherServlet(context));
        springmvc.addMapping("/");
        springmvc.setLoadOnStartup(1);
    }
}


package com.gy.controller;

import com.gy.bean.User;
import com.gy.service.HelloService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class HelloController {

    @Autowired
    HelloService helloService;

    @GetMapping("/hi")
    public String sayHi(String name){
        return helloService.sayHi(name);
    }

    @GetMapping("/user")
    public User user(){
        User user = new User();
        user.setId(1L);
        user.setUsername("lbj");
        user.setAddr("Lakers");
        return user;
    }

}


package com.gy.inter;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class HelloInterceptor implements HandlerInterceptor {
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("preHandle");
        return true;
    }

    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        System.out.println("postHandle");
    }

    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        System.out.println("afterCompletion");
    }
}


package com.gy.bean;

public class User {
    private Long id;
    private String username;
    private String addr;

    public Long getId() {
        return id;
    }

    public void setId(Long id) {
        this.id = id;
    }

    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getAddr() {
        return addr;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }
}


<?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.gy</groupId>
    <artifactId>java_ss</artifactId>
    <version>1.0-SNAPSHOT</version>
    <packaging>war</packaging>

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

        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>

        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>fastjson</artifactId>
            <version>1.2.47</version>
        </dependency>
    </dependencies>


</project>

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
SSM是指Spring+SpringMVC+MyBatis的集成开发环境。MySQL是一个关系型数据库管理系统,用于存储和管理数据。Maven是一个项目管理和构建工具,可以自动下载所需的类库和插件,并管理项目的依赖关系。Idea是一个Java集成开发环境(IDE),提供了开发、调试和部署Java代码的工具。 在SSM MySQL Maven Idea MyBatis Spring SpringMVC的集成开发环境下,我们可以通过Maven构建项目,引入相应的依赖库。Idea提供了可视化的界面,方便我们进行开发和调试工作。 首先,我们可以使用Maven来管理项目的依赖。在pom.xml文件中添加相应的依赖,Maven会自动下载并引入到项目中。 其次,我们可以使用Idea创建Spring项目,并配置相关的配置文件。在Idea的配置界面中,我们可以设置项目的数据库连接信息和配置MyBatis的相关内容。 然后,我们可以使用MyBatis来操作MySQL数据库。在MyBatis的mapper文件中编写SQL语句,并在Spring中配置相应的bean,使其可以与数据库进行交互。 此外,我们还可以使用SpringMVC来开发Web应用。在SpringMVC中,我们可以通过配置相应的请求映射和控制器来处理请求,并返回相应的结果。 最后,通过整合SpringSpringMVC和MyBatis,我们可以实现业务逻辑与数据库的交互,并通过Maven进行项目构建和管理。这样,我们就可以在SSM MySQL Maven Idea MyBatis Spring SpringMVC的集成开发环境中进行基于这些框架和工具的开发工作了。 总之,掌握SSM MySQL Maven Idea MyBatis Spring SpringMVC的集成开发环境,意味着我们可以利用这些强大工具和框架来进行Java开发,并能够高效地开发出优质的Web应用程序。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值