1. Getting started with SpringMVC basics, create a HelloWorld program
1. First, import the jar package required by SpringMVC.
2. Add the configuration about SpringMVC in the Web.xml configuration file
<!--configure the setting of springmvcDispatcherServlet and configure the mapping--> <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> --> </servlet> <servlet-mapping> <servlet-name>springmvc</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping>
3. Add springmvc-servlet.xml configuration file under src
<?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:context="http://www.springframework.org/schema/context" xmlns:mvc="http://www.springframework.org/schema/mvc" 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-4.1.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc-4.1.xsd"> <!-- scan the package and the sub package --> <context:component-scan base-package="test.SpringMVC"/> <!-- don't handle the static resource --> <mvc:default-servlet-handler /> <!-- if you use annotation you must configure following setting --> <mvc:annotation-driven /> <!-- configure the InternalResourceViewResolver --> <bean id="internalResourceViewResolver"> <!-- prefix--> <property name="prefix" value="/WEB-INF/jsp/" /> <!-- suffix--> <property name="suffix" value=".jsp" /> </bean></beans>
4. Create a folder named jsp in the WEB-INF folder to store the jsp view. Create a hello.jsp and add "Hello World" to your body.
5. Create package and controller as shown below
6. Write Controller Code
@Controller@RequestMapping("/mvc")public class mvcController { @RequestMapping("/hello") public String hello(){ return "hello"; }}7. Start the server and type http://localhost:8080/project name/mvc/hello
1.Dispatcherservlet
DispatcherServlet is a pre-controller configured in the web.xml file. Intercepting matching requests. The Servlet intercepting matching rules must be defined by itself. The intercepted requests are distributed to the target controller according to the corresponding rules for processing. This is the first step in configuring spring MVC.
2.InternalResourceViewResolver
View Name Resolver
3. The above annotations
@Controller is responsible for registering a bean into the spring context
@RequestMapping annotation specifies which URL requests can be processed for the controller
@Controller
Responsible for registering a bean into the spring context
@RequestMapping
Annotation specifies which URL requests can be processed for the controller
@RequestBody
This annotation is used to read part of the body data of the Request request, use the HttpMessageConverter configured by the system for parsing, and then bind the corresponding data to the object to be returned, and then bind the object data returned by HttpMessageConverter to the parameters of the method in the controller
@ResponseBody
This annotation is used to write the object returned by the Controller method to the body data area of the Response object after converting it to the appropriate HttpMessageConverter to the specified format
@ModelAttribute
Use @ModelAttribute annotation on method definition: Spring MVC Before calling the target processing method, the method that annotates @ModelAttribute on the method level will be called one by one.
Use @ModelAttribute annotation before entering the method parameter: You can obtain the object from the implicit object, bind the request parameters to the object, and then pass the method into the parameter object to add the method into the model.
@RequestParam
Use @RequestParam to pass the request parameters to the request method
@PathVariable
Bind URL placeholder to entry parameter
@ExceptionHandler
Annotated on the method, the method will be executed when an exception occurs
@ControllerAdvice
Make a Controller a global exception handling class. The method annotated with the @ExceptionHandler method in the class can handle all exceptions that occur in Controllers.
//match automatically @RequestMapping("/person") public String toPerson(String name,double age){ System.out.println(name+" "+age); return "hello"; }1. Write a Person entity class
package test.SpringMVC.model;public class Person { public String getName() { return name; } public void setName(String name) { this.name = name; } public int getAge() { return age; } public void setAge(int age) { this.age = age; } private String name; private int age; }2. Write methods in Controller
//boxing automatically @RequestMapping("/person1") public String toPerson(Person p){ System.out.println(p.getName()+" "+p.getAge()); return "hello"; } //the parameter was converted in initBinder @RequestMapping("/date") public String date(Date date){ System.out.println(date); return "hello"; } //At the time of initialization,convert the type "String" to type "date" @InitBinder public void initBinder(ServletRequestDataBinder binder){ binder.registerCustomEditor(Date.class, new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true)); } //pass the parameters to front-end @RequestMapping("/show") public String showPerson(Map<String,Object> map){ Person p =new Person(); map.put("p", p); p.setAge(20); p.setName("jayjay"); return "show"; }The front desk can get "p" in the Request domain
//pass the parameters to front-end using ajax @RequestMapping("/getPerson") public void getPerson(String name,PrintWriter pw){ pw.write("hello,"+name); } @RequestMapping("/name") public String saysHello(){ return "name"; }The front desk calls it with the following Jquery code
$(function(){ $("#btn").click(function(){ $.post("mvc/getPerson",{name:$("#name").val()},function(data){ alert(data); }); }); }); //redirect @RequestMapping("/redirect") public String redirect(){ return "redirect:hello"; }1. Two jar packages need to be imported
2. Add in SpringMVC configuration file
<!-- upload settings --> <bean id="multipartResolver"> <property name="maxUploadSize" value="102400000"></property> </bean>
3. Method code
@RequestMapping(value="/upload",method=RequestMethod.POST) public String upload(HttpServletRequest req) throws Exception{ MultipartHttpServletRequest mreq = (MultipartHttpServletRequest)req; MultipartFile file = mreq.getFile("file"); String fileName = file.getOriginalFilename(); SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddHHmmss"); FileOutputStream fos = new FileOutputStream(req.getSession().getServletContext().getRealPath("/")+ "upload/"+sdf.format(new Date())+fileName.substring(fileName.lastIndexOf('.'))); fos.write(file.getBytes()); fos.flush(); fos.close(); return "hello"; }4. Front desk form
<form action="mvc/upload" method="post" enctype="multipart/form-data"> <input type="file" name="file"><br> <input type="submit" value="submit"> </form>
@Controller@RequestMapping("/test")public class mvcController1 { @RequestMapping(value="/param") public String testRequestParam(@RequestParam(value="id") Integer id, @RequestParam(value="name")String name){ System.out.println(id+" "+name); return "/hello"; } }1.RestController
@Controller@RequestMapping("/rest")public class RestController { @RequestMapping(value="/user/{id}",method=RequestMethod.GET) public String get(@PathVariable("id") Integer id){ System.out.println("get"+id); return "/hello"; } @RequestMapping(value="/user/{id}",method=RequestMethod.POST) public String post(@PathVariable("id") Integer id){ System.out.println("post"+id); return "/hello"; } @RequestMapping(value="/user/{id}",method=RequestMethod.PUT) public String put(@PathVariable("id") Integer id){ System.out.println("put"+id); return "/hello"; } @RequestMapping(value="/user/{id}",method=RequestMethod.DELETE) public String delete(@PathVariable("id") Integer id){ System.out.println("delete"+id); return "/hello"; } }2.Form form sends put and delete requests
Configure in web.xml
<!-- configure the HiddenHttpMethodFilter,convert the post method to put or delete --> <filter> <filter-name>HiddenHttpMethodFilter</filter-name> <filter-class>org.springframework.web.filter.HiddenHttpMethodFilter</filter-class> </filter> <filter-mapping> <filter-name>HiddenHttpMethodFilter</filter-name> <url-pattern>/*</url-pattern> </filter-mapping>
In the foreground, you can use the following code to generate a request
<form action="rest/user/1" method="post"> <input type="hidden" name="_method" value="PUT"> <input type="submit" value="put"> </form> <form action="rest/user/1" method="post"> <input type="submit" value="post"> </form> <form action="rest/user/1" method="post"> <input type="submit" value="get"> </form> <form action="rest/user/1" method="post"> <input type="hidden" name="_method" value="DELETE"> <input type="submit" value="delete"> </form>
1. Import the following jar package
2. Method code
@Controller@RequestMapping("/json")public class jsonController { @ResponseBody @RequestMapping("/user") public User get(){ User u = new User(); u.setId(1); u.setName("jayjay"); u.setBirth(new Date()); return u; }}1. Handle local exceptions (in Controller)
@ExceptionHandler public ModelAndView exceptionHandler(Exception ex){ ModelAndView mv = new ModelAndView("error"); mv.addObject("exception", ex); System.out.println("in testExceptionHandler"); return mv; } @RequestMapping("/error") public String error(){ int i = 5/0; return "hello"; }2. Handle global exceptions (all Controllers)
@ControllerAdvicepublic class testControllerAdvice { @ExceptionHandler public ModelAndView exceptionHandler(Exception ex){ ModelAndView mv = new ModelAndView("error"); mv.addObject("exception", ex); System.out.println("in testControllerAdvice"); return mv; }}3. Another way to deal with global exceptions
Configure in SpringMVC configuration file
<!-- configure SimpleMappingExceptionResolver --> <bean> <property name="exceptionMappings"> <props> <prop key="java.lang.ArithmeticException">error</prop> </props> </property> </bean>
error is an error page
1. Create a MyInterceptor class and implement the HandlerInterceptor interface
public class MyInterceptor implements HandlerInterceptor { @Override public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3) throws Exception { System.out.println("afterCompletion"); } @Override public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3) throws Exception { System.out.println("postHandle"); } @Override public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception { System.out.println("preHandle"); return true; }}2. Configure in SpringMVC configuration file
<!-- interceptor setting --> <mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/mvc/**"/> <bean></bean>gt; </mvc:interceptor> </mvc:interceptors>
3. Interceptor execution order
1. Import the jar package required by Hibernate-validate
(Unselected, do not need to import)
2. Write entity class User and add verification annotations
public class User { public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]"; } private int id; @NotEmpty private String name; @Past @DateTimeFormat(pattern="yyyy-MM-dd") private Date birth;}ps:@Past means that time must be a past value
3. Use SpringMVC's form form in jsp
<form:form action="form/add" method="post" modelAttribute="user"> id:<form:input path="id"/><form:errors path="id"/><br> name:<form:input path="name"/><form:errors path="name"/><br> birth:<form:input path="birth"/><form:errors path="birth"/><form:errors path="birth"/><form:errors path="birth"/><form:errors path="birth"/><input type="submit" value="submit"> </form:form>
ps:path corresponding to name
4. Code in Controller
@Controller@RequestMapping("/form")public class formController { @RequestMapping(value="/add",method=RequestMethod.POST) public String add(@Valid User u,BindingResult br){ if(br.getErrorCount()>0){ return "addUser"; } return "showUser"; } @RequestMapping(value="/add",method=RequestMethod.GET) public String add(Map<String,Object> map){ map.put("user",new User()); return "addUser"; }}ps:
1. Because the modelAttribute attribute is used in jsp, there must be a "user" in the request domain.
2.@Valid means verify parameters according to the annotation marked on the entity
3. Return to the original page to re-express, and the form will also re-express.
5. Customize error message
Add locale.properties in the src directory
NotEmpty.user.name=name can't not be emptyPast.user.birth=birth should be a past valueDateTimeFormat.user.birth=the format of input is wrongtypeMismatch.user.birth=the format of input is wrongtypeMismatch.user.id=the format of input is wrong
Configure in SpringMVC configuration file
<!-- configure the locale resource --> <bean id="messageSource"> <property name="basename" value="locale"></property> </bean>
6. International display
Add locale_zh_CN.properties under src
username=account password=password
Added in locale.properties
username=user namepassword=password
Create a locale.jsp
<body> <fmt:message key="username"></fmt:message> <fmt:message key="password"></fmt:message> </body>
Configure in SpringMVC
<!-- make the jsp page can be visited --> <mvc:view-controller path="/locale" view-name="locale"/>
Let locale.jsp be directly accessed under WEB-INF
Finally, visit locale.jsp, switch the browser language, and the language that can see the account and password has also been switched.
1. Create a test.SpringMVC.integrate package to demonstrate integration and create various types
2.User entity class
public class User { public int getId() { return id; } public void setId(int id) { this.id = id; } public String getName() { return name; } public void setName(String name) { this.name = name; } public Date getBirth() { return birth; } public void setBirth(Date birth) { this.birth = birth; } @Override public String toString() { return "User [id=" + id + ", name=" + name + ", birth=" + birth + "]"; } private int id; @NotEmpty private String name; @Past @DateTimeFormat(pattern="yyyy-MM-dd") private Date birth;}3.UserService class
@Componentpublic class UserService { public UserService(){ System.out.println("UserService Constructor.../n/n/n/n/n/n/n/n/n"); } public void save(){ System.out.println("save"); }}4.UserController
@Controller@RequestMapping("/integrate")public class UserController { @Autowired private UserService userService; @RequestMapping("/user") public String saveUser(@RequestBody @ModelAttribute User u){ System.out.println(u); userService.save(); return "hello"; }}5.Spring configuration file
Create SpringIOC configuration file applicationContext.xml in the src directory
<?xml version="1.0" encoding="UTF-8"?><beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util-4.0.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd " xmlns:util="http://www.springframework.org/schema/util" xmlns:p="http://www.springframework.org/schema/p" xmlns:context="http://www.springframework.org/schema/context" > <context:component-scan base-package="test.SpringMVC.integrate"> <context:exclude-filter type="annotation" expression="org.springframework.steretype.Controller"/> <context:exclude-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan> </beans>
Add configuration in Web.xml
<!-- configure the springIOC --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <context-param> <param-name>contextConfigLocation</param-name> <param-value>classpath:applicationContext.xml</param-value> </context-param>
6. Make some configuration in SpringMVC to prevent SpringMVC and SpringIOC from overlapping management of the same object
<!-- scan the package and the sub package --> <context:component-scan base-package="test.SpringMVC.integrate"> <context:include-filter type="annotation" expression="org.springframework.steretype.Controller"/> <context:include-filter type="annotation" expression="org.springframework.web.bind.annotation.ControllerAdvice"/> </context:component-scan>
1. SpringMvc is developed based on method, and struts2 is developed based on class. springmvc maps the url and the method in the controller. After the mapping is successful, springmvc generates a Handler object, which only includes a method. The method execution ends and the formal parameter data is destroyed. SpringMVC's controller development is similar to web service development.
2. SpringMvc can perform singleton development, and it is recommended to use singleton development. Struts2 receives parameters through the member variables of the class. Singleton cannot be used, only multiple cases can be used.
3. After actual testing, struts2 is slow, because it uses struts tags. If you use struts, it is recommended to use jstl.