之前复制粘贴创建了几个ssm的项目,然而回头让自己写的时候还是一头雾水,究其原因是spring的陌生。仅仅是写过几个helloworld而已。而且是照着写。我都不知道springmvc到底需要多少jar,都用来干嘛。所以,接下来要用心看spring原理了。
最近由于有定时任务的需求,简单搭建了一个springmvc4的helloworld。
ide采用的是idea,当然eclipse应该也是没问题的,因为都是maven项目。
1.创建好maven结构。
可以通过new->project->maven来创建。创建完后补充成正常的javaweb结构。即src\main\java,src\main\resource,src\main\webapp.
2.jar包--pom
关于jar包有多少,干啥用,还不清楚。这里是我在网上找的一个版本,很少jar,以后需要的时候逐渐增加就行了。
3.web.xml
设置拦截器和过滤器
4.spring容器配置文件spring/spring-contex.xml
5.dispatcherServlet配置文件spring/spring-mvc.xml
6.helloController测试
7.视图:/web-inf/views/index.jsp
1
2
3
4
5
6
|
<html> <body> <h2>Hello World!</h2> hello ${username} </body> </html> |
8.定时任务task
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
|
package com.test.task;
import org.springframework.context.annotation.Lazy;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
/** * Created by Administrator on 2016/4/14 0014.
*/
@Service @Lazy ( false )
public class MyTask implements ITask {
private static int i = 0 ;
private static int y = 0 ;
@Scheduled (cron= "0/5 * * * * ?" ) //每5秒执行一次
public void testCyc() {
System.out.println( "task test,执行次数:" +i++);
}
/**
* 心跳更新。启动时执行一次,之后每隔2秒执行一次
*/
@Scheduled (fixedRate = 1000 * 2 )
public void print(){
System.out.println( "心跳执行次数:" +y++);
}
} |
9.测试代码:github