URL Mapping 注解
- @RequestMapping 通用绑定
可以作用在方法上 或作用在类上 作用在方法上表示可以接受get请求和post请求 作用在类身上url中多一层子集 比如 某网址 www.abc.com/g 这条链接 通过这个注解作用在类上定义一个 @RequestMapping("/um") 这样链接要用 www.abc.com/um/g 才能访问 - @GetMapping 绑定get请求
作用在方法上 只能接受get请求 - @PostMapping 绑定post请求
作用在方法上 只能接受post请求
package com.lovelves.springmvc.controller;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
@Controller
@RequestMapping("/um")
public class UrlMappingController {
@GetMapping("/g")
@ResponseBody
public String getMapping(){
return "this is getMapping";
}
@PostMapping("/p")
@ResponseBody
public String postMapping(){
return "this is postMapping";
}
@RequestMapping(value = "/r",method = RequestMethod.GET) //后面不加method 表示通用 get post 都可以用
@ResponseBody
public String requestMapping(){
return "this.is requestMapping on get";
}
}
接受浏览器的传过来的参数
1.比如浏览器通过get方式请求 http://localhost:8080/um/g?manger_name=lily 我们在程序中接受的方法如下
@GetMapping("/g")
@ResponseBody
public String getMapping(@RequestParam("manger_name") String mangerName){
System.out.println(mangerName);
return "this is getMapping";
}
这里有注意的一个点 第一个点是 浏览器传过来的参数名字和方法中接受参数的名字必须一样,第二个点是 比如我们想在方法上使用驼峰的命名方法 但是浏览器提供的参数不是驼峰格式的 如 manger_name 我们想在方法上用mangerName来名字 就使用参数注解 @RequestParam()与之对应 如上代码所示
2,接受通过post表单的数据
<form action="/um/p" method="post">
<input type="text" name="username"><br>
<input type="password" name="password"><br>
<input type="submit" value="提交">
</form>
@PostMapping("/p")
@ResponseBody
public String postMapping(String username, String password){
System.out.println(username+":"+password);
return "this is postMapping";
}
注意 html中的name属性和方法中参数必须一致
3,用java bean 接受浏览器中的参数
创建一个用来接受参数的实体类
package com.lovelves.springmvc.entity;
import org.springframework.web.bind.annotation.RequestParam;
public class User {
String userName;
String passWord;
public String getUserName() {
return userName;
}
public void setUserName(String userName) {
this.userName = userName;
}
public String getPassWord() {
return passWord;
}
public void setPassWord(String passWord) {
this.passWord = passWord;
}
@Override
public String toString() {
return "User{" +
"userName='" + userName + '\'' +
", passWord='" + passWord + '\'' +
'}';
}
}
然后接受方法上直接用实体类作为参数
@PostMapping("/p")
@ResponseBody
public String postMapping(User u){
System.out.println(u);
return "this is postMapping";
}
注意的是 接受的参数名字 必须和实体类的属性一致
案例 接受一组数据
div>
<h2>学员调查问卷表</h2>
<form action="/um/apply" method="post">
<h3>你的姓名</h3><input name="name" style="...">
<h3>你正在学习的技术方向</h3>
<select name="course" style="...">
<option value="java">java</option>
<option value="h5">html5</option>
<option value="python">python</option>
<option value="php">php</option>
</select>
<div>
<h3>你的学习目的</h3>
<input type="checkbox" name="purpose" value="1">就业找工作
<input type="checkbox" name="purpose" value="2">工作要求
<input type="checkbox" name="purpose" value="3">兴趣爱好
<input type="checkbox" name="purpose" value="4">其他
</div>
<input type="submit" value="提交">
</form>
</div>
@PostMapping("/apply")
@ResponseBody
public String apply(String name,String course, Integer[] purpose){
for(Integer a :purpose){
System.out.println(a);
}
return "this is "+name+" and "+course;
}
@PostMapping("/apply")
@ResponseBody
public String apply(String name,String course, @RequestParam List<Integer> purpose){
for(Integer a :purpose){
System.out.println(a);
}
return "this is "+name+" and "+course;
}
接受数组的 用列表接受 要在参数前添加 @RequestParam
占位符 比如用户没有输入用户名 我们默认给一个值
@PostMapping("/apply")
@ResponseBody
public String apply(@RequestParam(value = "n",defaultValue = "hello") String name,String course, @RequestParam List<Integer> purpose){
for(Integer a :purpose){
System.out.println(a);
}
return "this is "+name+" and "+course;
}
name 没有值的话 直接默认为hello
关联对象赋值
一个实体类的属性是另外一个实体类
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Title</title>
</head>
<body>
<div>
<h2>学员调查问卷表</h2>
<form action="/um/apply" method="post">
<h3>你的姓名</h3><input name="name" style="...">
<h3>你正在学习的技术方向</h3>
<select name="course" style="...">
<option value="java">java</option>
<option value="h5">html5</option>
<option value="python">python</option>
<option value="php">php</option>
</select>
<div>
<h3>你的学习目的</h3>
<input type="checkbox" name="purpose" value="1">就业找工作
<input type="checkbox" name="purpose" value="2">工作要求
<input type="checkbox" name="purpose" value="3">兴趣爱好
<input type="checkbox" name="purpose" value="4">其他
</div>
手机号码:<input type="text" name="card.phone"> <br>
身份号码:<input type="text" name="card.card"> <br>
昵称:<input type="text" name="card.name"> <br>
<input type="submit" value="提交">
</form>
</div>
</body>
</html>
package com.lovelves.springmvc.entity;
public class Card {
private String name;
private String card;
private String phone;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCard() {
return card;
}
public void setCard(String card) {
this.card = card;
}
public String getPhone() {
return phone;
}
public void setPhone(String phone) {
this.phone = phone;
}
}
package com.lovelves.springmvc.entity;
import org.springframework.web.bind.annotation.RequestParam;
import java.util.List;
public class User {
private String name;
private String course;
private List<Integer> purpose;
private Card card = new Card();
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getCourse() {
return course;
}
public void setCourse(String course) {
this.course = course;
}
public List<Integer> getPurpose() {
return purpose;
}
public void setPurpose(List<Integer> purpose) {
this.purpose = purpose;
}
public Card getCard() {
return card;
}
public void setCard(Card card) {
this.card = card;
}
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", course='" + course + '\'' +
", purpose=" + purpose +
", card=" + card +
'}';
}
}
@PostMapping("/apply")
@ResponseBody
public String apply2(User u){
System.out.println(u);
String phone=u.getCard().getPhone();
System.out.println(phone);
return "this is data"+u;
}
接受日期数据
- 在参数上加上注解@DateTimeFormat(pattern = “yyyy-MM-dd”) 把浏览器传过来的日期数据转化为对应的Date对象
- 在实体类中属性加上该注解也有效
@GetMapping("/tb")
@ResponseBody
public String fromDate(@DateTimeFormat(pattern = "yyyy-MM-dd") Date time){
System.out.println(time);
return "the time is "+time;
}
- 设置一个全局的 只要浏览器传过来日期字符串 自动转化为Date对象 不用每次手动加注解
步骤1: 设置一个转换类
package com.lovelves.springmvc.converter;
import org.springframework.core.convert.converter.Converter;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
public class MyDateConverter implements Converter<String, Date> {
@Override
public Date convert(String s) {
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
try {
Date d = sdf.parse(s);
return d;
} catch (ParseException e) {
e.printStackTrace();
}
return null;
}
}
步骤2: 在配置文件通知springmvc 有那些转化类
<!-- 通知springmvc 有那些转换类-->
<bean id="converter" class="org.springframework.format.support.FormattingConversionServiceFactoryBean">
<property name="converters">
<set>
<bean class="com.lovelves.springmvc.converter.MyDateConverter"/>
</set>
</property>
</bean>
步骤3: 启动转化服务 conversion-service
<mvc:annotation-driven conversion-service="converter"/>
解决中文乱码问题
-
get请求的乱码解决方法
修改tomcat目录下conf中的server.xml文件 加上 URIEncoding=“UTF-8” 注意的是mysql 8.0后默认是加上这句话的
-
解决post请求
在web.xml 中添加filter
<filter>
<filter-name>characterFilter</filter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
<init-param>
<param-name>encoding</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>characterFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
- 解决response 响应乱码
<mvc:annotation-driven conversion-service="converter">
<!-- 解决response响应乱码-->
<mvc:message-converters>
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<property name="supportedMediaTypes">
<list>
<value>text/html;charset=utf-8</value>
</list>
</property>
</bean>
</mvc:message-converters>
响应产生的结果
@ResponseBody 产生响应文本 过程不涉及任何视图 可产生json 字符串 xml 等数据 被StringHttpMessageConverter影响
@ModerlAndView 利用模版引擎输出 数据与模版视图绑定 默认视图模板是jsp 可用其他模版代替
@GetMapping("/ui")
public ModelAndView jsp(){
ModelAndView mv = new ModelAndView("/view.jsp");
return mv;
}
传入对象到jsp 中显示
@GetMapping("/ui")
public ModelAndView jsp(){
ModelAndView mv = new ModelAndView("/view.jsp");
User u = new User();
u.setName("hello");
u.setCourse("computer");
mv.addObject("u",u);
return mv;
}
jsp中获取数据
<html>
<body>
hello world
${u.name}
${u.course}
</body>
</html>
addObject() 方法默认存放在当前请求当中 请求转发致页面 forward
要重定向 使用 new ModelAndView(“redirect:/view.jsp”);
SpringMvc 整合FreeMarkMarker
- 引用依赖
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.example</groupId>
<artifactId>lovelvesOne</artifactId>
<version>1.0-SNAPSHOT</version>
<repositories>
<repository>
<id>aliyun</id>
<name>aliyun</name>
<url>http://maven.aliyun.com/repository/public</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.19.RELEASE</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context-support</artifactId>
<version>5.1.19.RELEASE</version>
</dependency>
<dependency>
<groupId>org.freemarker</groupId>
<artifactId>freemarker</artifactId>
<version>2.3.28</version>
</dependency>
</dependencies>
</project>
配置application.xml
<bean id="ViewResolver" class="org.springframework.web.servlet.view.freemarker.FreeMarkerViewResolver">
<property name="contentType" value="text/html;charset=utf-8"/>
<property name="suffix" value=".ftl"/>
</bean>
<bean id="freemarkerConfig" class="org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer">
<property name="templateLoaderPath" value="/WEB-INF/ftl"/>
<property name="freemarkerSettings">
<props>
<prop key="defaultEncoding">UTF-8</prop>
</props>
</property>
</bean>
测试 视图是否正常
@GetMapping("/ui")
public ModelAndView jsp(){
ModelAndView mv = new ModelAndView("/test1");
User u = new User();
u.setName("hello");
u.setCourse("computer");
mv.addObject("u",u);
return mv;
}
<html>
<body>
hello world
${u.name}
${u.course}
</body>
</html>