SpringMVC

SpringMVC

常用注解:
容器部件:
@controller 控制器声明,控制器带mapping,与其他三个不同,其他三个接近

@service 逻辑层声明
@repository dao层声明
@component 不好分类的类加入容器,创建类对象,相当于配置bean

@Configuration 初始设置声明,加载spring容器时,容器初始化
@bean 声明在方法,(其他都是声明在类)将方法返回值加入到容器,与@Configuration 组合使用,可以在容器部件创建时生成
@Configuration
public class AppConfig {

@Bean
public TransferService transferService() {
    return new TransferServiceImpl();
}

}
等效于

测试:
@Configuration
public class cnf {
@Bean
public Type tran() {
return new Type(2,“2342”);
}
}
<context:component-scan base-package=“model”></context:component-scan>

@Qualifier(value=“id标识”) Value属性可以按照id唯一标识注入
@ComponentScan
@scope 部件 有效范围
@lazy(true) 延时加载
@PostConstruct 初始化的方法,在创建之前先执行
@PostConstruct
public void init() {
System.out.println(111);
}
@ PreDestroy 销毁的方法

请求类:
https://www.cnblogs.com/janeaiai/p/5667344.html
mapping:
@requestmapping
@RequestMapping

value: 指定请求的实际地址
method: 指定请求的method类型 RequestMethod.GET,只有get请求能进入
consumes: 指定处理请求的提交内容类型(Content-Type ,
例如application/json, text/html;//限制必须进来的类型
produces: 指定返回的内容类型
params: 指定request中必须包含某些参数值是,才让该方法处理,比如params=“id=1”,必须id=1,才能进来
params=“id=1” param=“id” param={“id”,“name”}
headers: 请求头部数据 headers=“Referer=http://www.ifeng.com/”,用来设置从哪个网站转发过来的进入哪个方法,类似于一种过滤
这些意味着不同请求可以用相同的地址,用约束来限制进哪一个,但是要注意,带约束的方法要放在上面,不然就会只进去没带约束的

其他请求的发送:

//必须为post //标准,不同的服务器不同,tomcat是_method 加上过滤器,在web.xml HiddenHttpMethodFilter org.springframework.web.filter.HiddenHttpMethodFilter HiddenHttpMethodFilter /* 使用 @DeleteMapping("sss") public void aaa() { System.out.println("ddddd"); }

@getmapping
@postmaping
@deletemaping
@putmapping

@PathVariable 从路径中获取参数

RESTFUL web设计模式
例子: /delete/2/a.jsp 将请求数据变成了地址
网址/Book/1 GET请求 获取
网址/Book/1 PUT请求 修改
网址/Book POST请求 新增
网址/Book/1 DELETE请求 删除
@GetMapping(“sss/{myid}”)
public void aaa(@PathVariable(“myid”) int id) {
System.out.println(id);
}
总结:
在@RequestMapping注解中定义URL变量规则
在@RequestMapping注解方法中获取URL变量-@PathVariable
@PathVariable指定URL变量名
定义多个URL变量
用正则表达式精确定义URL变量

@requestParam 请求参数的值放入方法参数
public void aaa(@RequestParam(“id”) int d) 请求转方法参数(参数名称不一致)
defaultvalue 设置默认值
required=true 设置为必有项

@ModelAttribute modelmap的值的处理
1.方法前使用,每次请求前执行方法,像初始化请求,无论调用同级的哪个请求,他都会执行(如果有返回值,他的返回值会自动到modelmap中)
@ModelAttribute(“all”) 返回值加入model
public int aaass() {
System.out.println(“ddddd”);
return 300;
}
@GetMapping(“sss”)
public void aaa( int id,ModelMap m) {
System.out.println(m.get(“all”));
}
2. 注释方法的参数时,从modelmap中取值塞到变量里面
public void aaa(@ModelAttribute(“all”) int id,ModelMap m) syso id 输出值和all值相等
@sessionAttribute
1.注释一个类(指定名称的map值的添加,自动添加一份到session)
@SessionAttributes(“user”)
public class BookController {
@GetMapping(“sss”)
public void aaa(ModelMap s) {
s.addAttribute(“user”, “aaaa11a”);
}
2.注释一个方法的参数(从sessionl取值到方法参数)
public void aaa(@SessionAttribute(“user”) String id,ModelMap m)

@ExceptionHandler 当控制器内出现异常时自动执行
@ExceptionHandler
public void ex(Exception e) {
e.printStackTrace();
}

@ResponseBody将返回值作为回应的内容,为ajax接口使用,也可以写在方法上面;;
@restContrller==@@ResponseBody+@controller
public @ResponseBody String aaa() {
return “json”; //object 将自动转为json
}
@RequestBody 将请求内的内容转化为参数,数组,集合,复杂对象
//要求对方发过来是以json串发过来的
发送方:(最好ajax)
function testajax(){
$.ajax({
headers: {
‘Content-Type’: ‘application/json’//必须json
},
type: “post”,
url: “Book/sss.action”,
data: JSON.stringify([{name:“a1”},{name:“a2”}]),//json字符串
success: function (data) {
},
error: function (data) {
}
});
}
接收方:
@RequestMapping(“sss”)
public void aaa(@RequestBody List ts ) {
System.out.println(ts.size());
for(Type t:ts) System.out.println(t.getName());
}
@ControllerAdvice控制器额外通知,拦截所有控制器,不是service层的
做全局处理异常的
@ControllerAdvice //全局异常处理
public class allExceptionRunner {
@ExceptionHandler
public ModelAndView allException(Exception e){
//根据异常类型,转移到不同错误页
if(e instanceof NullPointerException) {
}
}
}
spring拦截器
拦截器类
public class myInterceptor implements HandlerInterceptor{
public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
throws Exception {
//完成之后
System.out.println(“完成之后”);
}
public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
throws Exception {
//过程
System.out.println(“过程”);
}
public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
//之前
System.out.println(“之前”);
return false; //false拦截取消请求 true可以进入方法
}
配置 写在扫描后面
mvc:interceptors
mvc:interceptor
<mvc:mapping path="/Book/*"/>

</mvc:interceptor>
</mvc:interceptors>
几种拦截区别
filter(请求)->interceptor(请求,控制器对象)->aop(请求,控制器对象,调用方法)

文件上传:
form:

//上传类型 //name与后台对应 pom.xml commons-fileupload commons-fileupload 1.4 applicationcontext.xml: 控制器方法: @RequestMapping("sss") public void aaa(@RequestParam("file") CommonsMultipartFile file ) file.transferTo(new File("目标位置")); 实例1: @RequestMapping("sss") public void aaa(@RequestParam("file") CommonsMultipartFile file,HttpServletRequest req )throws Exception { String oname=file.getOriginalFilename(); String ex=oname.substring(oname.lastIndexOf("."),oname.length()); String nname = UUID.randomUUID()+ex;

String path=req.getSession().getServletContext().getRealPath("/");
path=new File(path).getParentFile().getPath()+"/upload";
System.out.println(path);
file.transferTo(new File(path,nname));
}

测试

实例2:ajax文件上传(********)
注意:要想图片显示,需要更改tomcat的发布路径
@RequestMapping(“sss”)
public @ResponseBody String aaa(@RequestParam(“file”) CommonsMultipartFile file,HttpServletRequest req )throws Exception {
String oname=file.getOriginalFilename();
String ex=oname.substring(oname.lastIndexOf("."),oname.length());
String nname = UUID.randomUUID()+ex;

String path=req.getSession().getServletContext().getRealPath("/");
path=new File(path).getParentFile().getPath()+"/upload";
System.out.println(path);
file.transferTo(new File(path,nname));
return "/upload/"+nname;

}

function openfile(){
KaTeX parse error: Expected 'EOF', got '}' at position 29: …")[0].click(); }̲ function uploa…("[name=file]")[0].files[0]);
$.ajax({
url:‘Book/sss.action’,
type:‘post’,
data: formData,
contentType: false,
processData: false,
success:function(res){
$(".upimg").attr(“src”,res);
}
});
}

测试 上传

控制器方法:
方法参数:
用户参数:
简单类型: 基础类型,简单对象(get,set)
复杂类型:嵌套型对象,对象集合,map集合(使用要求:前台必须设置:enctype=‘application/json’;;请求参数数据为json字符串)
文件上传:public void aaa(@RequestParam(“file”) CommonsMultipartFile file )
服务器变量参数:
@modelattribute request值赋值参数
@sessionattribute session值赋值参数 @SessionAttribute(“user”) String id
系统参数:
model
modelmap,request值栈,在el中使用,进行页面渲染,与model相同
m.addAttribute,一旦重复报异常
m.put 重复不报异常
httpservletrequest 获取地址常用
httpservletresponse
httpsession

方法返回值:
视图名称返回
1.返回string,指定视图名称
2.无返回,返回mapping路径,作为视图名称
json返回,html返回:
必须使用@ResponseBody或者@restcontroller;;将返回对象转换为字符串,直接写入回应数据里面
视图返回:
@RequestMapping(“aaa”)
public ModelAndView dsd() {
ModelAndView view=new ModelAndView();
view.addObject(“name”, “而韩11国”);
view.setViewName(“Book/sss”);
// view.setView(new JstlView(url));
return view;
}

spring标签库:在jsp页面,用taglib导入,但是一般不用
1.表单显示处理 :form
2.数据处理:bind
编码乱码:(数据库,网络,文件页面,java编码)

终极解决:name= new String(name.getBytes(“ISO8859-1”),“UTF-8”);在controller层添加这句话,把jsp前端传过来的字符串改变编码
文件编码 :记事本
*ide文件编码, 项目右键–属性
***java编译编码, jsp页面最上面的那个
***web页面编码
请求编码 request对象&get请求地址
response编码 setcontentType方法
数据库链接类型编码 ?characterEncoding=utf-8&autoReconnect=true
*****数据库引擎编码 my.ini设置,或者创建库表选择

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值