4.5, Servletforwardingcontroller
Forward the received request to a named servlet, with the following specific examples:
Package cn.javass.chapter4.web.servlet; public class Forwardingservlet extends HttpServlet { @Override protected void doget (HttpServletRequest req, HttpServletResponse resp) throws Servletexception, IOException { resp.getwriter (). Write ("Controller forward to Servlet "); } }
<servlet> <servlet-name>forwarding</servlet-name> <servlet-class> Cn.javass.chapter4.web.servlet.forwardingservlet</servlet-class> </servlet>
<!-on Chapter4-servlet.xml Configuration processor-- <bean name= "/forwardtoservlet" class= " Org.springframework.web.servlet.mvc.ServletForwardingController "> <property name=" Servletname "value=" Forwarding "></property> </bean>
When we request/forwardtoservlet, it is forwarded to the servlet processing with the name "forwarding", which is optional for the servlet-mapping tag configuration of the Sevlet.
4.6, Basecommandcontroller
The command controller general base class provides the following functionality support:
1. Data binding: The request parameter is bound to a command object, which is not a GOF command design mode, where the command object refers to any Pojo object that binds the request parameter;
Commandclass: Represents a Command object implementation class, such as Usermodel;
CommandName: Represents the name of the command object placed in the request (the default command), Request.setattribute (CommandName, commandobject);
2, the Authentication function: Provides the validator registration function, the registered authenticator verifies the Command object property data is legitimate;
Validators: The validator is injected through this property to verify that the Command object property is legitimate;
The abstract class does not provide process functionality, but it provides some common functionality that is actually used in its subclasses.
4.7, Abstractcommandcontroller
Command controller, can implement the controller to create a command controller, the controller can automatically encapsulate the request parameters to a command object, but also provides a validation function.
1, create the command class (is the ordinary JavaBean class/pojo)
Java code copy content to clipboard package Cn.javass.chapter4.model; public class Usermodel { private String username; private String password; Omit Setter/getter }
2. Implement the Controller
Package Cn.javass.chapter4.web.controller; Omit import public class Myabstractcommandcontroller extends Abstractcommandcontroller { public Myabstractcommandcontroller () { //SET Command object implementation class Setcommandclass (Usermodel.class); } @Override protected Modelandview handle (HttpServletRequest req, HttpServletResponse resp, Object command, Bindexception errors) throws Exception { //Convert the Command object to the actual type Usermodel user = (usermodel) command; Modelandview mv = new Modelandview (); Mv.setviewname ("Abstractcommand"); Mv.addobject ("user", user); return mv; } }
<!-on Chapter4-servlet.xml Configuration processor-- <bean name= "/abstractcommand" class= " Cn.javass.chapter4.web.controller.MyAbstractCommandController "> <!--can also be implemented by dependency injection injection commands--- <! --Property Name= "Commandclass" value= "Cn.javass.chapter4.model.UserModel"/--> </bean>
Main content under <!-web-inf/jsp/abstractcommand.jsp view--
When we enter "http://localhost:9080/springmvc-chapter4/abstractCommand?username=123&password=123" in the browser, The request parameters username and password are automatically bound to the Command object, and bindings are bound according to the JavaBean naming specification;
4.8, Abstractformcontroller
The base class for command controllers that support form submissions with steps, which can be done by using the controller:
1, define the form processing (form rendering), and get Command object from the controller to build the form;
2, submit form processing, when the user submits the form content, Abstractformcontroller can bind the data requested by the user to the Command object, You can verify the contents of the form and process the Command object.
@Override rotected modelandview handlerequestinternal (httpservletrequest request, httpservletresponse response) throws Exception { //1, is the form submitted? The method is implemented as ("POST". Equals (Request.getmethod ())), that is, the post represents the form submission if (isformsubmission (Request)) { try { Object Command = GetCommand (request); Servletrequestdatabinder Binder = bindandvalidate (request, command); Bindexception errors = new Bindexception (Binder.getbindingresult ()); The form submission should be put into the method implementation return Processformsubmission (Request, Response, command, errors); } catch (Httpsessionrequiredexception ex) { //Omit part of code return Handleinvalidsubmit (Request, response);} } else { //2, the presentation is a form display, and the method is then transferred to the ShowForm method, so we need to overwrite showform to complete the form display return Shownewform (Request, response) ;
bindonnewform: Whether to bind the request parameter to the form object when the form is being displayed, by default false, not bound;
Sessionform: Session form mode, if on (true), the form object is placed in the session, so that data can be guaranteed to be not lost across multiple requests (this is often used in multi-step forms, Detailed Abstractwizardformcontroller), default false;
Object Formbackingobject (HttpServletRequest request) : The Form object to be used when the form is presented (the default data to be displayed by the Form object form), By default the CommandName exposes to the presentation form;
Map Referencedata (httpservletrequest request, Object command, Errors Errors): Some reference data needed to present the form (e.g., user registration, You may need to select a workplace where this data can be provided), such as:
Protected map Referencedata (HttpServletRequest request) throws Exception { Map model = new HashMap (); Model.put ("CityList", citylist); return model; }
This allows you to get CityList data on the form Presentation page.
Simpleformcontroller inherits this class and provides simpler forms of process control.
4.9, Simpleformcontroller
Provides a better two-step form support:
1, prepare to display the data, and to the form display page;
2, submit data data for processing.
The first step is to show:
Next, let's write a user registration example to learn:
(1 , Controller
Package Cn.javass.chapter4.web.controller; Omit import public class Registersimpleformcontroller extends Simpleformcontroller {public registe Rsimpleformcontroller () {setcommandclass (Usermodel.class);//Set Command object implementation class Setcommandname ("us ER ");//Set the name of the Command object}//form object, providing form data when presenting the form (using CommandName to put the request) protected object Formbackingobject (HttpServletRequest request) throws Exception {Usermodel user = new Usermodel (); User.setusername ("Please enter user name"); return user; }//provide some additional data needed to display the form protected Map Referencedata (HttpServletRequest request) throws Exception { Map map = new HashMap (); Map.put ("CityList", Arrays.aslist ("Shandong", "Beijing", "Shanghai")); return map; } protected void Dosubmitaction (Object command) throws Exception {Usermodeluser = (usermodel) command; TODO invokes the Business object processing System.out.println (user); } }
Setcommandclass and the Setcommandname : the implementation class and name of the command object are set separately;
Formbackingobject and the Referencedata : provides the view required for form presentation;
dosubmitaction : used to perform form submission actions, called by the OnSubmit method, and can be processed directly using the Dosubmitaction method if no request/Response object or data validation is required.
(2 , Spring Configuration (Chapter4-servlet.xml )
<bean name= "/simpleform" class= "Cn.javass.chapter4.web.controller.RegisterSimpleFormController" > <property name= "FormView" value= "register"/> <property name= "Successview" value= "redirect:/success"/ > </bean> <bean name= "/success" class= "Cn.javass.chapter4.web.controller.SuccessController"/ >
FormView : represents the page that appears when the form is displayed;
Successview : Indicates the page that is displayed when processing succeeds, "redirect:/success" means redirect to/success controller after successful processing, prevent form repeating submission;
The function of the "/success" Bean is to display a success page, which is not listed here.
(3 , view pages
<!--register.jsp Registration Display page- <form method= "POST" > username:<input type= "text" name= "username" Value= "${user.username}" ><br/> password:<input type= "password" name= "username" ><br/> city:<select> <c:foreach items= "${citylist}" var= "City" > <option>${city}</ option> </c:forEach> </select><br/> <input type= "Submit" value= "register"/> </form>
Here, you can use ${user.username} to obtain form support data to Formbackingobject settings, using ${citylist} for Referencedata settings;
To this end of a simple two-step form, but this form has the problem of repeating the form, and the Form object to the page binding is by hand, we will learn the Spring tag library (provide automatic binding form object to the page).
4.10, Cancellableformcontroller
A form controller that can be canceled, inherits Simpleformcontroller, and provides extra cancellation form function.
1 , form display: same as Simpleformcontroller;
2 , form cancellation: same as Simpleformcontroller;
3 , Form successfully submitted: The cancellation function is handled by onCancel (Object command), and by default returns the logical view name specified by the Cancelview property.
So how do you decide to cancel it? If a parameter named "_cancel" is in the request, the form is canceled. You can also modify parameter names (such as "_cancel.x", etc.) by Cancelparamkey.
(1 , Controller
Replication Registersimpleformcontroller A copy named Cancancelregistersimpleformcontroller, adding the cancellation function to the processing method implementation:
@Override protected Modelandview onCancel (Object command) throws Exception { Usermodel user = (Usermodel) command; TODO invokes the Business object processing System.out.println (user);
OnCancel : Implement cancellation logic within this function method, the OnCancel method of the parent class returns the logical view name specified by the Cancelview property by default
(2 , Spring Configuration (Chapter4-servlet.xml )
<bean name= "/cancancelform" class= " Cn.javass.chapter4.web.controller.CanCancelRegisterSimpleFormController "> <property name=" FormView " value= "register"/> <property name= "Successview" value= "redirect:/success"/> <property name= "Cancelview" value= "Redirect:/cancel"/> </bean> <bean name= "/cancel" class= " Cn.javass.chapter4.web.controller.CancelController "/>
Cancelparamkey : used to determine whether the request parameter name is canceled, the default is _cancel, that is, if the request parameter data contains the name _cancel is canceled, will call OnCancel function processing method;
Cancelview : represents the page that is displayed at the moment of cancellation; "redirect:/cancel" indicates that it is redirected to the/cancel controller after successful processing, preventing the form from repeating the submission;
The function of the "/cancel" Bean is to display the cancellation page, which is not listed here (see Code).
(3 , view page (Modify register.jsp )
Input type="Submit" name= "_cancel" value="Cancel"/>
The function of the Submit button is to cancel, because Name="_cancel", that is, the request will have a parameter named _cancel, so the OnCancel function processing method will be performed.
(4 , testing:
Enter "Http://localhost:9080/springmvc-chapter4/canCancelForm" in the browser, first to the Display view page, click "Cancel button" will redirect to "http://localhost:9080/ Springmvc-chapter4/cancel ", stating that the cancellation was successful.
Actual projects may appear such as some of the website's perfect profile is multiple pages (that is, multi-step), how should it be implemented? Let's take a look at the support class Abstractwizardformcontroller provided by spring WEB MVC for multi-step forms.
SPRINGMVC Study Summary (iii)--controller interface detailed (2)