Location>code7788 >text

Java Web Gleanings

Popularity:206 ℃/2024-09-25 10:43:26

Maybe it's because I'm getting older, I always recall the past. Looking back at the original code, like a chance encounter with an ex-girlfriend who has not been seen for many years, once together with in-depth exchange of friendship in the nod between the dissipation of annoyance.

Today it's time to talk about the age-old cliché of Java Web Development. The reason for this is a simpleSpring BootProject remodeling, the author looked at a pile of notes and configurations, suffering from the pain of picking up memories, choose one or two records to commemorate the lost youth.

This article is helpful for newbies, so don't laugh over it.

JSP + JavaBean

The author was exposed as a student toJSP, as a product of the distant past, is now hard to find, but with it comes theJavaBean, but it has stayed on.

In any development model, a set of specifications is required and JavaBean is a class/object that conforms to these specifications, for example:

  • All fields are private (no direct external access, to avoid dependency failures caused by later renaming/deleting, etc.)
  • Provide default constructor methods (for easy external instantiation)
  • Provide getters and setters (read/write logic for custom properties)
  • Implement the serializable interface (serialization support)

Note that a JavaBean is not a POJO because it needs methods, events, etc. to handle and respond to business. It contains all the data and business logic, and the back-end code to call them is embedded in the HTML during development, as shown below:

<%@ page language="java" import=".*,.*" pageEncoding="utf-8"%>
<%
String path = ();
%>

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN">
<html>
  <head>
    <base href="<%=path%>">
  </head>

  <body>
    <%CheckUserBean cub=new CheckUserBean(); %>
  <jsp:useBean  class="" scope="request"></jsp:useBean>
  <jsp:getProperty property="name" name="user"/>
  <jsp:setProperty property="password" name="user"/>
  <%if((user)) {%>
  <jsp:forward page=""></jsp:forward>
  <%}else{%>
  <jsp:forward page=""></jsp:forward>
  <%} %>
  </body>
</html>

There are two JavaBeans, UserBean and CheckUserBean, UserBean is used to display data and receive user input, CheckUserBean is used to determine whether the user is legitimate or not.

Later, some of the features of JavaBean were adopted by developers, while the concept was simplified toBean, generalizing to more frameworks. For most of the later languages (e.g., C#), because of the pitfalls that Java helped to tread, they tend to provide language features from the beginning of the language design to more easily and naturally fit into these specifications.

Servlet

JSP + JavaBean model has an obvious drawback , that is, the implicit page jump (data flow), increasing the probability of error in the development process , such as the same page may be jumped from a number of different pages , and the corresponding data structure is not the same , the developer should consider all possible scenarios , and provide the appropriate JavaBean to take over these data. Similarly, with the development of the business, this kind of jump or data structure will often change, development and maintenance costs are extremely high.

So it's added.Servlet(Generally inherited fromHttpServletThis class defines a few straightforward methods (which I won't go into here) to handle requests, populate JavaBeans/call JavaBean methods, choose which view to return to, etc., and with the addition of routing configurations, it forms the basis of theMVCMode.

Routing is configured in thein the following:

<?xml version="1.0" encoding="UTF-8"?>
<web-app>
    <!--other configrations -->

    <!-- herald servlet -->
    <servlet>
        <servlet-name>login</servlet-name>
        <servlet-class></servlet-class>
    </servlet>
    <!-- Routing Configuration -->
    <servlet-mapping>
        <servlet-name>login</servlet-name>
        <url-pattern>/login</url-pattern>
    </servlet-mapping>

</web-app>

It is worth noting that the emergence ofFilterThe concept of AOP, that is, before the servlet processing request and return response after the intermediate processor, can provide business-independent general-purpose functions, such as identity verification, flow restriction, exception handling and so on. This AOP concept is very good and has been retained to this day.

Similarly, the Filter needs to be configured as follows:

<web-app>
    <!-- other configrations -->

     <filter>
         <filter-name>jsp</filter-name>
         <filter-class></filter-class>
     </filter>
     <filter-mapping>
         <filter-name>jsp</filter-name>
         <url-pattern>/*</url-pattern>
     </filter-mapping>

</web-app>

Note that the Servlet must run in a Servlet container such as Tomcat.

Struts

In order to improve development efficiency, on the basis of Servlet, provides a number of common modules and tools, the development of a set of specifications, the formation of a framework, the most well-known when theStrutsIt has two versions, 1 and 2. These two versions are not simple upgrades, but rather a change in the entire philosophy involved.

Struts1

Struts1 Using a singleton coreActionServletReceive all requests, request data is transformed intoActionForm, and then based on the configuration (hit the nail on the headActionMapping) distributed to differentActionActions generally contain only one excute method for processing operations.

Struts1's obvious shortcomings have led to the fact that basically no one uses it nowadays:

  • cumbersome configuration
  • ActionServlet singleton pattern, must consider thread-safety
  • Dependency on web container, unit testing is not convenient

Struts2

as a resultStruts2was launched.

It usesInterceptor + Controller (i.e. Action in Struts1)The model makes the whole processing process much more scalable.

At the same time it rejects the singleton model, each time a new Controller will be instantiated to handle the request (which can contain any number of methods to perform different business), do not have to worry about thread security issues, the disadvantage is that the concurrency of the object instance of the high surge of memory constraints.

With its own interception mechanism, the framework maps the request and response data to POJOs, realizing the Controller's ability toHttpServletRequestcap (a poem)HttpServletResponseSuch a stripping of the native Servlet object, i.e., the Controller is not dependent on the web container, allows for easy unit testing.

Remember the above Servlet's filter, Struts2 interceptor and it's the same principle, except that the former face all requests, the latter for a specific Controller. of course, Struts2 uses both.

Struts2 was a quantum leap over Struts1, but within a few years its glory was overshadowed by the upstarts.

Spring MVC

with regard toSpring MVCI have to start by saying.Spring

Spring

SpringSpring is a popular IOC and AOP framework for the Java platform, and although it doesn't target specific usage scenarios, the Web DNA of the Java platform has influenced it from the beginning, so we often use it to develop back-end services.Spring WebSpring MVC is a sub-module of Spring Web, which includes many other modules such asSpring WebFlux, Spring Web Service, Spring WebSocket, etc.

The second half of Java shines on mobile with another IOC frameworkDaggerSilent support behind the scenes, see the author's write-up of Jerking an App from Scratch - Dagger2, not to be repeated here.

IOC

We can do this by adding the following to the XML file (using theClassPathXmlApplicationContext(loaded), and then configure the bean in your code using the@Autowiredmaybe@Resource(from JSR-250, built-in to the JDK) injects a bean instance (scoped via thescope(set, the default is single instance).

XML configuration is a bit cumbersome, Sping2.5 began to support annotation injection, as long as the configuration in the XML<context:component-scan>(Corresponding to@ComponentScanannotation), Spring automatically scans all the classes in the specified package for classes such as the@Component,@Service,@Repository,@ControllerThis way, of course, you can only configure classes within the project.

In order to allow annotations to be injected into third-party classes, starting in 3.0, Spring introduced the@Configuration. Classes modified with the @Configuration annotation (using theAnnotationConfigApplicationContext(loading), you can use the@Beanannotation modifies the method that returns the bean. If we want to reuse the configuration class defined there, we can use the@Importannotation, which acts similarly to importing multiple XML configuration files into a single file.

XML configuration and annotation configuration can also be mixed, for example, by using the@ImportResourceannotation into the XML file.

AOP

Spring still provides AOP functionality.

AOP is divided into static AOP and dynamic AOP. static AOP is the compilation of the cutout code directly into the source code, as in the case of the Java platform'sAspectJimplementation; dynamic AOP refers to the dynamic weaving of faceted code into the runtime; Spring's AOP is dynamic AOP, implemented using the technology provided by the JDK'sdynamic agent technologycap (a poem)CGLIB (dynamic bytecode enhancement technology)The difference between the two is as follows:

  • JDK dynamic proxies utilize an interceptor (InvocationHandler must be implemented) plus a reflection mechanism to generate an anonymous class for the proxy interface, and invoke InvokeHandler before invoking a specific method; CGLIB utilizes theASMframework that loads in the class file generated by the target class and handles it by modifying its bytecode to generate subclasses.
  • The target class of a JDK dynamic proxy must implement an interface, and only the methods in the interface can be proxied; CGLIB does not have this restriction, but because of the inheritance pattern, the target class or method cannot be final.
  • After Java 1.8, JDK dynamic proxies are more efficient than CGLIB in most scenarios.

Both are based on the proxy model, despite different implementation techniques, and both generate a proxy object.

Spring decides whether to use JDK dynamic proxying or CGLIB depending on whether the target class implements an interface or not, and of course you can force CGLIB to be used if you meet the conditions (<aop:aspectj-autoproxy proxyt-target-class="true"/>)。

The annotations involved in Spring AOP include@Aspect、@Pointcut、@Before、@After、@AfterReturning、@AfterThrowing、@Around、@EnableAspectJAutoProxyetc., which are not detailed here.


Spring MVC is also based on Servlet, like the IOC version of Struts2, of course, due to the introduction of IOC, the two concepts and components are very different, but the backbone of the request processing is the same.

The page rendering implementations supported by Spring MVC do not contain JSPs. instead, theThymeleafFreemarkeretc.

Spring Boot

Finally to talk about Spring Boot, it is built on top of Spring, a rapid development framework , designed to simplify the initial setup of Spring applications as well as the development process. It does this by providing a default configuration,Starter dependenciesand other features that greatly reduce the configuration effort of a project.

Again, it's not exclusive to web development, but we use it primarily in the web domain.

@ConfigurationProperties

In Spring Boot projects, we often configure a large number of parameters in (Spring) or files, and then pass them through the@ValueTake values as follows:

@Value("${}")
private String userName;

In fact, by@ConfigurationPropertiesannotation, we can get these parameter values more refreshingly:

//@Component pour into
@ConfigurationProperties(prefix="db")
public class DbConfiguration{
  public String userName;
}

@ConfigurationProperties does not become a Spring bean unless the configuration class is also annotated with something like @Component, or if the user annotates the@EnableConfigurationPropertiesAnnotation (the latter is recommended, i.e., on-demand rather than globally visible):

@EnableConfigurationProperties()
public class Invoker{

    @Autowired
    DbConfiguration dbConfiguration;
}

If you're writing a Spring-based class library, many of the objects are injected for use as beans, so of course you want third-party projects that use the library to be able to load those objects into the container beforehand.

You can write in the ReadMe "Class XX and XXX and ...... must be instantiated into the container at project startup" so that the user knows that he has to write a big piece of non-business related configuration code using XML or @Configuration etc. configuration code in XML or @Configuration.

Or you can use the program. It's actually Spring boot that provides theSPImechanism, the user's project (which needs to be labeled in the entry class)@EnableAutoConfigurationannotation) will be based on theSpringFactoriesLoaderlook upClassLoaderAll the jars in theClassPath(all modules under it) introduced by theMETA-INF/file, the corresponding @Configuration-modified class is automatically loaded based on the interfaces in the file and registered with the container.

For modularity, configuration provides the cornerstone, we often refer to such as "xxx-spring-boot-starter" class library, is basically the use of this scheme.

ps: Since Spring Boot 3.0, theMETA-INF/spring/Replaces META-INF/, content formatting has changed, rationale remains the same.

Spring Boot 3.0 is a relatively major revamp, and the most impactful change is that you must use JDK17 and above.


Since we often use @ComponentScan,@SpringBootConfiguration(along with @Configuration), @EnableAutoConfiguration, and Spring Boot simply comes up with a@SpringBootApplicationAnnotation that combines all three.


Spring Boot has made some changes to the use of AOP that will not be repeated here.

Built-in common servers (e.g. Tomcat, Jetty), no need to deploy separately.


Spring Boot is a very mature out-of-the-box framework, but in the microservice scenario is too bulky. Followed by the fate of the author will come back to talk about the Java platform is more suitable for microservices running a few frameworks.