springMVC注解式开发要点

1.导入SpringMVC注解所需的jar包

2.在springMVC主配置中不需要添加<bean id=" " class=" "/>创建handler管理器对象 (因为是注解式开发,所以需要添加注解扫描器,在bean约束下没有此元素,还有引入context 约束)如下所示

<?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" 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.xsd">
<context:component-scan base-package="com.abc.handler"/>    注解扫描器器 扫描含有handler管理器所在的包

</bean>

3.在创建的handler类中 ,不需要继承controller类,但是要在类名之前添加@Controller,如果添加不成功,查看Controller导入的包是否正确

4.在handler类的方法名之前,添加@RequestMapping(“/some.do”)请求映射的哪个方法,并给该方法重新定义了一个新的名称。供浏览器访问。
@Controller
public class SomeHandler {
 @RequestMapping({"/some.do"})
 public ModelAndView handleRequest(HttpServletRequest request, HttpServletResponse response) throws Exception {
  ModelAndView mv = new ModelAndView();
  mv.addObject("message", "Hello SpringMVC!");
  //mv.setViewName("/WEB-INF/jsp/welcome.jsp");
  mv.setViewName("welcome");
  return mv; 
 }

5.创建的管理器handler也可以自定义参数类型,表单中提交到该对象中的属性也可以在jsp中访问得到

6.防止中文乱码的出现,有post方法也有get方法,这里统一在web.xml中配置过滤器

<filter>
  <filter-name>CharacterEncodingFilter</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>
  <init-param>
   <param-name>forceEncoding</param-name>
   <param-value>true</param-value>
  </init-param>
 </filter>
 <filter-mapping>
  <filter-name>CharacterEncodingFilter</filter-name>
  <url-pattern>/*</url-pattern>
 </filter-mapping>

7.在表单提交时,action="${pageContext.request.contextPath}/some.do"   //自动获取项目路径下的哪个映射地址

原文地址:https://www.cnblogs.com/liuna369-4369/p/10006245.html