SpringMvc——进行注解开发的基本配置

本文详细介绍了Spring MVC的基本配置与实践步骤,包括前端控制器的配置、SpringMVC的配置、Controller中URL的配置及访问地址,并提供实例说明。



入手文章,spring大神请绕行。


零,jar包引入




这个是我的myeclipse项目中的截图,如果使用idea进行开发的话,记得要在libraries中引入servlet-api的jar包,不然debug的时候会报错。



一,配置前端控制器

            

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
         xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
         xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd"
         version="3.1">
 
    <!--配置前端控制器-->
    <servlet>
        <servlet-name>springmvc</servlet-name>
        <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
        <!--contextConfigLocation配置springmvc加载的配置文件(配置处理器映射器,适配器等)
            如果不配置contextConfigLocation,默认加载的是/WEB-INF/servlet名称-servlet.xml(springmvc-servlet.xml)
        -->
        <init-param>
            <param-name>contextConfigLocation</param-name>
            <param-value>classpath:springmvc.xml</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>springmvc</servlet-name>
        <!--
            url-pattern配置方式:
            第一种:*.action:访问以.action结尾的由DispatcherServlet解析
            第二种:/,所有访问的地址都由DispatcherServlet进行解析,
                对于静态文件的解析需要配置不让DispatcherServlet进行解析
                使用此种方法可以实现restful风格的url
            第三种:/*,这种配置不对,使用这种配置,最终需要转发到jsp页面时候,
                    仍然由DispatcherServlet解析jsp,不能根据jsp找到handler,会报错
        -->
        <url-pattern>/</url-pattern>
    </servlet-mapping>
</web-app>

    因为我这里暂时木有用到spring的配置,所以现在只加上springmvc的必须配置。


二,spring MVC的配置


      

<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:mvc="http://www.springframework.org/schema/mvc"
       xmlns:context="http://www.springframework.org/schema/context"
       xmlns:aop="http://www.springframework.org/schema/aop"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="http://www.springframework.org/schema/beans
		http://www.springframework.org/schema/beans/spring-beans-3.2.xsd
		http://www.springframework.org/schema/mvc
		http://www.springframework.org/schema/mvc/spring-mvc-3.2.xsd
		http://www.springframework.org/schema/context
		http://www.springframework.org/schema/context/spring-context-3.2.xsd
		http://www.springframework.org/schema/aop
		http://www.springframework.org/schema/aop/spring-aop-3.2.xsd
		http://www.springframework.org/schema/tx
		http://www.springframework.org/schema/tx/spring-tx-3.2.xsd ">

  	
	<mvc:annotation-driven/>
	<!-- 自动扫描的包 -->
    <context:component-scan base-package="cn.itcast.ssm.controller"/>

    <bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
        <property name="viewClass" value="org.springframework.web.servlet.view.JstlView"/>
        <property name="prefix" value="/WEB-INF/jsp/"/>
        <property name="suffix" value=".jsp"/>
    </bean>
</beans>

         这里,注意前缀跟后缀的配置,在最后返回具体的视图的时候,会去/WEB-INF/jsp/+"你controller里面返回的字符串"+.jsp这里找你的资源,如果前缀或后缀配置错误,就404了(个人猜测,因为刚开始我的前缀配置错了,结果404了)。


三,controller中URL的配置及访问地址


    对于Controller类中要访问的方法,使用RequestMapping进行一个定位,类上的RequestMapping可以进行标识,也可以不进行标识。



        

       对应的浏览器中访问地址:http://localhost:8080/SpringMvcTest/hello/mvc。


 





### SpringMVC 中拦截器注解的使用方法 在SpringMVC中,拦截器可以通过配置文件或注解的方式进行注册。当采用注解形式时,主要通过`@Component`、`@Configuration`以及自定义注解来完成。 对于实现HandlerInterceptor接口或是其适配者HandlerInterceptorAdapter的情况,如果希望利用注解简化Bean的创建过程,则可以在拦截器类上加上`@Component`注解[^2]: ```java @Component public class MyInterceptor extends HandlerInterceptorAdapter { @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { // 实现预处理逻辑... return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { // 实现后置处理逻辑... } } ``` 为了让上述带有`@Component`标记的拦截器生效,还需要确保组件扫描能够找到它所在的包路径,并且将其加入到全局拦截链里。这一步骤可通过编写一个配置类并标注为`@Configuration`,再借助`WebMvcConfigurer`接口提供的扩展点——即重写addInterceptors()方法来达成目的: ```java @Configuration public class WebConfig implements WebMvcConfigurer { @Autowired private MyInterceptor myInterceptor; @Override public void addInterceptors(InterceptorRegistry registry) { registry.addInterceptor(myInterceptor).addPathPatterns("/**"); } } ``` 另外一种更为灵活的做法是创建自己的元数据注解,配合AOP表达式匹配特定条件下的Controller方法,从而达到局部应用的效果。下面的例子展示了如何声明这样一个名为`@LogAccess`的新注解及其对应的切面逻辑[^1]: #### 自定义注解 `@LogAccess` ```java import java.lang.annotation.ElementType; import java.lang.annotation.Retention; import java.lang.annotation.RetentionPolicy; import java.lang.annotation.Target; @Target(ElementType.METHOD) @Retention(RetentionPolicy.RUNTIME) public @interface LogAccess { } ``` #### 切面类 AspectLogging ```java @Aspect @Component public class AspectLogging { @Around("@annotation(LogAccess)") public Object logMethodExecution(ProceedingJoinPoint joinPoint) throws Throwable { long start = System.currentTimeMillis(); try { return joinPoint.proceed(); // 执行目标方法 } finally { long elapsedTime = System.currentTimeMillis() - start; String methodName = joinPoint.getSignature().getName(); // 记录访问日志或其他操作 System.out.println(String.format("Executed %s in %d ms", methodName, elapsedTime)); } } } ``` 以上就是有关于SpringMVC中拦截器注解的一些基本介绍和实践案例。值得注意的是,虽然这里展示的内容侧重于功能层面的应用场景,但在实际项目开发过程中还需考虑诸如性能优化、异常捕获等方面的因素。
评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

CopyProfessor

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值