创建一个基本的springmvc工程
idea创建一个maven webapp项目
(java和resources目录没有的加上)
1.web.xml文件配置
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app>
<display-name>Archetype Created Web Application</display-name>
<!-- 设置servlet的处理类-->
<servlet>
<servlet-name>dispatcherServlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<!-- 关联springmvc的配置文件-->
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc.xml</param-value>
</init-param>
<!-- 服务启动时加载-->
<load-on-startup>1</load-on-startup>
</servlet>
<!-- 拦截url-pattern 并用处理类处理 !注:如果前后端未分离(js css等文件也在tomcat下跑),获取js这些h5资源也会被拦截到 所以需要到springmvc.xml文件过滤这些静态资源-->
<servlet-mapping>
<servlet-name>dispatcherServlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
2.spring的配置文件
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd">
<!-- 扫描注解-->
<context:component-scan base-package="com.mobao"></context:component-scan>
<!-- 自定义类型转换器配置-->
<bean id="converdate" class="org.springframework.context.support.ConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.mobao.utils.StringToDate"></bean>
</set>
</property>
</bean>
<!-- 生效自定义类型转换器 conversion-service="converdate"-->
<mvc:annotation-driven conversion-service="converdate">
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<!-- 解决数据返回中文??问题-->
<property name="supportedMediaTypes" value="text/html;charset=UTF-8" />
</bean>
</mvc:message-converters>
</mvc:annotation-driven>
<!--由于在web.xml配置了拦截 "/" 所有请求,所以要在这过滤掉静态资源部分的请求-->
<!-- mapping 过滤的表达式 location 作用的目录-->
<mvc:resources mapping="/html/**" location="/html/"></mvc:resources>
</beans>
牵扯到的知识点
@RequestMapping
@RequestMapping
@ResponseBody
@GetMapping
@ModelAttribute
resetful风格
package com.mobao.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Enumeration;
//@Controller:修饰class,用来创建处理http请求的对象
//@RestController:Spring4之后加入的注解,原来在@Controller中返回json需要@ResponseBody来配合,如果直接用@RestController替代@Controller就不需要再配置@ResponseBody,默认返回json格式。
//@RequestMapping:配置url映射,在Spring 4.3 之后,为了更好的支持 RESTful 风格,增加了几个注解:@PutMapping、@GetMapping、@DeleteMapping、@PostMapping,其实也就是将 method 属性的值与 @RequestMapping 进行了绑定而已。
@Controller
//效果相当于二级目录 调用sayhello方法调用接口样式为:..../sayhellotop/sayhello
//@RequestMapping(path = "/sayhellotop")
@RequestMapping(path = "")
public class HelloController {
// RequestMapping
// path和value作用一样
// method表示允许的请求方式
// params该请求需要接收的参数 设置后如果未传入该值则会报错 可不设置 参数会自动绑定到方法参数里
// headers请求必须包含请求头 不包含则会包404错误
@RequestMapping(
path = "/sayhello",
method = {RequestMethod.GET, RequestMethod.POST}
// , params = {"name", "age"}
// , headers = {"token"}
)
@ResponseBody
public String sayhello(String name, Integer age) {
System.out.println("paras ===" + name + ":" + age);
System.out.println(Thread.currentThread());
System.out.println(this);
return "一般请求";
}
@RequestMapping(path = "/beanbound")
// 解决返回数据中文??问题
// @RequestMapping(path = "/beanbound",produces = "application/json; charset=utf-8")
@ResponseBody
// 在接收到参数,spring自身会进行类型的转换 比如birthday date类型(2018/10/10) 但是如果是2018-10-10则无法自动转换 请求会报错
// 自定义类型转换器
public String beanRequestbound(User user) {
System.out.println(user);
return "请求参数实例化绑定";
}
// 获取原始servlet对象
@RequestMapping(path = {"/originalServlet", "/originalServlet2"})
@ResponseBody
public String originalServlet(HttpServletRequest request, HttpServletResponse response, String name) {
Enumeration ary = request.getParameterNames();
while (ary.hasMoreElements()) {
System.out.println("key==" + ary.nextElement());
}
return "好的" + name;
}
@RequestMapping(path = "/aliapara")
@ResponseBody
// RequestParam 指定参数的别名,调用接口传入的key和name不对应,required参数是否必要,默认true,不传则报错
public String aliapara(@RequestParam(value = "nickname", required = false) String name) {
System.out.println(name);
return "参数==" + name;
}
/*** 获取request或者response的各种信息 **/
/*** 直接获取请求体 @RequestBody 请求体只有post请求才会有 **/
@RequestMapping(path = "/requestbody")
@ResponseBody
public String requestbody(@RequestBody String paras) {
System.out.println(paras);
return "获取请求体==" + paras;
}
/*** 获取请求头数据 **/
// token: 123
// Cookie: cookiename=cookievalue
@RequestMapping(path = "/requestheader")
@ResponseBody
public String requestheader(@RequestHeader(name = "token") String token) {
System.out.println(token);
return "获取请求头==" + token;
}
/*** 获取cookie数据 **/
// token: 123
// Cookie: cookiename=cookievalue
@RequestMapping(path = "/requestcookie")
@ResponseBody
public String requestcookie(@CookieValue(name = "cookiename", required = false) String cookiename, @CookieValue(name = "JSESSIONID", required = false) String JSESSIONID) {
System.out.println(cookiename);
return "获取请求头cookie==" + cookiename + "=JSESSIONID=" + JSESSIONID;
}
/*** restful风格 无明确参数名 实际接口调用样式为:/restful/zhangsan/27 **/
@RequestMapping(path = "/restful/{name}/{age}")
@ResponseBody
// 直接获取请求体 @RequestBody 请求体只有post请求才会有
public String resetful(@PathVariable(name = "name") String finalname
, @PathVariable(name = "age") Integer age) {
System.out.println(finalname + age);
return "获取参数==" + finalname + age;
}
@GetMapping(path = "/modeattrthree")
@ResponseBody
public String modeattrthree(String paraone, String paratwo, String parathree) {
return "参数==" + paraone + paratwo + parathree;
}
@GetMapping(path = "/modeattrtwo")
@ResponseBody
public String modeattrtwo(String paraone, String paratwo) {
return "参数==" + paraone + paratwo;
}
@GetMapping(path = "/modeattrone")
@ResponseBody
public String modeattrone(String paraone, ModelMap modelMap) {
System.out.println(modelMap.values());
System.out.println(modelMap.keySet());
return "参数one==" + paraone;
}
/*** ModelAttribute 控制器controller里其他方法调用前,该方法会被调用,可以在执行逻辑前先进行必要的数据处理 **/
// 注:通过拦截的方式抢先得到运行,但是在这个地方获取请求的参数后再进行修改不影响接下来的方法执行的参数,也就是说修改的参数仅在本方法有效
// 因为ModelAttribute所做的所有修改等操作均是设置在了model中,实质上并没有修改请求的参数
@ModelAttribute
public void modelattributemethodVoid(@RequestHeader(name = "token", required = false) String token, String paraone, String paratwo) {
System.out.println("modelattribut不带返回值===paraone:" + paraone + "=paratwo=" + paratwo);
}
//带返回值隐性的ModelAttribute
@ModelAttribute
public Integer modelattributemethod(@RequestHeader(name = "token", required = false) String token, String paraone, String paratwo) {
System.out.println("带返回值 隐性传入model");
// 这里隐性的封装到了model中,在 "modeattrone" 方法中通过参数ModelMap modelMap可将其通过键值对形式取出
// 键为数据类型(这里Integer作为key,不过字母会变成小写)
return 123;
}
//带返回值隐性的ModelAttribute 自定义在model中的key值
@ModelAttribute(value = "customreturnkey")
public Integer modelattributeCustomKey(@RequestHeader(name = "token", required = false) String token, String paraone, String paratwo) {
System.out.println("带返回值 隐性传入model");
// 这里隐性的封装到了model中,在 "modeattrone" 方法中通过参数ModelMap modelMap可将其通过键值对形式取出
// 此时的key值就为指定的 "customreturnkey"
return 123;
}
//在自定义在model中的key值后,取值也可以用注解简化赋值操作
@GetMapping(path = "/modeattroneautopara")
@ResponseBody
public String modeattroneautopara(@ModelAttribute(value = "customreturnkey") Integer customreturnkeyvalue) {
return "带返回值的ModelAttribute通过注解直接获取value==" + customreturnkeyvalue;
}
@GetMapping(path = "/modeattroneautoparaObject")
@ResponseBody
public String modeattroneautoparaObject(@ModelAttribute(value = "user") User user) {
return "带返回值的ModelAttribute通过注解直接获取对象==" + user;
}
//显性的ModelAttribute
@ModelAttribute
public void modelattributAppear(@RequestHeader(name = "token", required = false) String token, String paraone, String paratwo, Model model) {
model.addAttribute("key", "value");
System.out.println("不带返回值 显性设置model");
}
//ModelAttribute 此处抢先获得请求参数,然后对user进行修改 但是不会影响到其他方法参数user,本方法修改的user仅在本方法起作用
@ModelAttribute
public User modelattributObject(User user) {
user.setName("wocao");
System.out.println("ModelAttribute对象处理==" + user);
return user;
}
}
/*** resetful风格 **/
@RestController
@RequestMapping("/restfulstyle")
class RestfulStyle {
@GetMapping("/{para}")
public String resetfultest(@PathVariable(name = "para") String parastring) {
return parastring;
}
@GetMapping("/{para}/{para2}")
public String resetfultest22(@PathVariable(name = "para") String parastring, @PathVariable(name = "para2") String parastring2) {
return parastring + parastring2;
}
@PostMapping("/{para2}")
public String resetfultest2(@PathVariable(name = "para2") String parastring2) {
return parastring2;
}
}
网友评论