preface

This article mainly tells about SpringBoot integration Jsp and SpringBoot integration Thymeleaf, to achieve a simple user add, delete, change the example project. To be clear, there are three projects, two integrated individually and one integrated together. If you need one of these, just look at the corresponding section. If you need the project source code, you can go to the bottom and download the project code from the link.

Jsp SpringBoot integration

The development of preparation

Environment Requirements JDK: 1.7 or later SQL: MySql

Mysql > create a user table to store user information. The database script is as follows:

CREATE TABLE `t_user` (
  `id` int(11) NOT NULL AUTO_INCREMENT COMMENT 'on the id',
  `name` varchar(10) DEFAULT NULL COMMENT 'name',
  `age` int(2) DEFAULT NULL COMMENT 'age',
  `password` varchar(24) NOT NULL COMMENT 'password',
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=17 DEFAULT CHARSET=utf8
Copy the code

Once the table is created, let’s create the project. Our project is to create a normal Web project using Maven. Once the project is created, we need to download the corresponding JAR package and proceed with the development. We can add the springBoot and Jsp related jars to the POM.xml file. Related notes and written in it, I will not talk too much here. Maven has the following dependencies:

<dependencies> <! <dependency> <groupId>org.springframework. Boot </groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <! <dependency> <groupId>org.springframework. Boot </groupId> <artifactId>spring-boot-devtools</artifactId> <optional>true</optional> </dependency> <! --> <dependency> <groupId>org.springframework. Boot </groupId> <artifactId>spring-boot-starter-test</artifactId> <scope>test</scope> </dependency> <! -- Spring Boot JPA --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-jpa</artifactId> </dependency> <! <dependency> <groupId>org.mybatis. Boot </groupId> <artifactId>mybatis-spring-boot-starter</artifactId> <version>${mybatis-spring-boot}</version> </dependency> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> </dependency> <! Alibaba </groupId> <artifactId>fastjson</artifactId> <version>${fastjson}</version> </dependency> <! --JSP dependencies --> <! Javax. servlet</ artifactId> </artifactId> </dependency> <dependency>  <groupId>javax.servlet</groupId> <artifactId>javax.servlet-api</artifactId> <scope>provided</scope> </dependency> <! --> <dependency> <groupId>org.apache.tomcat.embed</groupId> <artifactId>tomcat-embed-jasper</artifactId> <scope>provided</scope> </dependency> </dependencies>Copy the code

After the relevant Jar package is downloaded, we will confirm the engineering structure of the project. First is the background related package description:

Dao com.pancm.pojo- Entity class com.pancm.service - Business logic layer Application - Application startup class SRC /main/resources application.properties - Application configuration file, which is automatically read when the Application startsCopy the code

Storage instructions of front-end related files:

SRC /main/webapp web-INF-web. XML Web-related core configuration web-INF/jsp-jsp file pathCopy the code

Overall engineering structure drawing:

After the engineering structure is confirmed, we will add the corresponding configuration. Simply add the appropriate configuration in application.properties. The configuration of the data source is pretty much the same as before, but note the configuration of the Jsp. Since springBoot’s default supported template is Thymeleaf, we need to change it accordingly.

The configuration is as follows:

# # code
banner.charset=UTF-8
server.tomcat.uri-encoding=UTF-8
spring.http.encoding.charset=UTF-8
spring.http.encoding.enabled=true
spring.http.encoding.force=true
spring.messages.encoding=UTF-8
# # port
server.port=8088

# # the data sourcespring.datasource.url=jdbc:mysql://localhost:3306/springBoot? useUnicode=true&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=123456
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

# # the JSP configuration
# default page prefix
spring.mvc.view.prefix=/WEB-INF/jsp/
The default suffix for the response page
spring.mvc.view.suffix=.jsp
Copy the code

The code

The code is basically the same as in the previous article, with the only difference being that I’m using JPA implementation to operate on the database (by the way, using the JPA framework).

The first is the entity class, which is a little different from the previous one because it uses JPA, with some annotations added. Entity: indicates that this is an Entity class. Table: name of the data Table mapped by the entity class. Column: Specifies the attributes of the field. Nullable indicates whether the field is non-null, and unique indicates whether the field is unique.

The code for the entity class looks like this:

@Entity
@Table(name = "t_user") public class User {/** Id */ @id @generatedValue private Long Id; /** name */ @column (nullable =false, unique = true) private String name; /** Password */ @column (nullable =false) private String password; /** age */ @column (nullable =false) private Integer age; // getters and setters omitted}Copy the code

Since JPA is used, the DAO layer simply inherits the JpaRepository class, specifying the entity class and primary key type. The DAO layer code is as follows:

@Mapper
public interface UserDao extends JpaRepository<User, Long>{
	
}
Copy the code

The business layer can be called as before, although using JPA, but the method is also very simple, add and modify is to use save, delete is to delete, findOne is to find by ID, findAll is to query all and so on.

The services code is as follows:

@Service
public 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 failure!");
			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() {
		returnuserDao.findAll(); }}Copy the code

In the control layer, we still provide the interface to the Jsp to call, but we can’t use the RestController annotation, which returns data in JSON format, but we sometimes need to jump back to the interface, so we should use the Controller annotation. If you want to return json data in a method, annotate the ResponseBody annotation on that method.

The control layer code is as follows:

@Controller
public 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.findUserById(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"; }}Copy the code

A functional test

The back-end code introduction is here, as for the front-end JSP code will not say more (mainly because the interface is too ugly…) Let’s just start the project and see what happens. Start the project, the input on the browser: http://localhost:8088/list main interface:

The interface after adding a piece of data:

Other modifications and deletions can also be made, but here they are removed. This is where springBoot’s Jsp integration ends.

Integrate SringBoot 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, including XML/XHTML/HTML5, JavaScript, CSS, and even text files.

The use of the Thymeleaf

I am not familiar with Thymeleaf, which is not the main content of this article. You can check the official documents for details. https://www.thymeleaf.org/documentation.html

The development of preparation

Basically the same as the SringBoot integration Jsp above, I will not repeat here.

Since the default template engine for SpringBoot is Thymeleaf, Maven’s dependencies only need to add Thymeleaf dependencies to the original SpringBoot project.

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

The application. Properties configuration can be basically the same as the previous project, only the spring. Thymeleaf. cache configuration needs to be paid attention to.

There is a big difference between SringBoot and SringBoot: Thymeleaf files are stored in SRC /main/resources, while Jsp files are stored in SRC /main/webapp. The static directory in the Resources directory is used for static content, such as CSS, JS, JPG images, etc. The templates directory is used to put the page templates used by the project, which is the **.html** file.

Its project structure is as follows:

The code is basically consistent with SringBoot integration Jsp, which is not described here.

A functional test

To start the project, enter http://localhost:8085 in the browser.

After modifying user data:

Other functions are also available, so there are no more maps here. SpringBoot integrates Thymeleaf to this end.

SpringBoot integrates Jsp with Thymeleaf

Note: this is a new item added later. SpringBoot’s separate integration of Jsp and Thymeleaf worked fine, with no problems. However, this has changed since SpringBoot’s default template engine is Thymeleaf, and JSP’s template engine does not take effect with JSP. However, if you want to use JSP templates, you can disable Thymeleaf at this point, which can be done through polymorphic configuration changes, but feels too cumbersome. So I did some research and found a way to coexist.

The differences with the previous two projects are as follows:

  1. The previous Jsp and Thymeleaf configurations were in the application.properties file, and I’ve changed their configurations to code here.

2. Thymeleaf files were stored in SRC /main/resources. Now move to web-INF.

3. Add a layer of control that strictly distinguishes between access paths to Jsp and Thymeleaf. The path to access Jsp is prefixed with Jsp, and the Thymeleaf prefix is templates.

The new configuration code is as follows:

@Configuration
@EnableWebMvc
@ComponentScan
public class WebConfig extends WebMvcConfigurerAdapter {
	
	   @Bean
       public ViewResolver viewResolver() {
           InternalResourceViewResolver resolver = new InternalResourceViewResolver();
           resolver.setPrefix("/WEB-INF/");
           resolver.setSuffix(".jsp");
           resolver.setViewNames("jsp/*");
           resolver.setOrder(2);
           return resolver;
       }

       @Bean
       public ITemplateResolver templateResolver() {
           SpringResourceTemplateResolver templateResolver = new SpringResourceTemplateResolver();
           templateResolver.setTemplateMode("HTML5");
           templateResolver.setPrefix("/WEB-INF/");
           templateResolver.setSuffix(".html");
           templateResolver.setCharacterEncoding("utf-8");
           templateResolver.setCacheable(false);
           return templateResolver;
       }

       @Bean
       public SpringTemplateEngine templateEngine() {
           SpringTemplateEngine templateEngine = new SpringTemplateEngine();
           templateEngine.setTemplateResolver(templateResolver());
           return templateEngine;
       }

       @Bean
       public ThymeleafViewResolver viewResolverThymeLeaf() {
           ThymeleafViewResolver viewResolver = new ThymeleafViewResolver();
           viewResolver.setTemplateEngine(templateEngine());
           viewResolver.setCharacterEncoding("utf-8");
           viewResolver.setViewNames(new String[]{"thymeleaf/*"});
           viewResolver.setOrder(1);
           returnviewResolver; } @Override public void configureDefaultServletHandling(DefaultServletHandlerConfigurer configurer) { configurer.enable(); } @Override public void addResourceHandlers(ResourceHandlerRegistry registry) { super.addResourceHandlers(registry); }}Copy the code

The structure of the project is as follows:

A functional test

In the browser input: http://localhost:8089/list view the Thymeleaf template interface

Enter http://localhost:8089/list2 in the browser view JSP template interface

You can see that it’s been successfully integrated

other

So much for integrating Jsp and Thymeleaf with SpringBoot. SpringBoot integration Jsp project project address: https://github.com/xuwujing/springBoot-study/tree/master/springboot-jsp-jpa Thymeleaf SpringBoot integration project address: https://github.com/xuwujing/springBoot-study/tree/master/springboot-thymeleaf SpringBoot integration of Jsp and Thymeleaf project address: https://github.com/xuwujing/springBoot-study/tree/master/springboot-jsp-thymeleaf

Original is not easy, if you feel good, I hope to give a recommendation! Your support is the biggest motivation for my writing! Copyright Notice: Author: nothing Blog garden reference: http://www.cnblogs.com/xuwujing CSDN reference: http://blog.csdn.net/qazwsxpcm personal blog reference: http://www.panchengming.com