spring Quick Start

Application start spring

Creating app project

Create a java application project, set up the directory structure:

+ lib/
+ src/
    - beans.xml
    - Message.java
    - Main.java

beans.xmlFile name can be followed by passing xml to name ApplicationContextthe class find.

Add Library

Start with the official website to download spring library: https: //repo.spring.io/release/org/springframework/spring/

Use ide add (add as library) the following commonly used to spring the library (aop, aspects is required when using the section):

  • core
  • context
  • beans
  • expression
  • aop
  • aspects

Since the spring needs common logging library official website to download: http: //commons.apache.org/proper/commons-logging/download_logging.cgi

Add to ide in:

  • common logging

Code

Add java class as a bean.

// src/Message.java
public class Message {
    private String msg;

    public String getMsg() {
        return msg;
    }

    public void setMsg(String msg) {
        this.msg = "this mssage is : " + msg;
    }

}

Add xml files, configuration bean.

<!--src/beans.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
       http://www.springframework.org/schema/beans/spring-beans-3.0.xsd">

    <bean id="msg1" class="Message">
        <property name="msg" value="hello world"/>
    </bean>

</beans>

Add java class, as the main class, the xml configuration file, acquired bean.

// src/Main.java
import org.springframework.context.ApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;

public class Main {

    public static void main(String[] args){
        ApplicationContext context = new ClassPathXmlApplicationContext("beans.xml");
        Message msg = (Message) context.getBean("msg1");
        System.out.println(msg.getMsg());
    }
}

Run the main class.


Spring start page

Create a web project

Directly idea to create a web project wizard, can reduce some idea of ​​the configuration, it is not necessary to learn the cost.

New Project -> Java Enterprise -> Web Application

Spring can also be directly selected in the configuration, it will automatically download the configuration better spring libraries needed.

Directory Structure:

+ lib/
+ src/
    + main/
        + java/
            + com/
                + yww/
                    - HomeController.java
+ web/
    + WEB-INF/
        + jsp/
            - home.jsp
        - applicationContext.xml
        - dispatcher-servlet.xml
        - web.xml
    - index.jsp

com.yww.HomeController.javaIs the controller of his own creation, when do the project, should be attributed to a controller folder easy to manage.
applicationContext.xmlFile is not necessary, I can web.xmlnot want to remove this section <context-param>.
applicationContext.xmlYou can configure file bean, because the web.xmlfile <context-param>configuration label this a good document, it does not have to be like the previous app project using ClassPathXmlApplicationContexta series of context retrieved bean的xml配置文件, go get bean.

Add Library

In order to use java ee, you need to install the idea Enterprise Edition.

Compared to applications, web pages need to add the web, webmvc library.

Add the library to the lib folder:

  • common logging
  • core
  • context
  • beans
  • expression
  • aop
  • aspects
  • web
  • webmvc

Select all libraries, right add as library.

Configuration

  • Set code path: File -> Project Structure -> Modules -> Right select the project path src / main / java /, select Sources.

  • 配置输出:File -> Project Structure -> Artifacts -> + -> Web Application:Exploded -> From Modules...

  • Fix the problem (add lib when packaging): File -> Project Structure -> Problems -> Fix, it will automatically add repaired.

  • To directly run the debugger in the idea, the idea of ​​the configuration tomcat: Run -> Edit Configurations ... -> + -> Tomcat Server -> local -> Application server the Configure ... -> Tomcat_Home choose to download the Tomcat directory .

  • The web.xmlmedium <url-pattern>*.form</url-pattern>was changed <url-pattern>/</url-pattern>, otherwise it will intercept *.formthe end of the request.

If you need to deploy to tomcat on your own server, you need to configure packaged as a war configuration.

  • Packing war Configuration: File -> Project Structure -> Artifacts -> + -> Web Application: Archive -> From 'xxx', packed into Exploded from the previous war.
  • 打包war:Build -> Build Artifacts... -> xxx archive -> build。

In Project Structure-> Artifactstime configuration, create Web Application:Exploded(as can be generated from Modules in), then create Web Application:Archive(as can be generated directly from Exploded in).

Code

tomcat web.xml reads configuration, which includes a servlet spring DispatcherServlet path processing.

<!-- web/WEB-INF/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>/WEB-INF/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
    <servlet>
        <servlet-name>dispatcher</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>dispatcher</servlet-name>
<!--        <url-pattern>*.form</url-pattern>-->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

Configuration, the scanning assembly open, view view parser configured prefix and suffix.

<!-- web/WEB-INF/dispatcher-servlet.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">

    <context:component-scan base-package="com.yww"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>

</beans>

applicationContext.xml without any configuration.

Controller, mapping the path setting request, the returned string rendered view name, spring automatically using the xml configuration specified above after adding the suffix .jsp, jsp find matching documents (as at home.jsp).

// src/main/java/com/yww/HomeController.java
package com.yww;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

@Controller
@RequestMapping("/home")
public class HomeController {
    @RequestMapping(method = RequestMethod.GET)
    public String printHome(ModelMap model){
        model.addAttribute("msg", "this is a page!");

        return "home";
    }
}

Render view for matches of the view by the controller returns a string.

<!-- web/WEB-INF/jsp/home.jsp -->
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
    <h1>${msg}<h1>
</body>
</html>

run

Configuring the idea of ​​tomcat configuration, you can click on the Run button Run, type in the browser: http: // localhost: 8080 / or http: // localhost: 8080 / home, to see.

Or configure the pack war, war on first tomcat目录/webapps/down, and then manually run tomcat目录/bin/startup.shstart tomcat, tomcat will automatically deploy the web application, the last point your browser to: http: // localhost: 8080 / .


Maven Quick Start

Create a maven of spring items

Download Maven, use the command to create a webapp:

mvn archetype:generate -DarchetypeArtactId="maven-archetype-webapp" -DarchetypeGroupId="org.apache.maven.archetypes" -DarchetypeVersion="1.4"

Directory Structure:

+ src/
    + main/
        + java/
            + com/
                + yww/
                    - HomeController.java
                    - Message.java
        + resources/
        + webapp/
            + WEB-INF/
                + jsp/
                    - home.jsp
            - applicationContext.xml
            - dispatcher-servlet.xml
            - web.xml
        - index.jsp
- pom.xml

Code

Other files are not the same as using maven project management, but the directory structure is different.

It is a maven pom.xml configuration file.

<!-- pom.xml -->
<?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.yww</groupId>
  <artifactId>demo</artifactId>
  <version>1.0-SNAPSHOT</version>
  <packaging>war</packaging>

  <name>demo Maven Webapp</name>
  <!-- FIXME change it to the project's website -->
  <url>http://www.example.com</url>

  <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>commons-logging</groupId>
      <artifactId>commons-logging</artifactId>
      <version>1.2</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-core</artifactId>
      <version>5.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-context</artifactId>
      <version>5.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-beans</artifactId>
      <version>5.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-expression</artifactId>
      <version>5.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aop</artifactId>
      <version>5.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-aspects</artifactId>
      <version>5.2.0.RELEASE</version>
    </dependency>

    <dependency>
      <groupId>org.springframework</groupId>
      <artifactId>spring-web</artifactId>
      <version>5.2.0.RELEASE</version>
    </dependency>

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

    <dependency>
      <groupId>junit</groupId>
      <artifactId>junit</artifactId>
      <version>4.11</version>
      <scope>test</scope>
    </dependency>
  </dependencies>

</project>

Here will be <build>all <plugin>deleted, it can also be packaged properly to build the project.

Configuration bean, the Messagebean class into the com/yww/directory, bean configuration files applicationContext.xml.

<!-- src/main/webapp/WEB-INF/applicationContext.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"
       xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd">

    <bean id="msg1" class="Message">
        <property name="msg" value="hello world"/>
    </bean>

</beans>

Bean.xml different profiles with the previous, where the need to use qualified names.

web.xmlConfiguration file with before.

The controller acquires bean (automatic connection requires Autowired guide package).

package com.yww;

import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.beans.factory.annotation.Autowired;

@Controller
@RequestMapping("/home")
public class HomeController {

    @Autowired
    public Message msg1;

    @RequestMapping(method = RequestMethod.GET)
    public String printHome(ModelMap model){
        String str1 = msg1.getMsg();
        model.addAttribute("msg", "this is a page! gradle " + str1);

        return "home";
    }
}

Packaging run

In the pom.xml the same directory, use the command to download dependencies and then packaged into war:

mvn install

The target/directory of the war file into the tomcat/webapps/run.


Gradle Quick Start

Create a directory structure gradle

Download Gradle, execute the command to create a web project:

gradle init

Directory Structure:

+ src/
    + main/
        + java/
            + com/
                + yww/
                    - HomeController.java
                    - Message.java
        + resources/
        + webapp/
            + WEB-INF/
                + jsp/
                    - home.jsp
            - applicationContext.xml
            - dispatcher-servlet.xml
            - web.xml
        - index.jsp
- build.gradle

Code

The code is not the same as those listed on.

build.gradle is gradle project management profiles.

// build.gradle
plugins {
    id 'java'
    id 'war'
}

group = 'com.yww'
version = '0.0.1-SNAPSHOT'
sourceCompatibility = 1.8
targetCompatibility = 1.8

ext{
    springVersion = '5.2.0.RELEASE'
}

repositories {
    mavenCentral()
}

dependencies {
    compile "org.springframework:spring-core:$springVersion"
    compile "org.springframework:spring-context:$springVersion"
    compile "org.springframework:spring-beans:$springVersion"
    compile "org.springframework:spring-expression:$springVersion"
    compile "org.springframework:spring-aop:$springVersion"
    compile "org.springframework:spring-aspects:$springVersion"
    compile "org.springframework:spring-web:$springVersion"
    compile "org.springframework:spring-webmvc:$springVersion"

    testCompile "junit:junit:4.12"
    compile "org.springframework:spring-jdbc:$springVersion"
    compile group: 'mysql', name: 'mysql-connector-java', version: '8.0.15'
}

Packaging run

In the build.gradle the same directory, execute the command building packed war:

gradle build

The build/lib/directory of warthe file into the tomcat run.


Guess you like

Origin www.cnblogs.com/maplesnow/p/11619716.html
Recommended