SpringMVC常用注解
1.@Controller
注解到类名上,表示该类是控制器。
2.@RequestMapping("/xxxx")
可以放在类名/方法名之上,表示访问请求该方法时的url。如果该方法类名有@RequestMapping,则访问该方法的url=项目名+类的RequestMapping+方法的RequestMapping。
3.@Resource
作用相当于@Autowired,只不过@Autowired按类型自动注入,而@Resource默认按byName注入。
@Resource有两个属性是比较重要的,分是name和type,Spring将@Resource注解的name属性解析为bean的名字,而type属性则解析为bean的类型。
所以如果使用name属性,则使用byName的自动注入策略,而使用type属性时则使用byType自动注入策略。
如果既不指定name也不指定type属性,这时将通过反射机制使用byName自动注入策略。
举例:如果Spring上下文中存在不止一个UserDao的bean时,就会抛出BeanCreationException异常;
如果Spring上下文中不存在UserDao类型的bean,也会抛出BeanCreationException异常。
我们可以使用@Qualifier配合@Autowired来解决。
①存在多个bean时,这样解决。
@Autowired
@Qualifier("userServiceImpl")
public IUserService userService;
②不存在时这样解决。
@Autowired(required = false)
public IUserService userService
4.@Service
@Service("Bean的名称") 其中双引号内为可选操作,可以不填,填了代表自定义业务名。整体含义为定义业务层bean。
@Service用在实现类的类名上。如
@Service("alarmManageService")
public class AlarmServiceImp implements AlarmManageService{}
5.@Repository
@Repository("Bean的名称")
定义DAO层Bean
6.@Component
定义Bean, 不好归类时使用。即除了常用的归类外,此Bean不属于其中任何一个,即可用Component修饰。
7.@InitBinder
用于绑定数据,比如前端页面有两个对象,一个student,一个course,切他俩的属性名都一样,此时即可使用该注解。
@Controller @RequestMapping("/classtest") public class TestController { @InitBinder("student") public void initBinderUser(WebDataBinder binder) { binder.setFieldDefaultPrefix("student."); } @InitBinder("course") public void initBinderAddr(WebDataBinder binder) { binder.setFieldDefaultPrefix("course."); } @RequestMapping("/methodtest") @ResponseBody public Map<String, Object> test(@ModelAttribute("student") Student student, @ModelAttribute("course") Course course) { Map<String, Object> map = new HashMap<String, Object>(); map.put("student", student); map.put("course", course); return map; } }
8.前端小知识:
jquery使用ajax时,可以设置同步或异步执行 async: true为异步 async: false是同步。
9.加入aop,可以用作日志相关。
(1).pom.xml引包
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-aop</artifactId>
<version>${spring.version}</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjrt</artifactId>
<version>1.9.2</version>
</dependency>
<dependency>
<groupId>org.aspectj</groupId>
<artifactId>aspectjweaver</artifactId>
<version>1.9.3</version>
</dependency>
(2).springmvc.xml配置
<!--配置cglib代理 -->
<aop:aspectj-autoproxy proxy-target-class="true" />
(3).创建自定义注解
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ ElementType.PARAMETER, ElementType.METHOD })
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface SystemLog {
String method() default "";// 方法名
String flag() default "";// 预留标识
String describe() default "";// 操作描述
String type() default "";// 操作类型(如设备,证书,用户)
}
其中SystemLog内的方法是用作注解内的参数,如flag,type可让切面内容更加丰富。
(4).在需要进行切面的函数上添加如下注解
@SystemLog(method = <方法名>, flag = <自定义标识符>, describe = <自定义描述>, type = <自定义类型>)
(5).配置切面函数。首先创建一个类,例如 test ,然后创建一个函数,如qiemian。在qiemian函数进行如下配置。
@Pointcut("@annotation(<SystemLog自定义注解类全路径,如com.test.SystemLog>)")
public void test() {
}
(6).添加后置或前置或环绕等切面通知,例如:
@AfterReturning(value = "test()", returning = "result")
public Object doAfterReturning(JoinPoint joinPoint, Object result) {
}
注意,returning = "result"的result一定要和Object result这个参数的参数名一致。
如果需要获取request,可用如下方法:
HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
10.HTTPHeader
11.突然报错
Description Resource Path Location Type
Cannot change version of project facet Dynamic Web Module to 2.5. JBFEducation line 1 Maven Java EE Configuration Problem
解决方式:打开当前项目目录,进入.setting文件夹,修改org.eclipse.wst.common.project.facet.core.xml 中的为 <installed facet="jst.web" version="2.5"/> 即可。
12.常见http错误码
302 redirect: 302 代表暂时性转移(Temporarily Moved )。
意思就是访问网址A,但是网址A因为服务器端的拦截器或者其他后端代码处理的原因,会被重定向到网址B。
13.事务:
可以在需要事务的public(其他三种的访问权限不行)方法上添加@Transational。或者在类上添加@Transational表明整个类都开启事务。
工作中常用的是利用AOP设置全局事务,可在applaction中加入如下代码:
<!-- 事务处理 --> <bean id= "transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager"> <property name="dataSource" ref="dataSource"/> </bean> <!-- 事务注解:开启注解支持--> <tx:annotation-driven transaction-manager="transactionManager" proxy-target-class="true"/> <!-- 全局AOP事物,除get,list,select,query开头的方法外,都处在事物当中 --> <tx:advice id="txAdvice" transaction-manager="transactionManager"> <tx:attributes> <tx:method name="select*" propagation="REQUIRED" read-only="true" /> <tx:method name="get*" propagation="REQUIRED" read-only="true" /> <tx:method name="list*" propagation="REQUIRED" read-only="true" /> <tx:method name="query*" propagation="REQUIRED" read-only="true" /> <tx:method name="*" propagation="REQUIRED" read-only="false" rollback-for="java.lang.Exception"/> </tx:attributes> </tx:advice> <!-- 配置事务切面 到Service层 --> <aop:config expose-proxy="true" proxy-target-class="true" > <aop:advisor advice-ref="txAdvice" pointcut="execution(* com.chx.shop.service..*.*(..))"/> </aop:config>