Common annotation sharing of SSM framework

Copyright statement: Copyright by Yang Yangyang~~https://blog.csdn.net/weixin_38316697/article/details/82769671

Common annotation sharing of SSM framework

1. @Controller                               [Chinese to English: Manager ]

    It just defines a controller class, and the method annotated with @RequestMapping is the way to use the processor @Controller that actually handles the request

(1) Define the bean object of MyController in the SpringMVC configuration file.

   <bean class="com.host.app.web.controller.MyController"/>

(2) In the SpringMVC configuration file, tell Spring where to find the Controller controller marked as @Controller.

   < context:component-scan base-package = "com.host.app.web" />

    //The path is written to the upper layer of the controller (for details of the scan package, see the analysis below)

Configuration of spring-mvc.xml

<!-- Use Annotation to automatically register beans, only scan @Controller -->

  <context:component-scan

   base-package="com.thinkgem.jeesite" use-default-filters="false">

   <!-- If there are multiple base-packages, separate them with "," -->

  <context:include-filter type="annotation" expression="org.springframework.stereotype.Controller"/>

  </context:component-scan>


2. @RequestMapping                       [Chinese to English: Request Mapping ]

Role: process request mapping, used on classes or methods,

         When used in a class, it means that all methods in the class that respond to requests have this address as the parent path.

6 properties:

1、 value, method;

value:      specifies the actual address of the request, the specified address can be in URI Template mode (will be explained later);

method:  specifies the method type of the request, GET, POST, PUT, DELETE, etc.;

2、consumes,produces

consumes: Specify the submitted content type (Content-Type) of the processing request, such as application/json, text/html;

produces:    specifies the returned content type, which is only returned when the (Accept) type in the request header contains the specified type;

3、params,headers

params: Specifies that the request must contain certain parameter values ​​for this method to process.

headers: The specified request must contain certain specified header values ​​in order for this method to process the request.

E.g:

@Controller

@RequestMapping(value = "${adminPath}/sys/log")

public class LogController extends BaseController {

    @Autowired

    private LogService logService;

...


3. @Resource and @Autowired                  [Chinese to English: @Resource and @Autowired ]

are used for bean injection

@Resource is not a Spring annotation, its package is javax.annotation.Resource, which needs to be imported, but Spring supports the injection of this annotation.

1. Common ground

 Both can be written on fields and setter methods. If both are written on the field, then there is no need to write the setter method.

2. Differences

@Autowired  is only injected by type

@Resource    is injected by name by default

Purpose of @Autowired  :

      When using Spring, beans injected by Spring are generally defined as private, and have getter and setter methods, which is cumbersome and increases the amount of code. Using @Autowired can reduce the amount of code.

      Annotations can be placed on member variables or on the set method of member variables. In the former, Spring will directly assign the only bean of the UserDao type to the userDao member variable; in the latter, Spring will call the setUserDao method to assemble the only bean of the UserDao type to the userDao property.

E.g:

public class TestServiceImpl {

    // The following two @Autowired only need to use one

    @Autowired

    private UserDao userDao; // used on the field

    

    @Autowired

    public void setUserDao(UserDao userDao) { // used on property methods

        this.userDao = userDao;

    }

}


4. @PathVariable                                      [Chinese to English: @PathVariable ]

Use : Map the template variables in the request URL to the parameters of the function processing method , that is, take the variables in the uri template as parameters

example:

    @RequestMapping(value = "treeList/{typeAlias}.xml")

    @ResponseBody

    public TreeList treeList(@PathVariable("typeAlias") String typeAlias) {

        

        // If Cache is used and exists in Cache, return directly.

        boolean useCache = Global.getConfig("supcan.useCache") == "true";

        if (useCache){

            Object object = CacheUtils.get(SUPCAN_CACHE, typeAlias);

            if (object != null){

                return (TreeList)object;

            }

        }

    ...


5. @requestParam                                 [Chinese to English: @parameter request ]

@requestParam is mainly used to obtain parameters in the SpringMVC background control layer,

A similar one is request.getParameter("name") ,

It has three common parameters: defaultValue = "0",   // defaultValue means to set the default value.

                                  required = false,       // required is a parameter that must be passed in by boolean setting.

                                  value = "isApp";   // The value value represents the accepted incoming parameter type.

E.g:

    @ModelAttribute

    public CbrcLogData get(@RequestParam(required = false) String id) {

        CbrcLogData entity = null;

        if (StringUtils.isNotBlank(id)) {

            entity = cbrcLogDataService.get(id);

        }   

        return entity;

    }


6. @ResponseBody                               [Chinese to English: @Main Results ]

Function : This annotation is used to convert the object returned by the Controller method into the specified format through the appropriate HttpMessageConverter .

into the body data area of ​​the Response object.

Timing of use : When the returned data is not a page of HTML tags, but data in some other format (such as json, xml, etc.);

【Details】

HttpMessageConverter message converter combined with @ResponseBody

@responsebody indicates that the return result of this method is directly written into the HTTP response body

It is generally used when acquiring data asynchronously . After using @RequestMapping, the return value is usually parsed as a jump path . After adding @responsebody, the return result will not be parsed as a jump path , but written directly into the HTTP response body. For example, asynchronously obtaining json data and adding @responsebody will directly return json data.

The function of @ResponseBody of Spring3 MVC is to write the return value directly into the HTTP response body.

The HttpMessageConverter class is encapsulated in the spring-web-*.RELEASE.jar package

E.g:

@RequestMapping(value = "treeList/{typeAlias}.xml")

    @ResponseBody

    public TreeList treeList(@PathVariable("typeAlias") String typeAlias) {

        // If Cache is used and exists in Cache, return directly.

        boolean useCache = Global.getConfig("supcan.useCache") == "true";

    ...


7. Repository                                   [Chinese to English: @Warehouse ]

Function: applied to the guide layer, and annotated on the daoImpl class.

E.g:

@Repository

public class ActMyBusinessDao extends BaseHibernateDao<ActMyBusiness,String>{

    public Class getEntityClass() {

        return ActMyBusiness.class;

    }

...


8、@ModelAttribute和 @SessionAttributes  

(1) The role of @ModelAttribute

Before all methods of the Controller are called , execute this @ModelAttribute method first

(2) The role of @SessionAttributes

Make properties accessible across properties

E.g:    

          @Controller  

          @RequestMapping("/bbtForum.do")  

           <span style="color: #008000;">@SessionAttributes("currUser"

            //①Name the attribute in ModelMap as the attribute of currUser 

            // Put it in the Session property list so that this property can be accessed across requests

            </span>  

          public class BbtForumController {   

           …  

          @RequestMapping(params = "method=listBoardTopic")  

           public String listBoardTopic(@RequestParam("id")int topicId, User user,  ModelMap model) {  

                 bbtForumService.getBoardTopics (topicId);  

                 System.out.println("topicId:" + topicId);  

                 System.out.println("user:" + user);  

                 model.addAttribute("currUser",user);

                 <span style="color: #008000;">

                  //②Add a property to ModelMap whose property name is currUser

                 </span>  

                return "listTopic";  

           }  

           }  


9、@Service   

声明Service组件


10、@RequestParam

返回叁数@RequestParam(value = "fileUpload", required = false)


11、@RequiresPermissions权限注解

@RequiresPermissions("yzy:eaparam:eaparam:edit")


12、@Param()

叁数与对应xml里的#{}里的内容一致

-----------------------------------------------------------------------

13、@postmapping

    是一个组合注解,是@RequestMapping(method = RequestMethod.POST)的缩写。

---------------------------------------------------------------------------------

14、@GetMapping()

是一个组合注解,是@RequestMapping(method = RequestMethod.GET)的缩写。

------------------------------------------------------------------------

15、@Transactional

在service层加载事务,目的在于关于操作数据库的操作由事务来管理

Related Posts