配置文件
web.xml配置
1 | <!-- 配置Spring字符编码过滤器 --> |
spring配置
springMVC配置
1 | <!-- 配置SpringMVC --> |
spring-dao配置
1 | <!-- 加载数据库资源文件 --> |
mybatis配置
1 | <!-- 配置全局属性 --> |
mybatis配置
建议使用注解方式:1
2
3
4
5
public interface UserMapper {
"select * from `user` where username=#{name} and status=0") (
public User query(String name);
}
代码
编写Controller代码
1 |
|
常用注解
@Controller
负责注册一个bean 到spring 上下文中
@RequestMapping
注解为控制器指定可以处理哪些 URL 请求
@ResponseBody
返回json
@ModelAttribute
在方法定义上使用@ModelAttribute注解:Spring MVC 在调用目标处理方法前,会先逐个调用在方法级上标注了@ModelAttribute 的方法
在方法的入参前使用 @ModelAttribute 注解:可以从隐含对象中获取隐含的模型数据中获取对象,再将请求参数 –绑定到对象中,再传入入参将方法入参对象添加到模型中
@RequestParam
在处理方法入参处使用 @RequestParam 可以把请求参 数传递给请求方法@RequestParam(value="name",defaultValue="Guest")
//修饰在方法参数里面
@PathVariable
绑定 URL 占位符到入参1
2
3
4
5
6"/path/{language}/{id}") (
public String documentView(Model model,
@PathVariable(value = "language") String language,
@PathVariable(value = "id") Long id
) {
}
@ExceptionHandler
注解到方法上,出现异常时会执行该方法
@ControllerAdvice
使一个Contoller成为全局的异常处理类,类中用@ExceptionHandler方法注解的方法可以处理所有Controller发生的异常
@Configuration
把一个类作为一个IoC容器,它的某个方法头上如果注册了@Bean,就会作为这个Spring容器中的Bean。
@Component
组件
@EnableScheduling
启动定时任务
传递参数
1 | "/show") ( |
Model model这个放在方法里面的参数,然后就可以model.addAttibute(“key”,value);页面可以获取到
Model model, Mapmodel2, ModelMap model3都是同一个对象 request传统方式
1
2
3public String view(HttpServletRequest req,HttpSession session){
}
使用redirect方式处理请求
1 | //redirect |
异常的处理
1 | // 处理访问方法时权限不足问题 (value = UnauthorizedException.class) |
自定义拦截器
创建一个MyInterceptor类,并实现HandlerInterceptor接口1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18建一个MyInterceptor类,并实现HandlerInterceptor接口
public void afterCompletion(HttpServletRequest arg0,
HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
System.out.println("afterCompletion");
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1,
Object arg2, ModelAndView arg3) throws Exception {
System.out.println("postHandle");
}
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, //先執行,
Object arg2) throws Exception {
System.out.println("preHandle");
return true;
}
- 编写拦截器类实现接口HandlerInterceptor,重写方法afterCompletion,postHandler,
preHandler(执行时三种方法的执行步骤为,controller方法前执行preHandler,执行controller方法后执行postHandler、afterCompletion)
- 将拦截器注册到springMVC框架中(springmvc配置文件):
1
2
3
4
5
6
7
8
9
10<mvc:interceptors>
<mvc:interceptor>
<mvc:mapping path="/**"/>
<bean class="com.gao.interceptor.LoginInterceptor"></bean>
</mvc:interceptor>
<mvc:interceptor>
<mvc:mapping path="/news/del"/>
<bean class="com.gao.interceptor.LimitInterceptor"></bean>
</mvc:interceptor>
</mvc:interceptors>
数据效验
1 | <!-- 配置校验器 --> |
实体类1
2
3
4 3,max=10,message="{errors.title}") (min=
private String tTitle;
"{errors.content}") (message=
private String tContent;
controller1
2
3
4
5
6
7
8
9
10
11
12
13"/add",method=RequestMethod.POST) (value=
public String add(@Validated News news,BindingResult br,Model model){
//@validated 是@valid一次封装
if(br.hasErrors()){
List<ObjectError> errors = br.getAllErrors();
model.addAttribute("errors", errors);
//errors.get(0).getDefaultMessage();
FieldError name = br.getFieldError("tTitle");
System.out.println(name.getDefaultMessage());
return "addnews";
}
}
文件上传
1 | <!-- 文件上传的配置 --> |
controller1
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
30
31
32
33
34
35
36
37
38
39
40
41
42"/upload") (value=
public String upload(@RequestParam MultipartFile[] myfile,HttpServletRequest request) throws Exception{
for (MultipartFile multipartFile : myfile) {
if(multipartFile.isEmpty()){
System.out.println("文件未上传");
}else{
String fileName = multipartFile.getOriginalFilename();
String path1 = request.getSession().getServletContext().getRealPath("image")+File.separator;
String path = path1 + new SimpleDateFormat("yyyyMMddHHmmss").format(new Date())+fileName;
System.out.println(path);
File localFile = new File(path);
multipartFile.transferTo(localFile);
}
}
return "";
}
"/download") (
public String download(String fileName, HttpServletRequest request,
HttpServletResponse response) throws Exception{
response.setCharacterEncoding("utf-8");
response.setContentType("multipart/form-data");
response.setHeader("Content-Disposition", "attachment;fileName="
+ fileName);
String path = request.getSession().getServletContext().getRealPath
("image")+File.separator;
InputStream inputStream = new FileInputStream(new File(path
+ fileName));
OutputStream os = response.getOutputStream();
byte[] b = new byte[2048];
int length;
while ((length = inputStream.read(b)) > 0) {
os.write(b, 0, length);
}
// 这里主要关闭。
os.close();
inputStream.close();
return null;
}