Springboot Integrated JSP and Thymeleaf (with engineering)

Source: Internet
Author: User
Tags findone

Objective

This article mainly describes Springboot integrated Jsp and springboot integration Thymeleaf, to achieve a simple user-deletion sample project. In advance, these two are separately integrated, namely two projects. If you need one, just look at the corresponding section of the introduction. If you need the project source code, you can skip to the bottom and download the project code via the link.

Springboot Integrated JSP Development preparation

Environmental requirements
JDK: 1.7 or above
SQL: MYSQL

Here we need to create a user table in MySQL to store the user's information.
The database scripts are as follows:

CREATE TABLE `t_user` (  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT '自增id',  `name` varchar(10) DEFAULT NULL COMMENT '姓名',  `age` int(2) DEFAULT NULL COMMENT '年龄',  `password` varchar(24) NOT NULL COMMENT '密码',  PRIMARY KEY (`id`)) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8

After creating a new table, we'll create the project again.
Our project is to create a common Web project through maven.
After the project is created, we need to download the appropriate jar package and then do the related development.
These jar packages we add springboot and JSP-related jars to the Pom.xml file.
related comments and written in it, here is not too much to tell. The
maven dependency is as follows:

 <dependencies> <!--Spring Boot Web-dependent core--<dependency> <groupid>org. Springframework.boot</groupid> <artifactId>spring-boot-starter-web</artifactId> </ dependency> <!--Spring Boot Hot Deploy class file is automatically restarted-<dependency> <groupid>or G.springframework.boot</groupid> <artifactId>spring-boot-devtools</artifactId> &lt ;optional>true</optional> </dependency> <!--Spring Boot Test Dependent-<depende Ncy> <groupId>org.springframework.boot</groupId> <artifactid>spring-boot-starte R-test</artifactid> <scope>test</scope> </dependency> <!--SPR            ing Boot JPA--<dependency> <groupId>org.springframework.boot</groupId> <artifactid>spriNg-boot-starter-data-jpa</artifactid> </dependency> <!--Spring boot Mybatis dependent--&        Gt <dependency> <groupId>org.mybatis.spring.boot</groupId> <artifactid>mybatis- Spring-boot-starter</artifactid> <version>${mybatis-spring-boot}</version> </depend ency> <dependency> <groupId>mysql</groupId> <artifactid>my Sql-connector-java</artifactid> </dependency> <!--Fastjson related jars--<de Pendency> <groupId>com.alibaba</groupId> <artifactid>fastjson</artifactid&gt            ;        <version>${fastjson}</version> </dependency> <!--JSP Dependency-- <!--servlet dependency.           -<dependency> <groupId>javax.servlet</groupId>   <artifactId>jstl</artifactId> </dependency> <dependency> &            Lt;groupid>javax.servlet</groupid> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> <!--tomcat support .--> <depe Ndency> <groupId>org.apache.tomcat.embed</groupId> <artifactid>tomcat-embed-jas per</artifactid> <scope>provided</scope> </dependency> </dependencies&gt ;

Once the relevant jar package has been downloaded, we will confirm the project structure.
The first is the background related package description:

src/main/javacom.pancm.web - Controller 层com.pancm.dao - 数据操作层 DAOcom.pancm.pojo- 实体类com.pancm.service - 业务逻辑层Application - 应用启动类src/main/resourcesapplication.properties - 应用配置文件,应用启动会自动读取配置

Front-end related file storage instructions:

src/main/webappWEB-INF - web.xml web相关的核心配置WEB-INF/jsp - JSP文件的存放路径

Overall engineering structure diagram:

Once the engineering structure is confirmed, we'll add the appropriate configuration.
Simply add the appropriate configuration to the application.properties .
The configuration of the data source is similar to the previous one, and it is important to note that the Jsp is related.
Because the Springboot default supported templates are Thymeleaf, we need to make the appropriate changes here.

The configuration is as follows:

?## 编码banner.charset=UTF-8server.tomcat.uri-encoding=UTF-8spring.http.encoding.charset=UTF-8spring.http.encoding.enabled=truespring.http.encoding.force=truespring.messages.encoding=UTF-8## 端口server.port=8088## 数据源spring.datasource.url=jdbc:mysql://localhost:3306/springBoot?useUnicode=true&characterEncoding=utf8spring.datasource.username=rootspring.datasource.password=123456spring.datasource.driver-class-name=com.mysql.jdbc.Driver## JSP配置# 页面默认前缀spring.mvc.view.prefix=/WEB-INF/jsp/# 响应页面默认后缀spring.mvc.view.suffix=.jsp
Code writing

In fact, the code here is basically consistent with the previous article, and the only difference is that I'm working with the JPA implementation of the database (that is, by the way, the JPA framework).

The first is the entity class, where JPA is used, so it's a little different from the previous one, adding some annotations.
Entity: Indicates that this is a physical class.
table: The name of the data table for the entity class mapping.
Column: Specifies the property of the field, nullable indicates whether it is non-null, and unique indicates whether it is unique.

Then the code for the entity class is as follows:

@Entity@Table(name = "t_user")public class User {         /** 编号 */     @Id     @GeneratedValue     private Long id;     /** 姓名 */     @Column(nullable = false, unique = true)     private String name;     /** 密码*/     @Column(nullable = false)     private String password;     /** 年龄 */     @Column(nullable = false)     private Integer age;        //getter和setter略}    

Because the Jpa,dao layer is used only to inherit the Jparepository class, you need to specify the entity class and the primary key type.
The DAO layer code is as follows:

@Mapperpublic interface UserDao extends JpaRepository<User, Long>{    }

Business layer this block and before the call can, although the use of JPA, but the method is very simple, new and modified with Save, delete is Delete,findone is through the ID lookup, FindAll is query all and so on.

The services code is as follows:

@Servicepublic class Userserviceimpl implements UserService {@Autowired private Userdao Userdao;        @Override public boolean addUser (user user) {Boolean flag=false;            try{userdao.save (user);        Flag=true;            }catch (Exception e) {System.out.println ("New failed!");        E.printstacktrace ();    } return flag;        } @Override public boolean updateUser (user user) {Boolean flag=false;            try{userdao.save (user);        Flag=true;            }catch (Exception e) {System.out.println ("Modification failed!");        E.printstacktrace ();    } return flag;        } @Override public Boolean deleteuser (Long ID) {Boolean flag=false;            try{userdao.delete (ID);        Flag=true;            }catch (Exception e) {System.out.println ("Delete failed!");        E.printstacktrace ();    } return flag; } @Override Public User Finduserbyid (Long ID){return userdao.findone (ID);    } @Override Public list<user> findAll () {return userdao.findall (); }}

To the control layer, this provides or provides an interface to the JSP to call, but here the class annotations can not use the previous Restcontroller this annotation, this annotation in the format of JSON return data, but we sometimes return when we need to jump interface, So the Controller should use this annotation. If the data format that you want to return in a method is JSON, add the responsebody annotation to the method.

The control layer code is as follows:

@Controllerpublic class Userrestcontroller {@Autowired private userservice userservice;        @RequestMapping ("/hello") public String Hello () {return "Hello";        @RequestMapping ("/") public String Index () {return "redirect:/list"; } @RequestMapping ("/list") public String list (model model) {SYSTEM.OUT.PRINTLN ("            Query All ");            List<user> Users=userservice.findall ();            Model.addattribute ("Users", users);        return "User/list";        } @RequestMapping ("/toadd") public String Toadd () {return "User/useradd";            } @RequestMapping ("/add") public String Add (user user) {userservice.adduser (user);        return "Redirect:/list"; } @RequestMapping ("/toedit") public String Toedit (Model model,long id) {User user=userservice.fi            Nduserbyid (ID); Model.AddAttribute ("user", user);        return "User/useredit";            } @RequestMapping ("/edit") public String edit (user user) {userservice.updateuser (user);        return "Redirect:/list";            } @RequestMapping ("/todelete") public String Delete (Long id) {userservice.deleteuser (ID);        return "Redirect:/list"; }}
Functional Testing

Back-end code introduced here, as far as the front-end JSP code is not more said (the main reason is that the interface is too ugly to write ...) ), we start the project directly to see the effect.
Start the project and enter it on the browser: http://localhost:8088/list
Main interface:

Add a piece of data after the interface:

Other modifications and deletions can also be achieved, here in one by one does not map.
Springboot integrated JSP to this end.

Sringboot Integrated Thymeleaf

The project reference: http://www.ityouknow.com/springboot/2017/09/23/spring-boot-jpa-thymeleaf-curd.html

Thymeleaf Introduction

Thymeleaf is a template engine that can be used for web and non-Web applications, it can xml/xhtml/html5, JavaScript, CSS, and even text files.

Use of Thymeleaf

Thymeleaf this piece of personal use is not very skilled, this is not the main content of this article, detailed can view the official documents.
Https://www.thymeleaf.org/documentation.html

Development preparation

The basic and the above Sringboot integration JSP is similar, here will not repeat.

Because the Springboot default template engine is Thymeleaf, Maven relies on this block only to add thymeleaf dependencies on the original Springboot project.

  <dependency>            <groupId>org.springframework.boot</groupId>            <artifactId>spring-boot-starter-thymeleaf</artifactId> </dependency>

application.properties Configuration of this block, and the previous project can be basically consistent with the need to note that only the spring.thymeleaf.cache configuration, When false, the Thymeleaf cache is turned off, and the interface is automatically restarted and then takes effect.

Sringboot Integration Thymeleaf and Sringboot integrated JSP has a big difference is that the Thymeleaf resource file is placed in the src/main/resources directory, JSP is placed in src/ The Main/webapp directory. In the resources directory, the static directory is used to place content such as CSS, JS, jpg pictures and so on. The templates directory is used to place the page template used by the project, which is the . html file.

Its project structure is shown below:

The code basically and Sringboot integration JSP consistent, here is not to repeat.

Functional Testing

Start the project in browser input: http://localhost:8085
Main interface:

After modifying the user data:

Other functions are also possible, and there is no more mapping.
Springboot integration Thymeleaf to this end.

Other

About Springboot integration JSP and Thymeleaf here is the end.
Springboot Integrated JSP Project Engineering address:
Https://github.com/xuwujing/springBoot-study/tree/master/springboot-jsp-jpa
Springboot Integrated Thymeleaf Project Engineering address:
Https://github.com/xuwujing/springBoot-study/tree/master/springboot-thymeleaf

Original is not easy, if feel good, hope to give a recommendation! Your support is my greatest motivation for writing!
Copyright Notice:
Empty Realm
Blog Park Source: http://www.cnblogs.com/xuwujing
CSDN Source: HTTP://BLOG.CSDN.NET/QAZWSXPCM
Personal blog Source: http://www.panchengming.com

Springboot Integrated JSP and Thymeleaf (with engineering)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.