标签:return SpringMVC 笔记 class 学习 bean user public
SpringMVC学习笔记
-
SpringMVC 技术与Servlet技术功能等同,均属于web层开发技术
-
SpringMVC是一种基于Java实现MVC模型的轻量级web框架
-
优点:使用简单,开发便捷(相比于Servlet),灵活性强
//Servlet
@WebServlet("/user/save")
public class UserSaveServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req,HttpservIeLkespunse resp) throws ServletException,IOException {
string name = req.getParameter( "name" ) ;
system.out.println( "servlet save name ==> " + name);
resp.setContentType( "text/json;charset=utf-8");
Printwriter pw = resp.getwriter();
pw.write( "{ ' module ' : ' servlet save' }");
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException,IOException {
this.doGet(req,resp);
}
}
//SpringMVC
@Controller
public class UserController{
@RequestMapping( "/save")@ResponseBody
public String save( String name){
system.out.println( "springmvc save name ==> “ + name );
return "{'module':'springmvc save'}";
}
}
一、SpringMVC简介
- SpringMVC入门案例
- 先导入SpringMVC坐标与Servlet坐标
<dependency>
<groupId>javax.servlet</ groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.2.10.RELEASE</version>
</dependency>
- 创建SpringMVC控制器类
@Controller
pubilc class UserController {
@RequetMap("/save")
@RequestBody
public String save(){
System.out.println("user save ...");
return "{'info':'Springmvc'}";
}
}
- 初始化SpringMVC环境(同Spring环境),设定SpringMVC加载对应的bean
@Configuration
@Componentscan("com.shine.controller")
public class SpringMvcConfig {}
- 初始化Servlet容器,加载SpringMVC环境,并设置SpringMVC技术处理的请求
public class ServletContainersInitConfig extends AbstractDispatcherServletInitializer {
protected webApplicationContext createServletApplicationContext() {
AnnotationConfigwebApplicationContext ctx = new AnnotationConfigwebApplicationContext();
ctx.register(SpringMvcConfig.class);
return ctx;
}
protected String[] getServletMappings() {
return new String[]{"/"};
}
protected WebApplicationContext createRootApplicationContext() {
return null;
}
}
- Controller加载控制与业务bean加载控制
-
SpringMVC相关bean(表现层bean)
-
Spring控制的bean
- 业务bean (Service)
- 功能bean (DataSource等)
-
因为功能不同,如何避免Spring错误的加载到SpringMVC的bean——加载spring控制的bean的时候排除掉springMVC控制的bean
-
SpringMVC相关bean加载控制
- SpringMNC加载的bean对应的包均在com.shine.controller包内
-
Spring相关bean加载控制
-
方式一:Spring加载的bean设定扫描范围为com.shine,排除掉controller包内的bean
-
方式二:Spring加载的bean设定扫描范围为精准范围,例如service包、dao包
-
方式三:不区分spring与SpringMVC的环境,加载到同一个环境中
//方式一 @Configuration @ComponentScan({"com.shine.service","com.shine.dao"}) public class SpringConfig { } //方式二 @componentscan(value="com.shine", excludeFilters = @ComponentScan.Filter( type = FilterType.ANNOTATION, classes = Controller.class )
-
-
简化开发
public class ServletContainersInitConfig extends AbstractAnnotationConfigDispatcherServletInitializer{ protected class<?>[] getServletConfigclasses () { return new Class[]{SpringMvcConfig.class}; } protected String[] getServletMappings() { return new String[]{"/"}; } protected class<?>[] getRootConfigclasses() { return new Class[]{SpringConfig.class}; } }
二、请求与响应
(一)请求
- 请求映射路径
-
名称:@RequestMapping
-
类型:方法注解 类注解
-
位置: SpringMVC控制器方法定义上方
-
作用:设置当前控制器方法请求访问路径,如果设置在类上统一设置当前控制器方法请求访问路径前缀
-
范例:
@Controller @RequestMapping("/user") public class UserController { RequestMapping ("/save" ) @ResponseBody public String save(){ system.out.println( "user save ... " ); return "{'module':'user save'}"; }
- 请求参数
-
Get请求
-
Post请求
-
SpringMVC解决Post请求中文乱码问题
//SevletContainersInitConfig类 @Override protected Filter[] getServletFilters() { CharacterEncodingFilter filter = new CharacterEncodingFilter(); filter.setEncoding("UTF-8"); return new Filter[]{filter}; } //注意:以上是针对POST请求
-
五种类型参数传递
- 普通参数:url地址传参,地址参数名与形参变量名相同,定义形参即可接收参数
- POJO(实体类)参数:请求参数名与形参对象属性名相同,定义POJO类型形参即可接收参数
- 嵌套POJO参数:请求参数名与形参对象属性名相同,按照对象层次结构关系即可接收嵌套POJO属性参数
- 数组参数:请求参数名与形参对象属性名相同且请求参数为多个,定义数组类型形参即可接收参数
- 集合保存普通参数:请求参数名与形参集合对象名相同且请求参数为多个,@RequestParam绑定参数关系
- json数据传递参数
-
step1:添加json数据转换相关坐标
<dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.13.3</version> </dependency>
-
step2:设置发送json数据(请求body中添加json数据)
-
step3:开启自动转换json数据的支持
@Configuration @ComponentScan("com.shine.controller") @EnableWebMvc public class SpringMvcConfig { }
注:@EnablelwebNvc注解功能强大,该注解整合了多个功能,此处仅使用其中一部分功能,即json数据进行自动类型转换
-
step4:设置接收json数据
@RequestMapping( "/listParamForson") @ResponseBody public String listParamForJson(@RequestBody List<string> likes){ system.out.println("list common(json)参数传递list ==> "+likes); return "{'module':'list common for json param'}"; }
-
@RequestBody和@RequestParam区别
- @RequestParam用于接收url地址传参,表单传参【application/x-www-form-urlencoded】
- @RequestBody用于接收json数据【application/json】
-
日期类型参数传递
-
日期类型数据基于系统不同格式也不尽相同
- 2088-08-18
- 2088/08/18
- 08/18/2088
-
接收形参时,根据不同的日期格式设置不同的接收方式
@RequestMapping( "/dataParam") @ResponseBody public String dataParam(Date date, @DateTimeFormat(pattern = "yyyy-MM-dd" ) Date date1, @DateTimeFormat(pattern = "yyyy/MM/dd HH: mm: ss" )Date date2){ System.out.print1n("参数传递date ==> "+date); system.out.println("参数传递date(yyyy-MM-dd) ==> "+date1); system.out.println("参数传递date(yyyy/MM/dd HH:mm:ss) ==> "+date2); return "{'module':'data param'}";
http://localhost/dataParam?date=2088/08/08&date1=2088-08-18&date2=2088/08/28 8:08:08
(二)响应
- @ResponseBody
- 位置:SpringMVC控制器方法定义上方置当前控制器返回值作为响应体
- 作用:设置当前控制器返回值作为响应体
- HttpMessageConverter接口
public interface HttpMessageConverter<T> {
boolean canRead(class<?> clazz,@Nullable MediaType mediaType);
boolean canwrite(Class<?> clazz,@Nullable MediaType mediaType);
List<MediaType> getSupportedMediaTypes();
T read(class<? extends T> clazz,HttpInputMessage inputMessage)
throws IOException,HttpMessageNotReadableException;
void write(T t,@Nullable MediaType contentType,HttpOutputMessage outputMessage) throws IOException,HttpMessageNotwritableException;
}
三、REST风格
- REST风格简介
-
REST(Representation State Transfer),表现形式状态转换
-
优点:
- 隐藏资源的访问行为,无法通过地址得知对资源是何种操作
- 书写简化
-
按照REST风格访问资源时使用行为动作区分对资源进行了何种操作
- http: / / localhost/users 查询全部用户信息 GET(查询)
- http:/ /localhost/users/1 查询指定用户信息 GET(查询)
- http: / / localhost/users 添加用户信息 POST(新增保存)
- http: / /localhost/users 修改用户信息 PUT(修改/更新)
- http:/ /localhost/users/1删除用户信息 DELETE (删除)
注:上述行为是约定方式,约定不是规范,可以打破,所以称REST风格,而不是REST规范
描述模块的名称通常使用复数,也就是加s的格式描述,表示此类资源,而非单个资源,例如: users、books、account.... -
根据REST风格对资源进行访问称为RESTful
- 案例
-
设定http请求动作(动词)
@RequestMapping(value = "/users", method = RequestMethod.POST) @ResponseBody public String save(@RequestBody User user){ system.out.println( "user save.. ." + user); return "{'module':'user save'}"; } @RequestMapping(value = "/users" ,method = RequestMethod.PUT) @ResponseBody public string update(@RequestBody User user){ system.out.println( "user update..."+user); return " 'module':'user update'}" ;
-
设定请求参数(路径变量)
@RequestMapping(value = "/users/{id}",method=RequestMethod.DELETE) @ResponseBody public string delete(@PathVariable Integer id){ system.out.println("user delete..." +id); return "{'module':'user delete'}" ; }
- @RequestBody @RequestParam @PathVariable
- 区别
- @RequestParam用于接收url地址传参或表单传参
- @RequestBody用于接收json数据
- @PathVariable用于接收路径参数,使用{参数名称}描述路径参数
- 应用
- 后期开发中,发送请求参数超过1个时,以json格式为主,@RequestBody应用较广
- 如果发送非json格式数据,选用@RequestParam接收请求参数
- 采用RESTful进行开发,当参数数量较少时,例如1个,可以采用@PathVariable接收请求路径变量,通常用于传递id值
- 设置对静态资源发访问放行
@Configuration
public class SpringMvcSupport extends webMvcConfigurationSupport {
@Override
protected void addResourceHandlers(ResourceHandlerRegistry registry) {
//当访问/pages/????时候,走/pages目录下的内容
registry.addResourceHandler("/pages/**").addResourceLocations("/pages/");
registry.addResourceHandler("/js/**").addResourceLocations("/js/");
registry.addResourceHandler("/css/**").addResourceLocations( "/css/");
registry.addResourceHandler("/plugins/**").addResourceLocations("/plugins/");
}
}
四、SSM整合
- 异常处理器
- 集中的、统一的处理项目中出现的异常
@RestControllerAdvice
public class ProjectExceptionAdvice {
ExceptionHandler(Exception.class)
public Result doException(Exception ex){
return new Result(666,null);
}
}
- 项目异常分类
- 业务异常(BusinessException)
- 规范的用户行为产生的异常
- 不规范的用户行为操作产生的异常
- 系统异常(SystemException)
- 项目运行过程中可预计且无法避免的异常
- 其他异常(Exception)
- 编程人员未预期到的异常
- 业务异常(BusinessException)
- 项目异常处理方案
- 业务异常(BusinessException)
- 发送对应消息传递给用户,提醒规范操作
- 系统异常(SystemException)
- 发送固定消息传递给用户,安抚用户
- 发送特定消息给运维人员,提醒维护
- 记录日志
- 其他异常(Exception)
- 发送固定消息传递给用户,安抚用户
- 发送特定消息给编程人员,提醒维护(纳入预期范围内)
- 记录日志
- 业务异常(BusinessException)
五、拦截器
- 拦截器概念
- 拦截器( Interceptor)是一种动态拦截方法调用的机制
- 作用︰
- 在指定的方法调用前后执行预先设定后的的代码阻止原始方法的执行
- 拦截器与过滤器区别
- 归属不同:Filter属于Servlet技术,Interceptor属于SpringMVC技术
- 拦截内容不同:Filter对所有访问进行增强,Interceptor仅针对SpringMVC的访问进行增强
- 案例
-
声明拦截器的bean,并实现HandlerInterceptor接口(注意:扫描加载bean)
@Component public class ProjectInterceptor implements HandlerInterceptor { public boolean preHandle( ..) throws Exception { System.out.println( "preHandle. . . " ); return true; } public void postHandle( ..) throws Exception { system.out.println( "postHandle. . ." ); } public void afterCompletion( ..) throws Exception { system.out.println( "afterCompletion. . ." ); }
-
定义配置类,继承WebMvcConfigurationSupport,实现addInterceptor方法(注意:扫描加载配置)
@Configuration public class SpringMvcSsupport extends webMvcConfigurationSupport { @Override public void addInterceptors(InterceptorRegistry registry) { ... } }
-
添加拦截器并设定拦截的访问路径,路径可以通过可变参数设置多个
@Configuration public class SpringMvcSupport extends webMvcConfigurationSupport { @Autowired private ProjectInterceptor projectInterceptor; @Override public void addInterceptors (InterceptorRegistry registry){ registry.addInterceptor(projectInterceptor).addPathPatterns("/books"); } }
-
执行流程
标签:return,SpringMVC,笔记,class,学习,bean,user,public 来源: https://www.cnblogs.com/Shine-Gan/p/16389083.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。