This article introduces the method of Maven to build its first Java backend. It is shared with you. The details are as follows:
1. Knowledge back
I have explained in detail in the last issue of how to use Maven to build your first project. The previous link is; today I will use SpringMvc and Mybatis frameworks to build your own Java backend.
2. Necessary preparations
①IntelliJ IDEA, Maven environment is well built
②Familiar with MyBatis, SpringMVC and other frameworks
③Creation of mysql database
3. Overall architecture layout
4. Specific steps
①Configure the jar package to use in pom.xml
<?xml version="1.0" encoding="UTF-8"?><!-- Licensed to the Apache Software Foundation (ASF) under one or more contributer license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.--><!-- $Id: pom.xml 642118 2008-03-28 08:04:16Z reinhard $ --><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/maven-v4_0_0.xsd"> <modelVersion>4.0.0</modelVersion> <packaging>war</packaging> <name>yakei</name> <groupId>com.yakei</groupId> <artifactId>yakei</artifactId> <version>1.0-SNAPSHOT</version> <dependencies> <dependency> <!--3.0 junit is used to test using programming, while junit4 is used to run junit--> <groupId>junit</groupId> <artifactId>junit</artifactId> <version>4.11</version> <scope>test</scope> </dependency> <!--Complete project dependencies--> <!--1. Log java logs include: slf4j,log4j,logback,common-logging slf4j: is the specification/interface log implementation: log4j,logback,common-logging Use: slf4j+logback --> <dependency> <groupId>org.slf4j</groupId> <artifactId>slf4j-api</artifactId> <version>1.7.12</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.1.1</version> </dependency> <!--Implement slf4j interface and integrate--> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.1.1</version> </dependency> <!--1. Database-related dependencies--> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>5.1.36</version> <scope>runtime</scope> </dependency> <dependency> <groupId>c3p0</groupId> <artifactId>c3p0</artifactId> <version>0.9.1.1</version> </dependency> <!--2.dao framework:MyBatis dependency--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis</artifactId> <version>3.3.0</version> </dependency> <!---mybatis itself implements spring integration dependency--> <dependency> <groupId>org.mybatis</groupId> <artifactId>mybatis-spring</artifactId> <version>1.2.3</version> </dependency> <!--3.Servlet web-related dependencies--> <dependency> <groupId>taglibs</groupId> <artifactId>standard</artifactId> <version>1.1.2</version> </dependency> <dependency> <groupId>jstl</groupId> <artifactId>jstl</artifactId> <version>1.2</version> </dependency> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.5.4</version> </dependency> <dependency> <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <version>3.1.0</version> </dependency> <!--4:spring dependencies--> <!--1)spring core dependencies--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-core</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-beans</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-context</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--2)spring dao layer dependencies--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-jdbc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-tx</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--3)springweb-related dependencies--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-web</artifactId> <version>4.1.7.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-webmvc</artifactId> <version>4.1.7.RELEASE</version> </dependency> <!--4)spring test-related dependencies--> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-test</artifactId> <version>4.1.7.RELEASE</version> </dependency> </dependencies></project>
It covers a series of jar packages such as Spring, mybatis, etc. This process is similar to Android adding third-party dependencies to build.gradle, and the principles are consistent.
2. Create two directories in the Resource directory: mapper, spring
mapper: mapper is a mapping of the mybatis framework, and its function is to use the mapping file in the dao layer; here I created a User.xml map:
The red part should be paid attention to. The top one is the path to map the dao layer, and the second one is the type of the return object. I will post the code here:
<!DOCTYPE mapper PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN" "http://mybatis.org/dtd/mybatis-3-mapper.dtd"><mapper namespace="com.dajiu.dao.UserDao"><!--Purpose: provide sql statement configuration for dao interface methods that are written, that is, write our sql statements for methods in dao interface--><select id="getAll" resultType="com.dajiu.bean.User"> select * from user</select><select id="getLogin" resultType="com.dajiu.bean.User"> select * from user where name = #{name} and password = #{password}</select></mapper>spring: Mainly load the configuration file of spring
1.spring-dao.xml
Post code:
<?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"> <!--Configuration integration mybatis process 1. Configure database-related parameters --> <context:property-placeholder location="classpath:jdbc.properties"/> <!--2. Database connection pool--> <bean id="dataSource"> <!--Configure connection pool properties--> <property name="driverClass" value="${driver}" /> <!-- Basic properties url, user, password --> <property name="jdbcUrl" value="${url}" /> <property name="user" value="${username}" /> <property name="password" value="${password}" /> <!--c3p0 private property--> <property name="maxPoolSize" value="30"/> <property name="minPoolSize" value="10"/> <!--Not automatically committed after closing the connection--> <property name="autoCommitOnClose" value="false"/> <!--Get connection timeout--> <property name="checkoutTimeout" value="10000"/> <!--Number of retry when the connection fails --> <property name="acquireRetryAttempts" value="2"/> </bean> <!--Convention is greater than configuration --> <!--3.Configuration of SqlSessionFactory object --> <bean id="sqlSessionFactory"> <!--Set down is the configuration that integrates mybatis and spring --> <!--Inject database connection pool --> <property name="dataSource" ref="dataSource"/> <!--Configuration of mybatis global configuration file: mybatis-config.xml--> <property name="configLocation" value="classpath:mybatis-config.xml"/> <!--Scan the entity package, use alias, use multiple names; separate --> <property name="typeAliasesPackage" value="com.dajiu.bean"/> <!--Scan the sql configuration file: the xml file required by mapper--> <property name="mapperLocations" value="classpath:mapper/*.xml"/> </bean> <!--4: Configure the scan Dao interface package, dynamically implement the DAO interface, and inject it into spring container--> <bean> <!--Inject SqlSessionFactory--> <property name="sqlSessionFactoryBeanName" value="sqlSessionFactory"/> <!-- Give the Dao interface to be scanned--> <property name="basePackage" value="com.dajiu.dao"/> </bean></beans>Places to pay attention to:
Connect to the database:
Configure the global mybatis-config and bean class, all files under mapper
Configure dao
2.spring-service.xml
Post code:
<?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" 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"> <!--Scan all types of annotations in the service package--> <context:component-scan base-package="com.dajiu.service"/> <!--Configure transaction manager--> <bean id="transactionManager"> <!--Inject database connection pool--> <property name="dataSource" ref="dataSource"/> </bean> <bean id="date"></bean> <!--Configure annotation-based declarative transactions to manage transaction behavior by default-> <tx:annotation-driven transaction-manager="transactionManager"/></beans>
Pay attention to the local area:
Configure service
3.spring-web.xml
Post code:
<?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"> <!--Configuration spring mvc--> <!--1, enable springmvc annotation mode a. Automatically register DefaultAnnotationHandlerMapping, AnnotationMethodHandlerAdapter b. By default, a series of functions are provided: data binding, format of numbers and dates@NumberFormat,@DateTimeFormat c:xml,json's default read and write support --> <mvc:annotation-driven/> <!--2. Default servlet configuration of static resources-> <!-- 1). Added static resource processing: js,gif,png 2). Allow "/" to do overall mapping-> <mvc:default-servlet-handler/> <!--3: Configure JSP to display ViewResolver--> <bean> <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/> <property name="prefix" value="/WEB-INF/view/"/> <property name="suffix" value=".jsp"/> </bean> <!--4:Scan the web-related beans--> <context:component-scan base-package="com.dajiu.controller"/> <mvc:resources mapping="/**/*.html" location="/"/> <mvc:resources mapping="/**/*.js" location="/"/> <mvc:resources mapping="/**/*.css" location="/"/> <mvc:resources mapping="/**/*.png" location="/"/> <mvc:resources mapping="/**/*.gif" location="/"/></beans>
Pay attention to the local area:
Configure controller
5. Logical implementation (taking user as an example)
①First define the user class in the bean
package com.dajiu.bean;/** * Created by zhangxing on 2017/4/7. */public class User { private int id; private String name; private String password; public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public String getPassword() { return password; } public void setPassword(String password) { this.password = password; }}② Then define the UserDao interface in dao
package com.dajiu.dao;import com.dajiu.bean.User;import org.apache.ibatis.annotations.Param;import org.springframework.stereotype.Repository;import java.util.List;/** * Created by zhangxing on 2017/4/7. */@Repositorypublic interface UserDao { List<User> getAll(); User getLogin(@Param("name") String name, @Param("password") String password);}Mapping dao layer in user.xml
③Next to declare the interface in the service
package com.dajiu.service;import com.dajiu.bean.User;import java.util.List;/** * Created by zhangxing on 2017/4/7. */public interface UserService { List<User> getAll(); User getLogin(String name,String password);}④ Then implement the interface logic in service.impl
package com.dajiu.service.impl;import com.dajiu.bean.User;import com.dajiu.dao.UserDao;import com.dajiu.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Service;import java.util.List;/** * Created by zhangxing on 2017/4/7. */@Service("UserService")public class UserServiceImpl implements UserService { @Autowired UserDao userDao; public List<User> getAll() { return userDao.getAll(); } public User getLogin(String name, String password) { return userDao.getLogin(name,password); }}@Autowired here is equivalent to creating a new instance
⑤Implement real background call logic in controller
package com.dajiu.controller;import com.dajiu.bean.User;import com.dajiu.service.UserService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.util.HashMap;import java.util.List;import java.util.Map;/** * Created by zhangxing on 2017/4/7. */@Controller@RequestMapping("/blog")public class UserController { @Autowired UserService userService; @RequestMapping("/getUser") @ResponseBody public Map<String,Object> getUser(){ Map map = new HashMap(); List<User> list = userService.getAll(); map.put("user",list); map.put("status",1); map.put("success",true); return map; } @RequestMapping("getLogin") @ResponseBody public Map<String,Object> getLogin(String name,String password){ Map map = new HashMap(); User user = userService.getLogin(name,password); map.put("user",user); map.put("isLogin",true); map.put("status",1); return map; }}Here @RequestMapping("") represents the accessed mapping path, @ResponseBody represents the request result printed in json data format, and @Controller represents that as long as the above root mapping path is accessed, the controller will be called directly;
Now let's help you understand your ideas: first request UserController--->UserService---->UserServiceImpl---->UserDao--->user.xml(mapper)---->bean(user)
6. Configure the Tomcat server
①Click the green triangle button in the upper right corner and click Edit Configuration
②Click the + sign and select Tomcat
③Select local
④Fill in the relevant configuration
⑤Click Deployment, click the + sign, and select Artifact
Then choose the first item and keep entering
In this way, your entire project will be completed, and the next step is to visit
Okay, today the explanation of springMvc and mybatis building Java backend is over.
The above is all the content of this article. I hope it will be helpful to everyone's learning and I hope everyone will support Wulin.com more.