springboot project creation and development compatible with jsp and comments, detailed effective (annotations and configure two)

If this blog to give you help be honored, if there is something wrong, please correct me are farming code. Directly to the question

First, I want to declare here my personal feeling if you will ssm (spring + mybatis + springmvc), then you can in five minutes to get, if you do not it does not matter.

I personally feel springboot project is actually a management ssm projects and integration. If you use eclipse then you need to download the plug-in, so I suggest that you download directly sts (Spring Tools Suite) software. Official website to download their own

I am using this leaves sts software. Now directly on:

1: The first new (new) find Spring Starter Project (this project is to create springboot), and then click to create a springboot project.

Then you will fill out some specific information about your project. Finally, click next (you can also choose to use the default thing)

Then let you choose some maven dependencies such as finding mysql Driver are all driven from the inside to find sql from the list below, and so on, you can add what you need depend on what (according to the actual needs to add)

After creating a project, then add to complete your project which will automatically download these dependencies, and time to go pom.xml inside view. Thus Congratulations you have created a simple springboot project.

My style is a map of the project point of view, we can use the window -> view -> Navigator to modify the view mode

There are several boxes from the description so down:

The first document is a **** application.java entire project startup class, all projects need to start (remember remember) from here

This file is then added to the decentralization of resources non-Java file resources, such as storage under static and under css img js and so on temolates file is stored html interface, this folder under WEB-INF files in the project folder under similar ssm

They are protected not just access. Then the most important thing is application.properties (application.yml) files. This file can be a global springboot project profile contains a lot of information such as: configuration datasource configuration data source port number application.yml I generally get used to a configuration. The last one is dependent on the maven pom.xml dependency. If your pom.xml if and as I reported the error:

 

 Put your version number into smaller, for example 2.1.4 and so on. Another point is that you application.properties (application.yml file) The following webapp following folder you need to add something, because you are using the war package, so the need to create a folder (WEB-INFO) and then inside and put a web.xml file as before ssm on it, then what web.xml file which can not write. This project is not being given you.

For example, my web.xml file:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         version="3.0"
         xmlns="http://java.sun.com/xml/ns/javaee"
         xsi:schemaLocation="http://java.sun.com/xml/ns/javaee
    http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd">
    <display-name>myspringbootDemo</display-name>
</web-app>

 

Then he began to write a little something. Write two queries it a note of a configuration file. According to the old rules or the student table to achieve:

Let's create a directory student, and then create several packages below him (model (entity classes), dao (persistence layer), service (business layer), web (control layer)) I can see to create a directory and then start at the top of the class in fact, if you configure the scanning entity if the classes and interfaces written in a *****. application following the start of class so it will automatically help you scan. But I am willing to scan a few worry about mistakes.

 

 Then that is good on the code: entity class details of what I give you a reference item. Now say the main workflow: Then you need to create an interface dao layer. Here we must note: a lot less because you configured, then what you need is annotated. So you need to give him annotate @Mapper when creating the interface (the equivalent of projects I tell the class what is the interface): Then what normal write interface, we write two annotation method is to use a primary key query. Another is to use the form of notes written mapper.xml check all: When you use annotations queries you will need to write your comments relevant item in your above query, such as the use of (@select) removed using modified using the @Update @Delete brackets then write your sql statement how to write on how to write, with ssm project exactly the same. Business layer and control layer also using annotations for configuration (can be understood: this project is to tell the business layer, the control layer), combined with the above scanning used together.

Of course, the control layer in the only place that is not quite the same thing under normal circumstances we look at the control layer will sometimes add a comment @Controller it now more than a @RestController this annotation, the mouse will be put up when he appeared more a comment that is @ResponseBody, this means that if you use @RestController annotation, then all your approach control layer format all the data returned json string than @Controller. (Of course I personally recommend that you use @Controller, then you can add @ResponseBody in each method above), when you wrote this step, may wish to stop and control it with me to see if the same ah:

Entity classes:

package com.company.demo.student.model;

public class Student {

    private Integer id;
    private String name;
    private Integer age;
    private String sex;

    public Integer getId() {
        return id;
    }

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

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    public String getSex() {
        return sex;
    }

    public void setSex(String sex) {
        this.sex = sex;
    }

    public Student(Integer id, String name, Integer age, String sex) {
        super();
        this.id = id;
        this.name = name;
        this.age = age;
        this.sex = sex;
    }

    public Student() {
        // TODO Auto-generated constructor stub
    }

    @Override
    public String toString() {
        return "Student [id=" + id + ", name=" + name + ", age=" + age + ", sex=" + sex + "]";
    }

}

dao layer:

package com.company.demo.student.dao;

import java.util.List;

import org.apache.ibatis.annotations.Mapper;
import org.apache.ibatis.annotations.Select;

import com.company.demo.student.model.Student;

@Mapper
public interface StudentMapper {
    
    @Select("select * from student where id =#{id}")
    public Student queryById(Integer id);
    
    public List<Student> findAll();
}

Business layer interface:

package com.company.demo.student.service;

import java.util.List;

import com.company.demo.student.model.Student;


public interface StudentService {
    
    public Student queryById(Integer id);
    public List<Student> findAll();
}

Business layer implementation class:

package com.company.demo.student.service;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.company.demo.student.dao.StudentMapper;
import com.company.demo.student.model.Student;


@Service
public class StudentImpl implements StudentService{
    
    @Autowired
    private StudentMapper studentMapper;
    
    @Override
    public Student queryById(Integer id) {
        // TODO Auto-generated method stub
        Student queryById = studentMapper.queryById(id);
        return queryById;
    }

    @Override
    public List<Student> findAll() {
        // TODO Auto-generated method stub
        List<Student> findAll = studentMapper.findAll();
        return findAll;
    }
    
}

Control layer:

package com.company.demo.student.web;

import java.util.List;

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 org.springframework.web.bind.annotation.RestController;

import com.company.demo.Message.Result;
import com.company.demo.Message.ResultCode;
import com.company.demo.student.model.Student;
import com.company.demo.student.service.StudentService;

@Controller
public class StudentController {
    
    @Autowired
    private StudentService  studentService;
    
    
    @ResponseBody
    @RequestMapping("/findAll")
    public Result findAll(){
        Result result = new Result();
        List<Student> findAll = studentService.findAll();
        if(findAll!=null){
            result.setData(findAll);
            result.setResultCode(ResultCode.SUCCESS);
            return result;
        }else{
            result.setResultCode(ResultCode.RESULT_IS_NOT);
            return result;
        }
    }
    
    @ResponseBody
    @RequestMapping("/selectById")
    public Result selectById(Integer id){
        Result result = new Result();
        if(id!=null){
            Student queryById = studentService.queryById(id);
            if(queryById!=null){
                result.setData(queryById);
                result.setResultCode(ResultCode.SUCCESS);
                return result;
            }else{
                result.setResultCode(ResultCode.RESULT_IS_NOT);
                return result;
            }
        }else{
            result.setResultCode(ResultCode.PARAM_IS_BLANK);
            return result;
        }
    }
    
}

After the bin, because I simply do presentations about the return process data himself wrote two two classes as data processing class return it considered:

A first return data classes:

package com.company.demo.Message;

import com.fasterxml.jackson.annotation.JsonInclude;
import com.fasterxml.jackson.annotation.JsonInclude.Include;

@JsonInclude(Include.NON_NULL)
public class Result{
     
    private ResultCode resultCode;
    private String message;
    private Object data;
    
    public ResultCode getResultCode() {
        return resultCode;
    }
    public void setResultCode(ResultCode resultCode) {
        this.resultCode = resultCode;
    }
    
    public Result() {
        // TODO Auto-generated constructor stub
    }    

    public String getMessage() {
        return message;
    }

    public void setMessage(String message) {
        this.message = message;
    }

    public Object getData() {
        return data;
    }

    public void setData(Object data) {
        this.data = data;
    }
    
    //查询成功返回的东西
    public static Result success(Object data){
        Result result = new Result();
        result.setResultCode (ResultCode.SUCCESS); 
        result.setData (Data); 
        return Result; 
    } 
    
    // Add delete modify call after successful 
    public  static the Result Success () { 
        the Result Result = new new the Result (); 
        result.setResultCode (ResultCode.SUCCESS ); 
        return Result; 
    } 
    
    // Add call fails 
    public  static the Result failure (the ResultCode the resultCode) { 
        the Result Result = new new the Result (); 
        result.setResultCode (the resultCode); 
        return Result; 
    } 
    
    // else fails call
    //查询成功返回的东西
    public static Result success(Object data,ResultCode resultCode){
        Result result = new Result();
        result.setResultCode(resultCode);
        result.setData(data);
        return result;
    }
    
}

Second: enumeration class parameter type:

Package com.company.demo.Message; 

public  enum the ResultCode { 
    
    SUCCESS ( . 1, "successful" ), 
    ERROR ( 0, "error" ), 
    
    PARAM_IS_INVALID ( 1001, "invalid parameters" ), 
    PARAM_IS_BLANK ( 1002, "parameter is empty" ), 
    PARAM_TYPE_BIND_ERROR ( 1003, "wrong type" ), 
    PARAM_NOT_COMPLETE ( 1004, "argument is missing" ), 
    
    USER_NOT_LOGGED_IN ( 2001, "the user is not logged in, access path shall verify, log" ), 
    USER_LOGIN_ERROR ( 2002, "the account does not the presence or password is incorrect " ), 
    USER_ACCOUNT_FORBIDDEN ( 2003," the account has been disabled " ),
    USER_NOT_EXIST ( 2004, "user does not exist"), 
    USER_HAS_EXISTED ( 2005, "user already exists" ), 
    
    RESULT_IS_NOT ( 5000, "did not match the query results you want" ), 
    RESULT_OTHER_ERROR ( 9999, "did not enter the method, jump directly return" ); 
    
    
    Private Integer code;
     Private Message String; 
    
    Private the ResultCode (code Integer, String Message) {
         the this .code = code;
         the this .message = Message; 
    } 
    
    public Integer code () {
         return  the this .code; 
    } 

    public String Message () {
         return  the this .message; 
    }
    
}

Then this is the key: it is a global springboot of a simple configuration: Before I put the following resource application.properties changed application.yml format (with accustomed)

Server: 
  Port: 8085 # port number for 
  the servlet: 
   context -path: / myspringboot # from your virtual project name defined convenient and practical 
the Spring: 
  MVC: 
    View: 
      suffix: # .jsp so because some people might add jsp configuration with jsp 
      prefix: / JSP /   # so we configure the look of prefixes and suffixes in fact, under normal circumstances, should be placed in / WEB-INF / below. For convenience I will demonstrate to the directories can be accessed directly, in fact, placed there all the same,
     static -path-pattern: / static / **   # filter static resource 
  thymeleaf: #springboot support html file using thymeleaf configuration 
    Cache: false 
    encoding :. 8 UTF- 
    MODE: LEGACYHTML5 
    prefix: CLASSPATH: / Templates / 
    suffix: .html 
    Check-Template-LOCATION: to true 
  DataSource: data source configuration #
    url: jdbc: MySQL: // localhost: 3306 / = to true teststudent useUnicode & characterEncoding = utf8 & serverTimezone = UTC? 
    username: root 
    password: root 
    Driver-class-name: com.mysql.cj.jdbc.Driver # see your database driver class is six more than you? High version need to use this drive 
the mybatis: 
  Mapper-locations: the CLASSPATH *:. Xml / xml # * This position is the configuration in which the first one is the name of your new package configuration dao layer mapper.xml storage location of what is What is 
  type-aliases-package: com.ygjy.hospital.model # entity class name of the configuration 

 # configure pagehelper 
pagehelper: 
  Helper-dialect: MySQL 
  Reasonable: to true 
  Support-arguments The Methods-: to true 
  params: COUNT = countSql  

Then if you are using a jsp so you need to do two things first add servlet-dependent:

     <!--jsp页面使用jstl标签 -->
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>jstl</artifactId>
        </dependency>
        <!--用于编译jsp -->
        <dependency>
            <groupId>org.apache.tomcat.embed</groupId>
            <artifactId>tomcat-embed-jasper</artifactId>
            <scope>provided</scope>
        </dependency>

Second: go to the configuration file which is configured: because I have already set up is to configure jsp view resolution: it no longer configured.

There because we also intend to use mapper.xml: So we need to create a folder to hold: we create a new folder called xml () file in the resource file with the above application.yml :( this configuration inside echoes) . Then he added in pom.xml file: <build> </ build> tag inside: Adds After completing you can use mapper.xml files:

        <resources>
            <resource>
                <directory>src/main/java</directory>
                <includes>
                    <include>**/*.xml</include>
                </includes>
            </resource>
            <resource>
                <directory>src/main/resources</directory>
            </resource>
        </resources>            

Which you can write your mapper.xml example, I wrote a:

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE mapper
        PUBLIC "-//mybatis.org//DTD Mapper 3.0//EN"
        "http://mybatis.org/dtd/mybatis-3-mapper.dtd">
<mapper namespace="com.company.demo.student.dao.StudentMapper">
       <resultMap id="student" type="com.company.demo.student.model.Student">
    <id column="id" jdbcType="INTEGER" property="id" />
    <result column="name" jdbcType="VARCHAR" property="name" />
    <result column="age" jdbcType="INTEGER" property="age" />
    <result column="sex" jdbcType="VARCHAR" property="sex" />
  </resultMap>
    
       <!-- 搜索全部 -->
    <select id="findAll" resultMap="student">
        select * from student where 1=1;
    </select>
   
</mapper>

 

Arrived here too! In fact, your project is considered good! Now let's start the following items: Here, remember springboot project with you once said: there is a fixed startup class: Now we find the right click run as a startup class

spring boot app click the little leaves on it!

You will see the words of spring:

 

Let's take a look at the presentation of the method using annotations to open your local postman measured about Interface: give him a default parameter For example, I gave a 5 

Show results:

Because my reception function more vegetables, so we simply write a jsp it, the purpose is to verify the first two: I have to see if the configuration is successful if springboot project is compatible with jsp on the configuration was successful.

Jsp directly below the display effect. In the following we webapp to create a new package and then write a jsp interface which method to use to verify this we mapper.xml of. Look at the way mapper.xml configuration is not successful.

Directly see the effect:

Here too! Even if it is done, in fact there are a lot of things did not go into the future we will continue to have the time, such as reverse engineering tab to upload any downloaded night, but today I write to you going to write a little tired, in fact, related to ssm no difference, after We have the opportunity to continue to improve. Finally, attach the source code to you now! (Although he also joined the line of chicken dishes) people generally do not give the source of the code is not a good farmer.

Links: https://pan.baidu.com/s/1fInJe4AtSXCAlfMcFa5k6Q extraction code: maay 

 

Guess you like

Origin www.cnblogs.com/lifan666/p/springbootDemo.html