[spring MVC] spring MVC foundation - spring MVC projects are built quickly, and the log framework is logback

Familiar with memory 2021-01-21 10:39:21
spring mvc spring mvc foundation

Reprint please indicate the source :http://blog.csdn.net/qq_26525215 This article comes from College trip _ The blog of memory


Spring MVC Provides a DispatcherServlet To develop Web application .

stay Servlet 2.5 And below, as long as web.xml The configuration <servlet> The elements are . In the following example , It uses Servlet3.0+ nothing web.xml Configuration mode , stay Spring MVC To realize WebApplicationInitialzer Interface implementation is equivalent to web.xml Configuration of .

The following example is in IDEA Based on Maven Build zero configuration Spring MVC Prototype project .


structure Maven project

pom.xml Content :

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<!--Generic properties -->
<!-- Web -->
<!-- Spring -->
<!--Logging -->
<!-- Spring MVC -->
<!-- other Web rely on -->
<!-- Spring and Transaction -->
<!-- Use SLF4J and LogBack As log -->

Log configuration

stay src/main/resources Under the table of contents , newly build logback.xml Used to configure logs , The contents are as follows :

<?xml version="1.0" encoding="UTF-8"?>
<!-- The basic structure of the configuration file can be described in this way : With <configuration> start ,
There are zero or more at the back <appender> Elements , There are zero or more <logger> Elements , There is at most one <root> Elements -->
<configuration debug="false" scan="true" scanPeriod="1 seconds">
<!-- debug : The default is false , Set to true when , Will print out logback Internal log information , Real-time view logback Running state .
scan : If the configuration file changes , Will be reloaded , The default value is true;
scanPeriod : Time interval to detect whether the configuration file has been modified , If no time unit is given , The default unit is milliseconds per hour ,
When scan by true when , This property works , The default time interval is 1min. -->
<contexListener class="ch.qos.logback.classic.jul.LevelChangePropagator">
<appender name="console" class="ch.qos.logback.core.ConsoleAppender">
<!-- <appender> yes <configuration> Child nodes of , It's the component responsible for writing logs .
appender There are two necessary attributes name ,class .name Appoint appender The name of , class Appoint appender Full name of
class Include :ch.qos.logback.core.ConsoleAppender / ch.qos.logback.core.FileAppender/ ch.qos.logback.core.RollingFileAppender -->
<!--ch.qos.logback.core.ConsoleAppender Add logs to the console , There are the following nodes : <encoder> : Format the log .
<target> : character string System.out perhaps System.err, Default System.out;
ch.qos.logback.core.FileAppender Add log to file
ch.qos.logback.core.RollingFileAppender[ Commonly used ] Scroll through the record file , First log to the specified file , When certain conditions are met , Log to other files -->
<pattern>logbak: %d{HH:mm:ss.SSS} %logger{36} - %msg%n</pattern>
<logger name="org.springframework.web" level="DEBUG"></logger>
<!--logger yes <configuration> Child nodes of To set the log printing level of a package or a specific class , And the designation <appender>
loger There is only one name attribute , Two optional properties level/addtivity
name : Used to designate the recipient loger A package of constraints or a specific class
level: Used to set the print level , Case is irrelevant -->
<!-- Element configuration root logger. This element has one level attribute . No, name attribute , Because it has been named by “root”-->
<!-- The default root node is INFO Level of logging -->
<!-- root:logger The root node , Just this one , The default name is root
level: The level of logging
appender-ref: Decide which one to use appender
<root level="info">
<appender-ref ref="console"></appender-ref>

take org.springframwork.web The logging level of the classes under the package is set to DEBUG, We develop Spring MVC It's often associated with parameter types 4XX error , Set this, we will see more detailed error messages .

Demo page

There's a point to note here , Where the page was created . stay src/main/resources Set up under the views Catalog , And create a new index.jsp. The contents are as follows :

Created by IntelliJ IDEA.
User: Chen Haoxiang
Date: 2016/12/18
Time: Afternoon 12:45
To change this template use File | Settings | File Templates.
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<title>MVC Title</title>
<pre>Welcome to Spring MVC</pre>
welcome !

The page here is not on Maven The standard src/main/webapp/WEB-INF Next , The reason for this is ,Spring Boot The page is placed in the src/main/resources Next .

Spring MVC Configuration class

This is a simple Spring Configuration class . There's one configured here JSP Of ViewResolver, Used to map the path and actual page location , among ,@EnableWebMvc Annotations will turn on some default configurations , As some ViewResolver perhaps MessageConverter etc.

package cn.hncu.springmvc;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.EnableWebMvc;
import org.springframework.web.servlet.view.InternalResourceViewResolver;
import org.springframework.web.servlet.view.JstlView;
* Created with IntelliJ IDEA.
* User: Chen Haoxiang .
* Date: 2016/12/19.
* Time: Afternoon 3:39.
* Explain: Configuration class
public class MyMvcConfig {
public InternalResourceViewResolver viewResolver(){
InternalResourceViewResolver viewResolver = new InternalResourceViewResolver();
viewResolver.setPrefix("/WEB-INF/classes/views/");// The mapping path - The runtime code will automatically compile our page to /WEB-INF/classes/views/ Next
viewResolver.setSuffix(".jsp");// The actual page suffix
return viewResolver;

Spring MVC Of ViewResolver, This is Spring MVC View (JSP Next is html) The core mechanism of rendering ;Spring MVC There's an interface called ViewResolver( our ViewResolver All implement the interface ), To implement this interface, we need to rewrite resolverViewName(), The return value of this method is the interface View, and View My duty is to use model、request、response object , And will render the view ( Is not necessarily html, May be json、xml、pdf) Back to the browser .

The mapping path prefix may be configured as /WEB-INF/classes/views/ It's a little strange. , This is not the way we put the page . This is because the page effect you see is run-time, not development time code , The runtime code will automatically compile our page to /WEB-INF/classes/views/ Next 、 Pictured :

This is the compiled path !

Web Configuration class

This class is designed to replace web.xml The location of .

package cn.hncu.springmvc;
import org.springframework.web.WebApplicationInitializer;
import org.springframework.web.context.support.AnnotationConfigWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRegistration;
* Created with IntelliJ IDEA.
* User: Chen Haoxiang .
* Date: 2016/12/19.
* Time: Afternoon 3:44.
* Explain:Web To configure
public class WebInitializer implements WebApplicationInitializer {
//WebApplicationInitializer yes spring Provide to configure Servlet3.0+ Configured interfaces , So that we can replace web.xml The location of .
// Implementing this interface will automatically be SpringServletContainerInitializer( To start Servlet3.0 Containers ) Get
public void onStartup(ServletContext servletContext) throws ServletException {
AnnotationConfigWebApplicationContext context = new AnnotationConfigWebApplicationContext();
context.setServletContext(servletContext);// newly build WebApplicationContext, Register configuration class , And compare it with the current servletContext relation
ServletRegistration.Dynamic servlet = servletContext.addServlet("dispatcher",new DispatcherServlet(context));
// register Spring MVC Of DispatcherServlet

Simple controller

package cn.hncu.springmvc;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
* Created with IntelliJ IDEA.
* User: Chen Haoxiang .
* Date: 2016/12/19.
* Time: Afternoon 3:55.
* Explain: Simple controller
@Controller // utilize @Controller An annotation declaration is a controller
public class HelloController {
@RequestMapping("/index")// utilize @RequestMapping To configure URL Mapping between and methods
public String hello(){
return "index";// Pass above ViewResolver Of Bean To configure , The return value is index, Explain that our page placement path is :/WEB-INF/classes/views/index.jsp

ad locum , We go through @RequestMapping To configure URL Mapping between and methods , To access the actual page !

Running results

Last , Deploy the program to Tomcat in , start-up Tomcat, visit : http://localhost:8080/springMVC/index

The source code links involved in this blog :

-> Click to access the source code -CHX

This article is written by [ Familiar with memory ] To write , All rights reserved . Welcome to reprint , Sharing is the source of progress .

Reprint please indicate the source :http://blog.csdn.net/qq_26525215 This article comes from College trip _ The blog of memory

Participation of this paper Tencent cloud media sharing plan , You are welcome to join us , share .

本文为[Familiar with memory]所创,转载请带上原文链接,感谢

  1. 【计算机网络 12(1),尚学堂马士兵Java视频教程
  2. 【程序猿历程,史上最全的Java面试题集锦在这里
  3. 【程序猿历程(1),Javaweb视频教程百度云
  4. Notes on MySQL 45 lectures (1-7)
  5. [computer network 12 (1), Shang Xuetang Ma soldier java video tutorial
  6. The most complete collection of Java interview questions in history is here
  7. [process of program ape (1), JavaWeb video tutorial, baidu cloud
  8. Notes on MySQL 45 lectures (1-7)
  9. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  10. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  11. 精进 Spring Boot 03:Spring Boot 的配置文件和配置管理,以及用三种方式读取配置文件
  12. Refined spring boot 03: spring boot configuration files and configuration management, and reading configuration files in three ways
  13. 【递归,Java传智播客笔记
  14. [recursion, Java intelligence podcast notes
  15. [adhere to painting for 386 days] the beginning of spring of 24 solar terms
  16. K8S系列第八篇(Service、EndPoints以及高可用kubeadm部署)
  17. K8s Series Part 8 (service, endpoints and high availability kubeadm deployment)
  18. 【重识 HTML (3),350道Java面试真题分享
  19. 【重识 HTML (2),Java并发编程必会的多线程你竟然还不会
  20. 【重识 HTML (1),二本Java小菜鸟4面字节跳动被秒成渣渣
  21. [re recognize HTML (3) and share 350 real Java interview questions
  22. [re recognize HTML (2). Multithreading is a must for Java Concurrent Programming. How dare you not
  23. [re recognize HTML (1), two Java rookies' 4-sided bytes beat and become slag in seconds
  24. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  25. RPC 1: how to develop RPC framework from scratch
  26. 造轮子系列之RPC 1:如何从零开始开发RPC框架
  27. RPC 1: how to develop RPC framework from scratch
  28. 一次性捋清楚吧,对乱糟糟的,Spring事务扩展机制
  29. 一文彻底弄懂如何选择抽象类还是接口,连续四年百度Java岗必问面试题
  30. Redis常用命令
  31. 一双拖鞋引发的血案,狂神说Java系列笔记
  32. 一、mysql基础安装
  33. 一位程序员的独白:尽管我一生坎坷,Java框架面试基础
  34. Clear it all at once. For the messy, spring transaction extension mechanism
  35. A thorough understanding of how to choose abstract classes or interfaces, baidu Java post must ask interview questions for four consecutive years
  36. Redis common commands
  37. A pair of slippers triggered the murder, crazy God said java series notes
  38. 1、 MySQL basic installation
  39. Monologue of a programmer: despite my ups and downs in my life, Java framework is the foundation of interview
  40. 【大厂面试】三面三问Spring循环依赖,请一定要把这篇看完(建议收藏)
  41. 一线互联网企业中,springboot入门项目
  42. 一篇文带你入门SSM框架Spring开发,帮你快速拿Offer
  43. 【面试资料】Java全集、微服务、大数据、数据结构与算法、机器学习知识最全总结,283页pdf
  44. 【leetcode刷题】24.数组中重复的数字——Java版
  45. 【leetcode刷题】23.对称二叉树——Java版
  46. 【leetcode刷题】22.二叉树的中序遍历——Java版
  47. 【leetcode刷题】21.三数之和——Java版
  48. 【leetcode刷题】20.最长回文子串——Java版
  49. 【leetcode刷题】19.回文链表——Java版
  50. 【leetcode刷题】18.反转链表——Java版
  51. 【leetcode刷题】17.相交链表——Java&python版
  52. 【leetcode刷题】16.环形链表——Java版
  53. 【leetcode刷题】15.汉明距离——Java版
  54. 【leetcode刷题】14.找到所有数组中消失的数字——Java版
  55. 【leetcode刷题】13.比特位计数——Java版
  56. oracle控制用户权限命令
  57. 三年Java开发,继阿里,鲁班二期Java架构师
  58. Oracle必须要启动的服务
  59. 万字长文!深入剖析HashMap,Java基础笔试题大全带答案
  60. 一问Kafka就心慌?我却凭着这份,图灵学院vip课程百度云