Spring MVC learning notes 02

Process model data:

If data is needed for jump, VM can use the following methods
	ModelAndView,ModelMap,Map,Model		Data placement request Scope of action
	//Example:
	public String testModelMap(ModelMap mm){   //The returned ModelAndView has both data and view
		Student student = new Student();
		student.setStuNo(111);
		student.setStuName("dagou");
		mm.put("student1", student);
		return "success";	
	}
How to put this information into the session domain? Annotate the class @ SessionAttributes
@SessionAttributes(value="student3","student2")    //If you want to store the student3,student2 object in the request, put the object into the session at the same time
@SessionAttributes(types= {Student.class,Address.class}) //If you want to store the student and address object in the request, put the object into the session at the same time
@ModelAttribute		Use when updating
//The method decorated with @ ModelAttribute will execute before each request. The parameter map.put() of the method can send the queried object as a parameter to the requested method
//Convention that must be satisfied: map.put(k,v) where k must be the name of the method parameter to be queried and lowercase the initial letter. If not, it needs to be identified by @ ModelAttribute
	@ModelAttribute     //The ModelAttribute decorated method is executed before any request
	public void queryStudentBystuNo(Map<String,Object> map) {
		Student student = new Student();
		student.setStuNo(31);
		student.setStuName("zs");
		student.setAge(23);  	  //Simulate the data found in the database
		map.put("stu", student);  //Convention: the key of map is the initial lowercase student of the following method parameter types
	}
	//modify
	@RequestMapping(value="testModelAttribute")
	public String testModelAttribute(@ModelAttribute("stu")Student student){   //The returned ModelAndView has both data and view
		student.setStuName(student.getStuName());
		System.out.println(student.getStuNo()+","+student.getStuName()+","+student.getAge());
		return "success";	
	}

View, view parser

Top level interface of view: View
 Top level interface of view resolver: ViewResolver
Common views and view parsers
InternalResourceView has a subclass, JstlView, which can parse jstl / and implement internationalization operations
		When spring MVC parses jsp, it will use internal resource view by default. If jsp contains jstl language, it will be automatically converted to JstlView
		Internationalization: different display for different regions and countries
Specific steps to achieve internationalization:
1. Create resource file name: base name language region. Properties example: base cn.properties or base.properties 
	The corresponding language of each country in the document
 2. configure springmvc.xml and load the resource file
	<bean id="" class="org.springframework.context.support.ResourceBundleMessageSource">
		<property name="basename" value="i18n"></property>
	</bean>
3. use
InternalResourceViewResolver
index.jsp --> Controller --> success.jsp
 To implement index. JSP -- > success. JSP with springmvc
	< MVC: view controller path = "" view name = "" / > this configuration will transfer all requests to < MVC... / > ignore @ RequestMapping
	If you want < MVC... / > and @ RequestMapping to coexist, you need to add a configuration
	<mvc:annotation-driven></mvc:annotation-driven>
Specify request method:
	return "forward:/views/success.jsp";
	Using the specified jump method forward redirect will not be prefixed by the view parser / views suffix.jsp

Processing static resources: html css js picture video

In spring MVC, static resources cannot be accessed directly. They will be blocked and processed by @ RequestMapping
 Static resource solution:
	If it is processed by @ RequestMapping corresponding to springmvc, if not, it will be sent to tomcat's default servlet for processing
	Add 2 configurations to springmvb.xml:	
		<mvc:annotation-driven></mvc:annotation-driven>
		<mvc:default-servlet-handler/>

Type conversion:

1. Spring MVC comes with some common type converters
Querying stuNo can receive either int type data or String type data
2. Write a custom Converter: (implement Converter interface)
a. Write a custom converter
public class MyConverter implements Converter<String, Student> {
	@Override
	public Student convert(String source) {
		//source receives data from the front end 2-fzz-21
		String[] studentArray = source.split("-");
		Student student = new Student();
		student.setStuNo(Integer.parseInt(studentArray[0]));
		student.setStuName(studentArray[1]);
		student.setAge(Integer.parseInt(studentArray[2]));
		return student;
	}
}
b.Configuration: will MyConverter Add to springmvc in
	<!-- 1.Include custom converters in SpringIOC container -->
	<bean id="myConverter" class="org.fzz.converter.MyConverter"></bean>
	<!-- 2.take myConverter Bring into SpringMVC Converter provided bean in -->
	<bean id="conversionService" class="org.springframework.context.support.ConversionServiceFactoryBean">
		<property name="converters">
			<set><ref bean="myConverter"/></set>
		</property>
	</bean>
	<!-- 3.take conversionService Register to annotation-driven in -->
	<mvc:annotation-driven conversion-service="conversionService"></mvc:annotation-driven>
c.Test converter
	@RequestMapping(value="testConverter")
	public String testConverter(@RequestParam("stuInfo") Student student){   //The returned ModelAndView has both data and view
		System.out.println(student.getStuNo()+","+student.getStuName()+","+student.getAge());
		return "success";	
	}
	//Where @ RequestParam("stuInfo") is the bridge that triggers the converter to receive data that is inconsistent with the target data, find the corresponding converter for conversion

Data format:

SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss")
SpringMVC Many annotations are provided for us to format the data
Implementation steps:
1.To configure:
	<bean id="conversionServiceBean" class="org.springframework.format.support.FormattingConversionServiceFactoryBean"></bean>
2.Using annotations:		
	@DateTimeFormat
	@DateTimeFormat(pattern="yyyy-MM-dd")   Annotate when defining this property
	private Date birthday;
		@RequestMapping(value="testDateTime")
		public String testDateTime(Student student){   //The returned ModelAndView has both data and view
			System.out.println(student.getStuNo()+","+student.getStuName()+","+student.getBirthday());
			return "success";	
		}
	@NumberFormat
		@NumberFormat(pattern = "###,#")
		private int stuNo;

Error message:

public String testDateTime(Student student,BindingResult result,Map<String,Object>)
The data to be verified is brithday in Student. Spring MVC requires that if the verification fails, the error information will be automatically put into the BindingResult after the object
 If you want to pass the error message from the console to the jsp, you can put the error message object into the request domain and get it from the jsp

Data verification:

JSR303, hibernate validator (extension supplement)
Use Hibernate Validator steps:
1.jar
	hiberante-validator.jar
	classmate.jar
	jboss-logging.jar
	validatetion-api.jar
	hibernate-validator-annotation-processor.jar
2.To configure:
	<mvc:annotation-driven></mvc:annotation-driven>
3.Using annotations directly 	
	public class Student{
		@Past			//Only the date before today
		private Date birthday;
	}
	//In the verified Controller, add @ Valid before the verified object

Ajax requests spring MVC and returns data in JSON format

1.jar
jackson-annotations-2.8.7.jar
jackson-core-2.8.7.jar
jackson-databind-2.8.7.jar
2. Create a Handler and add the @ ResponseBody annotation to change the return value of the method into a json array and return it to the foreground
@ResponseBody
@RequestMapping(value="testJson")
public java.util.List<Student> testJson(){ 
	//Simulate the query operation of calling service
	//Three students found
	java.util.List<Student> students = new ArrayList<>();
	students.add(stu1);
	students.add(stu1);
	students.add(stu1);
	return students;	
}
3. Reception of josn at the front desk
<script type="text/javascript">
	$(document).ready(function(){
		$("#testJson").click(function(){
			//Request spring MVC via Ajax
			$.post(
				"handler/testJosn", //server address
				function(result){
					for(var i=0;i<result.length; i++){
						alert(result[i].stuNo+","+result[i].stuName+","+result[i].stuAge)
					}
				}
			);
		});
	});
</script>

Spring MVC implements file upload:

Steps of file upload: Spring MVC can simplify the code of file upload
1.jar
		commons-filedupload.jar
		commons-io.jar
2. Implement the MultipartResolver interface. Spring MVC has provided the implementation class CommonsMultipartResolver to configure the class
	<bean id="multipartResolver" class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
			<property name="defaultEncoding" value="utf-8"></property>
			<property name="maxUploadSize" value="102400"></property>
	</bean>
3. Treatment method
@RequestMapping(value="testUpload")
public String testUpload(@RequestParam("desc")String desc,@RequestParam("file")MultipartFile file) throws IOException{ 
	System.out.println("Document description information:"+desc);
	//Upload files to a hard disk of the server
	InputStream input = file.getInputStream();
	String fileName = file.getOriginalFilename();
	OutputStream out = new FileOutputStream("d:\\"+fileName);
	byte[] bs = new byte[1024];
	int len = -1;
	while((len=input.read(bs))!=-1) {
		out.write(bs,0,len);
	}
	out.close();
	input.close();
	System.out.println("Upload success");
	return "success";	
}

Interceptor:

The principle of interceptor is the same as that of filter. To implement interceptor, spring MVC must implement an interface HandlerInterceptor
1. Write interceptor
public class MyInterceptor implements HandlerInterceptor {		
}
2. Configuration: configure the interceptor written by yourself to spring MVC to intercept all requests by default
<mvc:interceptors>
	<mvc:interceptor>
		<!-- Specify interception path to intercept all requests-->
		<mvc:mapping path="/**"/>
		<!-- Specify no intercept path -->
		<mvc:exclude-mapping path="/handler/welcome"/>
		<bean class="org.fzz.interceptor.MyInterceptor"></bean>
	</mvc:interceptor>
</mvc:interceptors>

Exception handling:

To handle exceptions, springMVC needs to implement the HandlerExceptionResolver interface
 Each implementation class of this interface corresponds to this exception handling method:
ExceptionHandlerExceptionResolver:
The @ ExceptionHandler annotation is mainly provided to handle exceptions
	@ExceptionHandler({ArithmeticException.class,ArrayIndexOutOfBoundsException.class})
	public String handlerArithmeticException(Exception e) {
		System.out.println(e);
		return "error";
	}
Be careful:
	@Method identified by ExceptionHandler. The parameter must be an exception type and cannot contain other types of parameters
 Exception handling path: the shortest priority is the ArithmeticException exception, including the ArithmeticException handling method and the exception handling method priority is the ArithmeticException handling method
 @ExceptionHandler can only catch exception methods in the current class by default,
	If the method with exception can handle in other classes, you need to add another annotation @ controlleradvise
ResponseStatusExceptionResolver: custom exception display page
@ResponseStatus(value=HttpStatus.FORBIDDEN,reason="Array out of bounds!!!")
public class MyArrayException extends Exception{  //Custom exception
}
DefaultHandlerExceptionResolver:
Spring MVC adds some new exceptions based on some common exceptions
	For example:
	 * @see org.springframework.web.servlet.mvc.method.annotation.ResponseEntityExceptionHandler
	 * @see #handleNoSuchRequestHandlingMethod
	 * @see #handleHttpRequestMethodNotSupported
	 * @see #handleHttpMediaTypeNotSupported
	 * @see #handleMissingServletRequestParameter
	 * @see #handleServletRequestBindingException
	 * @see #handleTypeMismatch
	 * @see #handleHttpMessageNotReadable
	 * @see #handleHttpMessageNotWritable
	 * @see #handleMethodArgumentNotValidException
	 * @see #handleMissingServletRequestParameter
	 * @see #handleMissingServletRequestPartException
	 * @see #handleBindException
SimpleMappingExceptionResolver: implement exception handling through configuration
<bean class="org.springframework.web.servlet.handler.SimpleMappingExceptionResolver">
	<property name="exceptionAttribute" value="ex"></property>      
	<property name="exceptionMappings">
		<props>
			<prop key="java.lang.ArithmeticException">error</prop>
		</props>
	</property>
</bean>
value="ex": if an exception occurs, the exception object will be saved in the ex and put into the request field. If it is not written, the default name is exception
Published 55 original articles, won praise 1, visited 674
Private letter follow

Keywords: Spring JSP Session Hibernate

Added by conor.higgins on Fri, 14 Feb 2020 15:10:10 +0200