MVC messy notes

SpringMVC simple notes

Mainly to learn about and View Controller design, at least write the specification point

Notes section from a brief proficient Spring MVC4, the book also happens to use Spring Boot, it is suitable to use
because of the time span is relatively large (about 23 months), so there may be some problems so foolish as to record the explosion. .

@SpringBootApplication is @ Configuration, and combinations @ EnableAutoConfiguration of @ComponentScan

@Configuration that our class will handle regular Spring configuration, such as the bean declaration

@ComponentScan It tells where to find the Spring Spring components (services, controllers, etc.). By default, this comment will scan the current package and all subpackages of the package below

@EnableAutoConfiguration comment, it will guide the Spring Boot to play its magic. If you remove it out, then you can not profit from the automatic configuration of Spring Boot

XML common configuration (Spring Boot are not required, but requested information)

Generally, the initial steps are as follows:
1. Spring MVC initialization of the DispatcherServlet;
2. Transcoder filter structures to ensure proper client requests transcoding;
3. Build a view resolver (view resolver), Spring told where to find the view, and they are written in what dialect (JSP, Thymeleaf templates, etc.) to use;
4. Configuration position static resources (CSS, JS);
5. Configuration supports geographical and resource bundle;
6. Multipart resolver configuration to ensure that the file uploads to work properly;
7. The Tomcat or Jetty included in, our application can be run on a Web server;
8. Establish error pages (such as 404).

properties in

debug = true Spring Boot Auto Configuration Report

server.port property or define an environment variable named SERVER_PORT, we can modify the default HTTP port defined in server.port property or definition named SERVER_PORT environment variables, we can modify the default HTTP port

Configuring SSL

server.port = 8443 
server.ssl.key-store = classpath:keystore.jks 
server.ssl.key-store-password = secret 
server.ssl.key-password = another-secret 

The default configuration has been good with other

In JacksonAutoConfiguration, declare using Jackson JSON serialization;

In HttpMessageConvertersAutoConfiguration, declare a default HttpMessageConverter;

In JmxAutoConfiguration, declare the JMX function.

Map is a simple model of a package or a Model Spring MVC ModelAndView.

It can be derived from databases, files, external services, etc., depending on how you get the data and drop model

By using @RequestMapping annotations, the controller will be able to declare that they handle a particular request according to the HTTP method (e.g., GET or POST method), and URL. The controller can determine what was written in the Web response directly, or the application routing view and a view property is injected into the

Pure RESTful application will choose the first approach, and will expose JSON or XML representation of the model directly in the HTTP response, which need to use @ResponseBody comment. In Web applications, this type of structure is often associated with the front end JavaScript framework, such as Backbone.js, AngularJS or React. In this scenario, Spring MVC application layer only in the process model.

In the second mode, the model is passed to the view, the view will be rendered by the template engine, and written into the response.

The former is probably meant to say before and after the end of the separation of work

In order to speed up development, adding that in application.properties file attributes:
spring.thymeleaf.cache = false
This will disable view caching is enabled, every time you visit will reload the template.

After the HTTP request to dispatch Dispatcher Servlet Handler Mapping / Controller / View Resolver / View

A typical class HttpServlet, it will be distributed to an HTTP request HandlerMapping. HandlerMapping will resource (URL) associated with the controller

Methods (i.e. methods annotated with @RequestMapping) corresponding to the controller will be called. In this method, the controller will set the data and the model name of the view is returned to the distributor.

Then, the DispatcherServlet ViewResolver will query interface to obtain a corresponding view to achieve.

(ThymeleafAutoConfiguration view resolver will build for us)

By looking at ThymeleafProperties class, you can view the default prefix know is "classpath: / templates /", the suffix is ​​".html".

This means that, assuming that view called resultPage, then the view resolver will look for a file named resultPage.html in the templates directory classpath.

By default sample, ViewResolver interfaces are static, but can be more advanced implementations according to the header information or user information request area, return different

The final view will be rendered, the results will be written into the response.

Access list element list [0]
access Map entry the Map [Key]
? Ternary operator for condition Condition 'yes': 'NO'
Elvis operator person:? Default if the person is empty, it will return to default
safe navigation person? .name If person name is null or empty, or null
template 'Your name is # {person.name} ' is injected into a string value
projection $ {persons. [name]} extract all the persons name, and a list into which
selected persons.?[name == 'Bob'] 'to return to the list name of the person Bob
calls person.sayHello function ()

Pass data to the view mode: model-> return

Request parameter acquisition data:? @ RequestParam-> Browser Properties Write

And commonly required defaultValue

P63 is progressing

Simple traversal

 <ul>
     <li th:each="tweet : ${tweets}" th:text="${tweet}">Some tweet</li>   
</ul>

Adding jQuery

<script src="/webjars/jquery/2.1.4/jquery.js"></script> 

head view CSS was added

 <link href="/webjars/materializecss/0.96.0/css/materialize.css" type="text/css" rel="stylesheet" media="screen,projection"/> 

Sample imitate P53

Can design reuse pages (layout)

default.html part

<html xmlns:th="http://www.thymeleaf.org"                xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"> 
<head>....</head>
<body> 
<section layout:fragment="content">   
    <p>Page content goes here</p> 
</section>
<script..>....</script>
</body>

For the result page

<!DOCTYPE html> 
<html xmlns:th="http://www.thymeleaf.org"  xmlns:layout="http://www.ultraq.net.nz/thymeleaf/layout"   layout:decorator="layout/default"> 
<head lang="en">
    <title>Hello twitter</title> 
</head> 
<body>
<div class="row" layout:fragment="content"> 
    <h2 class="indigo-text center" th:text="|Tweet results for ${search}|">Tweets</h2> 
    <ul class="collection"> 
        .....

Which, layout: decorator = "layout / default" can indicate where to find the layout. In this way, we can inject content into different layout layout: fragment area.

Note that this method has not recommended the (pit book is), you should use th: insert alternative,

A better use Example: https: //segmentfault.com/a/1190000009903821#articleHeader1

Simple error pop-P75

Treatment on request

Redirect / Forward typical alternative. They will be presented to the user to change the view that the difference is that a 302 Redirect message is sent, it will trigger navigation within the browser, and will not result in a change Forward URL. In Spring MVC, we can use any of these two programs, just add "redirect:" in the string returned by the method or "forward:" prefix to

GET common wording

@RequestMapping("/result")   
public String hello(
        @RequestParam(defaultValue = "masterSpringMVC4") String search, 
        Model model) {
    SearchResults searchResults = twitter.searchOperations().search(search);
    List<Tweet> tweets = searchResults.getTweets();  
    model.addAttribute("tweets", tweets);  
    model.addAttribute("search", search);  return "resultPage";  
}

If you want to modify the form, the method was changed to post (more than a method of intercepting postSearch)

@RequestMapping(value = "/postSearch", method = RequestMethod.POST) 
public String postSearch(
        HttpServletRequest request,
        RedirectAttributes redirectAttributes) {  
    String search = request.getParameter("search");
    redirectAttributes.addAttribute("search", search);
    return "redirect:result"; 
}

Spring RedirectAttributes is a model used to send values ​​scene redirect

A more robust method

@RequestMapping(value = "/postSearch", method = RequestMethod.POST) 
public String postSearch(
        HttpServletRequest request, 
        RedirectAttributes redirectAttributes) {  
    String search = request.getParameter("search");  
    if (search.toLowerCase().contains("struts")) {  //不允许出现的内容
        redirectAttributes.addFlashAttribute("error", "Try using spring instead!"); 
        return "redirect:/";  
    }  
    redirectAttributes.addAttribute("search", search);  
    return "redirect:result"; 
}

Forms

@ {} Syntax will build the complete path for the resource, it sends the server context path

Therefore thymeleaf may be used form th:action="@{...}"alternativelyform action=..

DTO can be used directly POJO, only getter and setter can perform data binding

Specific inspection P82

Check validation logic P86

Form logic P99

P120

HTTP session (session) is used in a way to store information between requests. HTTP is a stateless protocol, which means that there is no way to associate the two requests for the same user. Servlet container most common way is for each user to associate a cookie called the JSESSIONID. This cookie will be transmitted via the request header information, using this technology allows the user to any object stored in a Map, which is called the abstract form of HttpSession. Typically such a session will fail when the user closes the Web browser or switch, or no active user within a predetermined time action

@SessionAttributes by using annotations, objects placed into the session P115

@Controller @SessionAttributes("picturePath") public class PictureUploadController { } 

In Spring, the content on another popular way session is to add @Scope ( "session") annotated as bean.

Table pit:

https://blog.csdn.net/ystyaoshengting/article/details/84773952

Controller of mass participation on the return value, or refer to the official documentation MVC

https://docs.spring.io/spring/docs/5.1.8.RELEASE/spring-framework-reference/web.html

Probably in 1.3.3

The results still do not understand the relationship of String View ModelAndView. . .

Feel, String returns the View name, referred to treatment by the ViewResolver, and View setter can do the same to get View String name, but may have been further resolved, and ModelAndView may be further provided inside view depends model

Model parameters are passed on, the need for one-name?

About @ModelAttribute

You can use the @ModelAttribute annotation on a method argument to access an attribute from the model or have it be instantiated if not present. The model attribute is also overlain with values from HTTP Servlet request parameters whose names match to field names. This is referred to as data binding, and it saves you from having to deal with parsing and converting individual query parameters and form fields. The following example shows how to do so:

@PostMapping("/owners/{ownerId}/pets/{petId}/edit")
public String processSubmit(@ModelAttribute Pet pet) { } 

The Pet instance above is resolved as follows:

  • From the model if already added by using Model.
  • From the HTTP session by using @SessionAttributes.
  • From a URI path variable passed through a Converter (see the next example).
  • From the invocation of a default constructor.
  • From the invocation of a “primary constructor” with arguments that match to Servlet request parameters. Argument names are determined through JavaBeans @ConstructorProperties or through runtime-retained parameter names in the bytecode.

Guess you like

Origin www.cnblogs.com/caturra/p/11026090.html