SPRINGMVC Frame Finishing

Source: Internet
Author: User

Spring MVC
1. The most clearly structured MVC MODEL2 implementation
2.Controller
3.ModelAndView


1.HTTP Request SPRINGMVC Core is the front controller dispatcherservlet in the Web. XML <servlet-name>-servlet.xml Configuration

2.HandlerMapping: Configure to find Handler (Controller)

3.Handler: Processor calls service method for business processing

4. Return data Modelandview (increase and deletion) logical view name is not a real view object

5.ViewResolver: View resolver dispatcherservlet The logical view name into a real view object with the view parser.

6. Get model data models in view view (Jsp/jstl/pdf ...)

7.HTTP response to the client (user)

Springmvc in the Web. XML configuration
<servlet>
<servlet-name>springMVC</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<load-on-startup>1</load-on-startup><!--priority Start-up
</servlet>

<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>

Springmvc-servlet.xml Core configuration file/web-inf/springmvc-servlet.xml
<!--through the bean's name to complete the URL mapping--
<bean name= "/springmvc.html" class= "Cn.bdqn.controller.HelloController"/>
The name is the URL requested by the user through class to find the controller controller that returns Modelandwiew through the view resolver to return the view view to the user.

<!--View Resolver--
<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name= "prefix" value= "/web-inf/jsp/"/>
<property name= "suffix" value= ". jsp"/>
</bean>
I'm going to put it in resource. In the Web. XML configuration
<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:springMVC-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup><!--priority Start-up
</servlet>

<servlet-mapping>
<servlet-name>springMVC</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>


How to Annotate: defaultannotationhandlermapping

<!--using the annotation method to complete the mapping--
<!--using the annotation method to complete the mapping--
<!--let spring scan all classes under the package so that the class that annotated spring annotations takes effect-
<context:component-scan base-package= "Cn.bdqn.controller" ></context:component-scan>
<mvc:annotation-driven/>
by @requestmapping (value = "/hello")
The XXX method of the controller class is then executed by matching the URL of the user request by the value of @requestmapping

@Controller
public class Welcomcontroller {
Find the Hello () method of the controller class by matching the URL of the user request with the value of @requestmapping to execute
@RequestMapping (value = "/hello")
Public String Hello () {
System.out.println ("Hello spring!!!");
return "Hello";//Logical View name
}
}
View Resolver:
1. Match the name of the logical view with the view technology such as JSP
2.InternalResourceViewResolver
Find the View template in the war file for the Web application, and the path to the view template is determined by the logical view name of the appended prefix and suffix
Prefix
Suffix
<!--View Resolver--
<bean class= "Org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name= "prefix" value= "/web-inf/jsp/"/>
<property name= "suffix" value= ". jsp"/>
</bean>
Parameter Passing-1
[Email protected]
2. Passing values directly through function parameters

@RequestMapping (value = "/hello")
public string Hello (@RequestParam (value = "username") string username) {
System.out.println ("Hello Spring!!! Username----->>> "+ username);
return "hello01";//Logical View name
}
@RequestParam (value = "username") the parameters in the request must be written


@RequestMapping (value = "/hello")
public string Hello (string name) {
System.out.println ("Hello Spring!!! Name----->>> "+ name");
return "hello01";//Logical View name
}
The parameters passed through the URL can be obtained directly in the background. But the parameter name must match the parameter name passed by the method or it cannot be obtained

@RequestMapping (value = "/hello")
Model.addattribute ("username", name) is placed into the scope. Extracting data from an El expression
public string Hello (string name, model model) {
Model.addattribute ("username", name);
System.out.println ("Hello Spring!!! Name----->>> "+ name");
return "hello01";//Logical View name
}

@RequestMapping (value = "/hello")
Model.addattribute ("username", name) is placed into the scope. Extracting data from an El expression
Public Modelandview Hello (String name) {
SYSTEM.OUT.PRINTLN (name);
Modelandview model = new Modelandview ();
Model.setviewname ("hello01");//Logical View name
Model.addobject ("username", name);
return model;
}


@RequestMapping (value = "/hello")
Model.addattribute ("username", name) is placed into the scope. Extracting data from an El expression
Public Modelandview Hello (String name) {
SYSTEM.OUT.PRINTLN (name);
Modelandview model = new Modelandview ();
Model.setviewname ("hello01");//Logical View name
Model.addobject (name);//Value ${string} in the foreground is the data type that is taken to value
return model;
}

@RequestMapping (value = "/hello")
Model.addattribute ("username", name) is placed into the scope. Extracting data from an El expression
public string Hello (string name, map<string, object> model) {
SYSTEM.OUT.PRINTLN (name);
Model.put ("name", name), or//value ${string} in the foreground is the data type that is taken to value
return "HELLO01";
}


Parameter Passing-2
by map<spring,object>
Model
The controller is a singleton.


Rest style is not rest technology
1.Representational State transfer Expression Status transfer
2. Traditional search, change, delete URLs and rest-style additions and deletions to the URL comparison
/userview.action?id=12 VS/USER/12
/userdelete.action?id=12 Vs/user/12/delete
/userdelete.action?id=12 vs/user/12/update
3. Request method
GET Read Data query
POST Add Commit
Delete Deletes
PUT modification
He emphasizes that a resource can correspond to multiple views

Creating the Pojo-user Class
HashMap
@RequestMapping (value= "/userlist", Method=requestmethod.get)





@Controller
@RequestMapping (value = "/user")
public class Usercontroller {

private static map<string, object> Map = new hashmap<string, object> ();

Assigning values by static code blocks
static {
Map.put ("1", New User (1, "Zhang San", "123456", "[email protected]"));
Map.put ("2", New User (2, "John Doe", "123456", "[email protected]"));
Map.put ("3", New User (3, "Harry", "123456", "[email protected]"));
}

@RequestMapping (value = "/list", method = Requestmethod.get)
Public String list (model model) {
Model.addattribute ("map", map);
return "User/userlist";
}
}

User List:<br>
<c:foreach var= "ul" items= "${map}" >
Id:${ul.value.id}------
Username:${ul.value.username}------
Password:${ul.value.password}------
Email:${ul.value.email}<br>
</c:forEach>



@RequestMapping (value = "/list", method = Requestmethod.get)
Public String userlist (HttpServletRequest request) {
list<user> list = new arraylist<user> ();
List.add (New User (1, "Zhang San", "123456", "[email protected]"));
List.add (New User (2, "John Doe", "123456", "[email protected]"));
List.add (New User (3, "Harry", "123456", "[email protected]"));
Request.setattribute ("list", list);
return "User/userlist";

}


User List:<br>
<c:foreach var= "user" items= "${list}" >
Id:${user.id}------
Username:${user.username}------
Password:${user.password}------
Email:${user.email}<br>
</c:forEach>

The scope of the model is a request level

Exception handling

JSR303 is a set of JavaBean parameter verification standards, it defines a lot of commonly used check annotations, we can directly add these annotations to our JavaBean properties, you can check the need to verify the time. The annotations are as follows:
@NotNull annotation element must be non-null
@Null annotation element must be empty
@Digits Verify that the number is legal
@Future Verify that after the current system time
@Past verify that before the current system time
@Max Verify that the value is less than or equal to the maximum specified integer value
@Min verifies whether the value is greater than or equal to the minimum specified integer value
@Pattern verifies that the string matches the specified regular expression
@Size Verify that the element size is within the specified range
@DecimalMax Verify that the value is less than or equal to the maximum specified decimal value
@DecimalMin Verify that the value is greater than or equal to the minimum specified decimal value
@AssertTrue The annotated element must be true
@AssertFalse The annotated element must be false
Hibernate Validator extends the validation annotations on the basis of JSR303, extending annotations as follows:
@Email The annotated element must be an e-mail address
@Length the size of the annotated string must be within the specified range
@NotEmpty The annotated string must be non-empty
@Range The annotated element must be within the appropriate range



<!--processing character encoding filter--
<filter>
<filter-name>encodingFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>encodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>



@RequestMapping (value = "/addsave", method = Requestmethod.post)
Public String addsave (@Validated user user, Bindingresult bindingresult) {
if (Bindingresult.haserrors ()) {
Return "User/add"//If the user input is incorrect, it will return add re-enter
}
Map.put (User.getid () + "", user);
return "Redirect:/user/list";
}

/**
* Rest Style
* @param ID
* @param model
* @return
*/
@RequestMapping (value = "/view/{id}", method = Requestmethod.get)
public string view (@PathVariable string ID, model model) {
SYSTEM.OUT.PRINTLN (ID);
Model.addattribute ("User", Map.get (ID));
return "User/view";
}

/**
* First echo in Modify
* @param ID
* @param user
* @return
*/
@RequestMapping (value = "/{id}/update", method = Requestmethod.get)
public string update (@PathVariable string ID, model model) {
Model.addattribute (Map.get (id));
return "User/update";
}

/**
* Modify @pathvariable Rest style get parameter {ID} into Parameter form
* @param ID
* @param user
* @param bindingresult
* @return
*/
@RequestMapping (value = "/{id}/update", method = Requestmethod.post)
public string update (@PathVariable string ID, @Validated user user,
Bindingresult Bindingresult) {
if (Bindingresult.haserrors ()) {
return "User/update";
}
Map.put (User.getid () + "", user);
return "Redirect:/user/list";
}

@RequestMapping (value = "/{id}/delete", method = Requestmethod.get)
public string Detele (@PathVariable string id) {
Map.Remove (ID);//delete
return "Redirect:/user/list";
}
1. Exception Handling
1. Local Exception handling: @ExceptionHandler
2. Global exception Handling: Simplemappingexceptionresolver
2. Use the Servlet API object as the entry parameter
1.HttpSession
2.HttpServletRequest
3.HttpServletResponse
Map<key,value>

Structure of the hash table
1 map<object,object>
Map key= memory address of "t01" value

<!--global exception handling:simplemappingexceptionresolver-->

<!--global Exceptions--
<bean class= "Org.springframework.web.servlet.handler.SimpleMappingExceptionResolver" >
<property name= "Exceptionmappings" >
<props>
<prop key= "Cn.bdqn.bean.UserException" >error</prop>
</props>
</property>
</bean>
The foreground gets exception information
${exception.message} <br>

<!--configuration static file access Springmvc cannot access the static file and needs to be mapped to a URL path for access--
<mvc:resources location= "/statics/" mapping= "/statics/**"/>
The page needs to be introduced <link Href=<%=request.getcontextpath ()%>/statics/css/main.css rel= "stylesheet" style= "Text/css"/ >

Process file upload-Single file upload
Guide package: Commons-fileupload-1.2.2.jar, Commons-io-2.4.jar
Add a File Upload field to the Add page form
Modify Usercontroller's Add () method to receive uploaded files
Configuring the multipart file processor in spring

File Upload


<!--config file upload multipartresovler--
<bean id= "Multipartresolver" class= "Org.springframework.web.multipart.commons.CommonsMultipartResolver" >
<property name= "maxuploadsize" value= "1000000"/>
</bean>

@RequestMapping (value = "/addsave", method = Requestmethod.post)
Public String addsave (@Validated user User, Bindingresult bindingresult,
@RequestParam multipartfile[] Attachs, httpservletrequest request) {
if (Bindingresult.haserrors ()) {
Return "User/add"//If the user input is incorrect, it will return add re-enter
}
Get
String upload = Request.getsession (). Getservletcontext ()
. Getrealpath ("/statics/upload");

Non-null validation file.separator automatic recognition "/"
try {
Multiple file uploads
for (Multipartfile Attach:attachs) {
if (!attach.isempty ()) {
File File = new file (upload + file.separator
+ Attach.getoriginalfilename ());
Fileutils.copyinputstreamtofile (Attach.getinputstream (),
file);
}
}
} catch (IOException e) {
E.printstacktrace ();
}

Map.put (User.getid () + "", user);
return "Redirect:/user/list";
}
Add Page:</br>
<!--do not write action default submit to add-
<fm:form modelattribute= "user" action= "user/addsave" method= "post" enctype= "Multipart/form-data" >
Id:<fm:input path= "id"/></br>
Username:<fm:input path= "UserName"/><fm:errors path= "UserName"/></br>
Password:<fm:input path= "password"/><fm:errors path= "password"/></br>
Email:<fm:input path= "Email"/><fm:errors path= "email"/></br>
Attach:<input type= "File" Name= "Attachs"/></br>
<input type= "File" Name= "Attachs"/></br>
<input type= "File" Name= "Attachs"/></br>
<input type= "Submit" value= "Submission" >
</fm:form>
Spring MVC returns JSON data
1. Import jar Package: Jackson-all-1.9.11.jar
2.RequestMapping (value= "/{username}", method=requestmethod.get,param= "JSON)
3.ResponseBody

params= "JSON" means: When you access the view method, you must have a parameter JSON
@RequestMapping (value = "/view/{id}", method = Requestmethod.get, params = "json")
@ResponseBody
Public User view (@PathVariable String ID) {
return Map.get (ID);
}

SPRINGMVC Frame Finishing

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.