SpringMVC and springmvc tutorials

Source: Internet
Author: User

SpringMVC and springmvc tutorials

SpringMVC

The Servlet API is often called naturally when you access a session in a method.

It is very intuitive and convenient to use.

For example:

@RequestMapping(value = "/logout")public String logout(HttpSession session) {    session.removeAttribute("user");    return "/login";}

 

After all, it seems that pojo is not enough to depend on Servlet APIs.

 

So I tried to solve this problem.

I plan to use an annotation named "sessionScope". The Target can be a Method or Parameter.

That is to say:

 

import java.lang.annotation.Documented;import java.lang.annotation.ElementType;import java.lang.annotation.Retention;import java.lang.annotation.RetentionPolicy;import java.lang.annotation.Target;@Target({ ElementType.PARAMETER,ElementType.METHOD })@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface SessionScope {    String value();}

 

Then I want to register an ArgumentResolver to solve the annotated things and replace them all with the things in the session.

The Code is as follows:

 

import org.apache.commons.lang3.StringUtils;import org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.core.MethodParameter;import org.springframework.web.bind.support.WebDataBinderFactory;import org.springframework.web.context.request.NativeWebRequest;import org.springframework.web.context.request.RequestAttributes;import org.springframework.web.method.support.HandlerMethodArgumentResolver;import org.springframework.web.method.support.ModelAndViewContainer;public class SessionScopeMethodArgumentResolver implements        HandlerMethodArgumentResolver {    @Override    public boolean supportsParameter(MethodParameter parameter) {        if(parameter.hasParameterAnnotation(SessionScope.class))return true;        else if (parameter.getMethodAnnotation(SessionScope.class) != null)return true;        return false;    }    @Override    public Object resolveArgument(MethodParameter parameter,            ModelAndViewContainer mavContainer, NativeWebRequest webRequest,            WebDataBinderFactory binderFactory) throws Exception {        String annoVal = null;                                                                                                                                                                                                                                                                                                                                          if(parameter.getParameterAnnotation(SessionScope.class)!=null){            logger.debug("param anno val::::"+parameter.getParameterAnnotation(SessionScope.class).value());            annoVal = parameter.getParameterAnnotation(SessionScope.class).value();                                                                                                                                                                                                                                                                                                                                              }else if(parameter.getMethodAnnotation(SessionScope.class)!=null){            logger.debug("method anno val::::"+parameter.getMethodAnnotation(SessionScope.class).value());            annoVal = parameter.getMethodAnnotation(SessionScope.class)!=null?StringUtils.defaultString(parameter.getMethodAnnotation(SessionScope.class).value()):StringUtils.EMPTY;        }                                                                                                                                                                                                                                                                                                                                          if (webRequest.getAttribute(annoVal,RequestAttributes.SCOPE_SESSION) != null){            return webRequest.getAttribute(annoVal,RequestAttributes.SCOPE_SESSION);        }        else            return null;    }                                                                                                                                                                                                                                                                                                                                  final Logger logger = LoggerFactory.getLogger(SessionScopeMethodArgumentResolver.class);}

 

SupportParameter checks whether the object is annotated. If it is annotated, resolve is performed.

Obtain the annotation value during resolve. The annotation value is the session key, and the value is obtained from the session scope using webRequest.


In addition, you need to put this configuration in the customArgumentResolvers list of org. springframework. web. servlet. mvc. method. annotation. RequestMappingHandlerAdapter. You can use bean tag configuration or mvc tag directly.
That is:
Namespace is: xmlns: mvc = "http://www.springframework.org/schema/mvc"
Schema location: http://www.springframework.org/schema/mvc
Http://www.springframework.org/schema/mvc/spring-mvc-3.1.xsd

<mvc:annotation-driven>    <mvc:argument-resolvers>        <bean class="pac.common.SessionScopeMethodArgumentResolver" />    </mvc:argument-resolvers></mvc:annotation-driven><mvc:default-servlet-handler />


In other words, the order of mvc: annotation-driven and mvc: default-servlet-handler cannot be reversed. This is not the case for me --..

It can be used in controller now, for example:

@RequestMapping(value = "/index")@SessionScope("currentUser")public ModelAndView index(User currentUser) {    ModelAndView mav;    if (currentUser==null || currentUser.getId()==null)        mav = new ModelAndView("/login");    else {        mav = new ModelAndView("/index");    }    return mav;}

 

You can also annotate the following parameters:

@RequestMapping(value = "/welcome")public String welcome(@SessionScope("currentUser")User currentUser) {    return "/main";}

 

Currently, only @ sessionAttributes and ModelMap are used to update the session.
Well, I don't like this method very much...

 

Alternatively, you can directly integrate Apache Shiro and getSubject () in the controller ().
Let shiro take full responsibility for user information. Well, this is good.


Differences Between Spring and SpringMVC

Spring is an open-source framework for enterprise application development. The functions are as follows:
◆ Objective: To solve the complexity of Enterprise Application Development
◆ Function: Use Basic JavaBean instead of EJB, and provide more enterprise application functions
◆ Scope: any Java application
In short, Spring is a lightweight container framework for IoC and AOP.
◆ Lightweight-Spring is lightweight in terms of size and overhead. The complete Spring framework can be published in a JAR file with a size of more than 1 MB. In addition, the processing overhead required by Spring is negligible. In addition, Spring is non-intrusive: Typically, objects in Spring applications do not depend on specific classes of Spring.
◆ Control inversion-Spring promotes loose coupling through a technology called control inversion (IoC. When IoC is applied, other objects that an object depends on will be passed in passively, instead of creating or searching for dependent objects. You can think of IoC as the opposite of JNDI-instead of looking for Dependencies from the container, the container actively passes the dependency to the container when the object request is initiated.
◆ Aspect-Oriented -- Spring provides a wide range of support for Aspect-Oriented Programming, which allows you to manage business logic and system-level services (such as audit and transaction) by separating applications) for cohesion development. Application objects only implement what they should do -- complete the business logic -- that's all. They are not responsible (or even conscious) for other system-level concerns, such as log or transaction support.
◆ Container -- Spring contains and manages the configuration and lifecycle of application objects. In this sense, Spring is a container, you can configure how each of your beans is created-based on a configurable prototype ), your bean can create a separate instance or generate a new instance every time you need it-and how they are associated. However, Spring should not be mixed with traditional heavyweight EJB containers, which are often large and bulky and difficult to use.
◆ Framework-Spring can configure and combine simple components into complex applications. In Spring, application objects are declared and combined, typically in an XML file. Spring also provides many basic functions (such as transaction management and persistent framework integration), leaving the development of application logic to you.
All of these features of Spring allow you to write code that is cleaner, manageable, and easier to test. They also provide basic support for various modules in Spring.

Spring's two core AOP and IOC can be used independently for any application, including integration with Struts, MVC, Hibernate, and other ORM frameworks, currently, many companies use Spring + Struts (2) + Hibernate for lightweight development.
Spring MVC is an MVC framework. I personally think that Spring MVC annotation-based development is more convenient than Struts2 and can directly replace Struts above (of course, Struts is a very mature MVC, the function is better than Spring, but Spring MVC is enough ). Of course, the execution efficiency of spring mvc is higher than that of struts because the value stack of struts affects the efficiency.

Spring mvc is similar to a struts MVC open framework. It actually belongs to spring. spring mvc can run only when it has spring shelf packages as support.

If someone asks you something about control reversal (spring's core interview often asks): You will answer, why did the program come out of our new system, later, I handed it over to the program control for a new version. This is the control reversal. After so many hands were played, I had to worry about it. Let's give it a try.

Differences Between Spring and SpringMVC

Spring is an open-source framework for enterprise application development. The functions are as follows:
◆ Objective: To solve the complexity of Enterprise Application Development
◆ Function: Use Basic JavaBean instead of EJB, and provide more enterprise application functions
◆ Scope: any Java application
In short, Spring is a lightweight container framework for IoC and AOP.
◆ Lightweight-Spring is lightweight in terms of size and overhead. The complete Spring framework can be published in a JAR file with a size of more than 1 MB. In addition, the processing overhead required by Spring is negligible. In addition, Spring is non-intrusive: Typically, objects in Spring applications do not depend on specific classes of Spring.
◆ Control inversion-Spring promotes loose coupling through a technology called control inversion (IoC. When IoC is applied, other objects that an object depends on will be passed in passively, instead of creating or searching for dependent objects. You can think of IoC as the opposite of JNDI-instead of looking for Dependencies from the container, the container actively passes the dependency to the container when the object request is initiated.
◆ Aspect-Oriented -- Spring provides a wide range of support for Aspect-Oriented Programming, which allows you to manage business logic and system-level services (such as audit and transaction) by separating applications) for cohesion development. Application objects only implement what they should do -- complete the business logic -- that's all. They are not responsible (or even conscious) for other system-level concerns, such as log or transaction support.
◆ Container -- Spring contains and manages the configuration and lifecycle of application objects. In this sense, Spring is a container, you can configure how each of your beans is created-based on a configurable prototype ), your bean can create a separate instance or generate a new instance every time you need it-and how they are associated. However, Spring should not be mixed with traditional heavyweight EJB containers, which are often large and bulky and difficult to use.
◆ Framework-Spring can configure and combine simple components into complex applications. In Spring, application objects are declared and combined, typically in an XML file. Spring also provides many basic functions (such as transaction management and persistent framework integration), leaving the development of application logic to you.
All of these features of Spring allow you to write code that is cleaner, manageable, and easier to test. They also provide basic support for various modules in Spring.

Spring's two core AOP and IOC can be used independently for any application, including integration with Struts, MVC, Hibernate, and other ORM frameworks, currently, many companies use Spring + Struts (2) + Hibernate for lightweight development.
Spring MVC is an MVC framework. I personally think that Spring MVC annotation-based development is more convenient than Struts2 and can directly replace Struts above (of course, Struts is a very mature MVC, the function is better than Spring, but Spring MVC is enough ). Of course, the execution efficiency of spring mvc is higher than that of struts because the value stack of struts affects the efficiency.

Spring mvc is similar to a struts MVC open framework. It actually belongs to spring. spring mvc can run only when it has spring shelf packages as support.

If someone asks you something about control reversal (spring's core interview often asks): You will answer, why did the program come out of our new system, later, I handed it over to the program control for a new version. This is the control reversal. After so many hands were played, I had to worry about it. Let's give it a try.

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.