SpringMvc entry 3 ---- controller 1, springmvc entry ----

Source: Internet
Author: User

SpringMvc entry 3 ---- controller 1, springmvc entry ----

 

In the traditional Spring MVC development method, you must configure instance and request ing for each controller class in the Bean configuration file and enable each controller class to implement or expand framework-specific interfaces or base classes. This is not flexible enough.

If Spring MVC can automatically detect your controller class and request ing, it can reduce the workload required for configuration.

Spring2.5 supports annotation-based controller development.

Spring can automatically discover your Controller class through the @ Controller annotation and request ing in the @ RequestMapping annotation, which saves you the trouble of configuring them in the Bean configuration file. In addition, if annotations are used, the Controller class and handler method are more flexible in accessing context resources (such as request parameters, model attributes, and session attributes.

Commonly used annotations

1. @ Controller

2. @ RequestMapping

3. @ RequestParam, @ PathVariable, @ CookieValue

4. ModelAndView

@ Controller annotation can mark any class as a Controller class. Unlike traditional controllers, the labeled controller classes do not need to implement framework-specific interfaces or expand the framework-specific base classes.

Within the Controller class, the @ RequestMapping annotation may be added to one or more handler methods.

The signature of the processing method is flexible. You can specify any name for the handler method and define any of the following types as its method parameters. Here, we only mention common parameter types. For a complete list of valid parameter types, see the Spring document for configuring annotation-based controllers.

 

Common parameter types

 

1. HttpServletRequest, HttpServletResponse, or HttpSession.

2. added any type of request parameters with the @ RequestParam Annotation

3. added any type of model attributes annotated with @ ModelAttribute.

4. Any type of command object for Spring to Bind Request Parameters

5. Map or ModelMap for processing program methods to add attributes to the model

6. Errors or BindingResult to allow the handler method to access the binding and verification results of the command object

7. SessionStatus: Notify the handler method of session processing completion

Common return value types

The return type of the handler method can be ModelAndView, Model, Map, String, and void.

Before creating an annotation-based controller, you must construct a web application context to process the annotation.

First, to enable Spring to automatically detect the Controller using the @ Controller annotation, you must use the <context: component-scan> element to enable the Spring component scanning feature.

Next, Spring MVC can map requests to the Controller class and processing method based on @ RequestMapping.

To make it take effect, you must register the DefaultAnnotationHandlerMapping instance and AnnotationMethodHandlerAdapter instance in the context of the web application.

They process the @ RequestMapping annotation at the class level and method level respectively.

 

ModelAndView

 

The ModelAndView constructed by this constructor cannot be used directly. It should be because no view is specified or the corresponding model object is bound. Of course, the model object is not mandatory, but the view is indeed required.

Instances constructed using this constructor are mainly used to add view settings and model objects to them in the future.

 

You can set a view for a ModelAndView instance by using setViewName (String viewName) and setView (View view ). The former uses viewName, and the latter uses a pre-constructed View object. The former is commonly used. In fact, View is an interface, rather than a specific class that can be constructed. We can only obtain the View instance through other channels. For viewname, it can be either the jsp name or the name defined by tiles, depending on how the ViewNameResolver understands this view name. How to obtain the View instance will be studied later.

 

It is complicated to set a model for a ModelAndView instance. You can use the following three methods:

 

AddObject (Object modelObject)

 

AddObject (String modelName, Object modelObject)

 

AddAllObjects (Map modelMap)

 

ModelAndView can receive objects of the Object type. ModelAndView regards it as one of its many models. When using an Object, you must specify a name. ModelAndView can also receive objects without explicit names, because ModelAndView will call the. getVariableName () method of the Conventions class defined by spring to generate a name for this model. Obviously, the model name is required.

 

The naming rule for Conventions. getVariableName () is to use the lower-case mode of the object class name as the model name. When this model is a set or array, the Class Name of the first element of the set plus s is used as the model name.

ModelAndView can also receive Map objects. ModelAndView regards the elements in the Map as models rather than the Map itself. However, other collection classes can use themselves as model objects. In fact, ModelAndView's support for model comes from the class ModelMap, which inherits from HashMap.

DEMO structure:

Web. xml configuration file:

<? Xml version = "1.0" encoding = "UTF-8"?>

<Web-app xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"

Xmlns = "http://java.sun.com/xml/ns/javaee"

Xsi: schemaLocation = "http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"

Id = "WebApp_ID" version = "2.5">

<Display-name> SpringMvc02 </display-name>

<Welcome-file-list>

<Welcome-file> index. jsp </welcome-file>

</Welcome-file-list>

<Servlet>

<Servlet-name> springmvc </servlet-name>

<Servlet-class> org. springframework. web. servlet. DispatcherServlet </servlet-class>

<Init-param>

<Param-name> contextConfigLocation </param-name>

<Param-value> classpath: spring-mvc.xml </param-value>

</Init-param>

</Servlet>

<Servlet-mapping>

<Servlet-name> springmvc </servlet-name>

<Url-pattern> *. do </url-pattern>

</Servlet-mapping>

</Web-app>

 

Spring-mvc.xml configuration file:

<? Xml version = "1.0" encoding = "UTF-8"?>

<Beans xmlns = "http://www.springframework.org/schema/beans"

Xmlns: xsi = "http://www.w3.org/2001/XMLSchema-instance"

Xmlns: p = "http://www.springframework.org/schema/p"

Xmlns: context = "http://www.springframework.org/schema/context"

Xsi: schemaLocation ="

Http://www.springframework.org/schema/beans

Http://www.springframework.org/schema/beans/spring-beans.xsd

Http://www.springframework.org/schema/context

Http://www.springframework.org/schema/context/spring-context.xsd>

<! -- Use annotation packages, including subsets -->

<Context: component-scan base-package = "com"/>

<! -- View parser -->

<Bean id = "viewResolver"

Class = "org. springframework. web. servlet. view. InternalResourceViewResolver">

<! -Prefix -->

<Property name = "prefix" value = "/WEB-INF/jsp/"/>

<! -Suffix -->

<Property name = "suffix" value = ". jsp"> </property>

</Bean>

</Beans>

Model class Student. java:

Public class Student {

Private int id;

Private String name;

Private int age;

Public Student (){

Super ();

}

Public Student (int id, String name, int age ){

Super ();

This. id = id;

This. name = name;

This. age = age;

}

<! -- The get and set methods below are omitted -->

}

StudentController:

@ Controller

@ RequestMapping ("/student ")

Public class StudentController {

 

Private static List <Student> studentList = new ArrayList <Student> ();

// Add only once, use static

Static {

StudentList. add (new Student (1, "Zhang San", 11 ));

StudentList. add (new Student (2, "Li Si", 12 ));

StudentList. add (new Student (3, "Wang Wu", 13 ));

}

@ RequestMapping ("/list ")

Public ModelAndView list (){

ModelAndView mav = new ModelAndView ();

Mav. addObject ("studentList", studentList); // you can call the model method to pass the studentList object to the view.

Mav. setViewName ("student/list"); // The View name corresponds to student/list. jsp. When student/list. do is called, the page will be returned to student/list. jsp.

Return mav;

}

@ RequestMapping ("/preSave ")

Public ModelAndView preSave (@ RequestParam (value = "id", required = false) String id) {// parameter id. The id here is equivalent to the request in servlet. getPaXXx ("id"), required = false, indicating that the parameter is not a required parameter and can be left blank. The default value is true. Another common parameter is DefaultValue.

ModelAndView mav = new ModelAndView ();

If (id! = Null ){

Mav. addObject ("student", studentList. get (Integer. parseInt (id)-1 ));

Mav. setViewName ("student/update ");

} Else {

Mav. setViewName ("student/add ");

}

Return mav;

}

}

 

Jsp page:

Add. jsp

<Body>

<Form action = "$ {pageContext. request. contextPath}/student/save. do" method = "post">

<Table>

<Tr>

<Th colspan = "2"> Student addition </th>

</Tr>

<Tr>

<Td> name </td>

<Td> <input type = "text" name = "name"/> </td>

</Tr>

<Tr>

<Td> age </td>

<Td> <input type = "text" name = "age"/> </td>

</Tr>

<Tr>

<Td colspan = "2">

<Input type = "submit" value = "submit"/>

</Td>

</Tr>

</Table>

</Form>

</Body>

List. jsp

Reference before page: <% @ taglib prefix = "c" uri = "http://java.sun.com/jsp/jstl/core" %>

<Body>

<A href = "$ {pageContext. request. contextPath}/student/preSave. do"> Add students </a>

<Table>

<Tr>

<Th> Number </th>

<Th> name </th>

<Th> age </th>

<Th> operation </th>

</Tr>

<C: forEach var = "student" items = "$ {studentList}">

<Tr>

<Td >$ {student. id} </td>

<Td >$ {student. name} </td>

<Td >$ {student. age} </td>

<Td> <a href = "$ {pageContext. request. contextPath}/student/preSave. do? Id =$ {student. id} "> modify </a> </td>

</Tr>

</C: forEach>

</Table>

</Body>

Update. jsp

<Body>

<Form action = "$ {pageContext. request. contextPath}/student/save. do" method = "post">

<Table>

<Tr>

<Th colspan = "2"> Student modification </th>

</Tr>

<Tr>

<Td> name </td>

<Td> <input type = "text" name = "name" value = "$ {student. name}"/> </td>

</Tr>

<Tr>

<Td> age </td>

<Td> <input type = "text" name = "age" value = "$ {student. age}"/> </td>

</Tr>

<Tr>

<Td colspan = "2">

<Input type = "hidden" name = "id" value = "$ {student. id}"/>

<Input type = "submit" value = "submit"/>

</Td>

</Tr>

</Table>

</Form>

</Body>

 

Index. jsp redirection page

<% @ Page language = "java" contentType = "text/html; charset = ISO-8859-1"

PageEncoding = "ISO-8859-1" %>

<% Response. sendRedirect ("student/list. do"); %>

 

Test: http: // localhost: 8080/SpringMvc02/

Student/save. do has not been written yet. Modify and add it in the next article.

 

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.