SPRING-MVC case: Spitter's Notes

Source: Internet
Author: User
Tags apache tomcat

Source Address: Https://github.com/Young4Dream/yan/tree/master/Maven_spittr

Notes:

1. When Dispatcherservlet is started, the spring application context is created and the bean declared in the configuration file or configuration class is loaded. In the Getservletconfigclasses () method, the bean that is defined in the Webconfig configuration class is used when Dispatcherservlet loads the application context. In Springweb applications, however, there is usually another application context, and another application context is created in Contextloaderlistener. We want Dispatcherservlet to load the beans that contain the Web components, such as controllers, view resolvers, and processor mappings, and two contextloaderlistener to load the other beans in the app. These beans are typically the middle-tier and data-tier components that drive the application backend. In fact Abstractannotationconfigdispatcherservletinitializer will create both Dispatcherservlet and Contextloaderlistener. The class with @configuration annotations returned by the Getservletconfigclasses method will be used to define the bean in the Dispatcherservlet application context. The Getrootconfigclasses method returns a class with @configuration annotations that will be used to configure the bean in the context of the app Contextloaderlistener created.
2. Set Webmvcconfigureradapter as the parent class for webconfig, to configure static resources, and override the Configuredefaultservlethandling method, and makes the default servlet effective: Configurer.enable ();
GET from @requestmapping (method=get,value= "/") in 3.Controller need to introduce import static Org.springframework.web.bind.annotation.RequestMethod.GET;
4. Starting with Spring3.2, we can test the controller in the SPRINGMVC in the same way as the controller, not just as a pojo. Spring now contains a mechanism for mocking Spring MVC and executing HTTP requests against the controller. In this case, there is no need to start the Web server and Web browser when testing the controller. Be aware of the reference static package!!!
5. The class-level @requestmapping equals the namespace, if the class-level mapping is "/home" and the method-level mapping is "/method", the action to be specified when the view name returned by this method is "/home/ Method
The [email protected] parameter is the string[] type, which means you can specify multiple actions, such as {"/", "/Home"}, which means that all two are valid
The 7.Model type is actually a map, which is passed to the view so that the data can be rendered to the client, and when the Model.addattribute () method is called and no key is specified, the key is inferred from the worthwhile object type, if it is list< Book&gt, the default is Booklist, which may be used later with the Modelandview type, which is not investigated here first.
8. If you want to explicitly declare key, you can also specify, Model.addattribute ("key", Object obj)
9. If you want to use a non-spring type, you can also use map instead of Model,model.addattribute () to change to Model.put (), see Principle https://zhidao.baidu.com/question/ 564038740.html
10. When there is a method to construct a parameter, be sure to add the non-parametric construction method to the class of the corresponding Bean!!!!!!!!!!!!!!!!!! Otherwise the no default constructor found exception will be reported at startup
11. This error occurs when the Java file: The type javax.servlet.ServletException cannot be resolved. It is indirectly referenced from required. class files, you only need to add Servlet-api.jar in the Tomcat Lib directory
12.fn:length () is a jstl function that returns the length of a string or the number of elements in the collection.
13.<mvc:annotation-driven/> equivalent to registering the defaultannotationhandlermapping and annotationmethodhandleradapter two beans, Configure some messageconverter. This resolves the use premise configuration of the @controller annotations.
14.<context:annotation-config/> is a scan of the package, implementing a comment-driven bean definition, and the bean is automatically injected into the container for use. That is, the injection and use of the bean that resolves the class of the @controller identity.
15. If the configuration is not <mvc:annotation-driven/&gt, then all controller may not parse, all when there is no matching processing request class, go to <mvc: Default-servlet-handler/> is the default servlet processing. After <mvc:annotation-driven/> is added, the corresponding do request is handled by the controller, while the static resource is handled by the default servlet because there is no corresponding controller. In short, no corresponding controller will be processed by the default servlet OK.
16. The inserted SQL statement is best written, otherwise it will be misplaced because of the wrong order:
String sql= "INSERT into Spitter (Id,firstname,lastname,username,password,email) VALUES (" +
"Seq_spitter.nextval,:firstname,:lastname,:username,:p assword,:email" +
")";
17. Jump Personal Information page times: Mapped class is not specified exception.
Reason: did not pass Spitter.class in.
Solution: Rowmapper=new beanpropertyrowmapper<spitter> (Spitter.class);
18. When you develop a project, if you choose the Spring MVC Framework, and you use the spring label in the foreground, then you are likely to appear in this situation.
Javax.servlet.jsp.JspTagException:Neither Bindingresult nor plain target object for Bean name ' command ' available as requ EST attribute
Method: 1 Throws an exception cause, 2 is the exception workaround.
1. Reason: Enter the spring:bind tag source code you can see
Object target = Requestcontext.getmodelobject (beanname);
if (target = = null) {
throw new IllegalStateException ("Neither Bindingresult nor plain target object for Bean name '" +
Beanname + "' Available as request attribute");
}
Beanname= <spring:bind path= "COMMAND.SPJG" > Green section
If you are making a request directly to a page, the object is not command in request
2.
On the page, add
<jsp:usebean id= "command" class= "Com.ztenc.proj.bean.AFRFOAP" scope= "Request" ></jsp:useBean>
The red part fills in your binding class
Public String Register (@Valid @ModelAttribute ("Spitter") spitter Spitter,bindingresult errors) {
The 19.BindingResult and errors also have the same effect as the checksum, which is located in the Org.springframework.validation package
20. Achieve Internationalization:
1. Use spring's <%@ taglib prefix= "s" uri= "Http://www.springframework.org/tags"%> in the <s:message/> implementation;
2. Configuration information Source: Resourcebundlemessagesource or Reloadableresourcebundlemessagesource, respectively, with A and B McCartney
A scheme is configured under the root path, the name is related to the configuration of the BaseName, such as: Basename= "A", then create a new A.properties file under the root path;
The B scheme is configured throughout the system and can be decorated with classpath or file
3. How to use: <s:message code= "key"/>
21.Multipart file upload See Xmind file
22. Handling Exceptions
22.1 for anomalies that can be converted into httpstatus
1. Create a class that handles some kind of exception and let it inherit runtimeexception
public class Spittlenotfoundexception extends runtimeexception{}
2. Add the @responsestatus annotation, indicate the value of the corresponding httpstatus, and customize the reason
@ResponseStatus (value=httpstatus.not_found,reason= "spittle not FOUND")
3. Example: Add a try-catch block to the relevant method (Controller or DAO layer):
try {
spittle = Jt.queryforobject (sql, RowMapper, id);
} catch (Exception e) {
throw new Spittlenotfoundexception ();
}
4. When an error occurs, the following information is displayed:
HTTP Status 404-spittle not Found
Type Status Report
Message Spittle not Found
Description The requested resource is not available.
Apache tomcat/7.0.65
22.2 for exceptions with no corresponding httpstatus: such as inserting data repeatedly
1. Create a class that handles exceptions
public class Duplicatespitterexception extends runtimeexception{}
2. A new method at the controller layer that specifies that the corresponding logical view name is specified when there is a duplicatespitterexception exception in this class
@ExceptionHandler (Value=duplicatespitterexception.class)
Public String Handleduplicatespitter () {
return "Error/error";
}
[Email protected] is the role of listening to duplicatespitterexception, as long as the exception thrown Duplicatespitterexception class will be shifted to the corresponding view
4. This approach can handle duplicatespitterexception exceptions thrown in the same controller class
22.3 Handling Global Exceptions
1. Create a class that defines a global exception: public class Appwideexception extends runtimeexception{}
2. Create a class that specifically handles global exceptions, which is actually a controller and adds @controlleradvice on its class so that it can listen to all the exceptions thrown by the controller layer
3. Defining the handling of global exceptions in Appwideexceptioncontroller, specifying a logical view
4. If the exception heard by the @controlleradvice has a defined treatment in this class, it will be executed according to this rule, such as defining Appwideexception.class, snapping to execute error/apperror processing
Package Com.spring.mvc.controller;

Import Org.springframework.web.bind.annotation.ControllerAdvice;
Import Org.springframework.web.bind.annotation.ExceptionHandler;

Import com.spring.mvc.web.APPWideException;

@ControllerAdvice
public class Appwideexceptioncontroller {
@ExceptionHandler (Value=appwideexception.class)
Public String Appwideexceptionhandler () {
return "Error/apperror";
}
}
23. Cross-Redirect request data
23.1 can use Redirect:/spitter/{username}, if: Model.addattribute ("username", spitter.getusername ());
23.2 If there are extra parameters, such as Model.addattribute ("id", Spitter.getid ()), then it will become .../spitter/yan?id=***;
23.3 Use Model.addflashattribute ("Spitter", Spitter) to pass data except string and numeric types, which is shorter than the session until the scope is redirected.


SPRING-MVC case: Spitter's Notes

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.