1.首先配置springmvc-servlet.xml
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/mvc
https://www.springframework.org/schema/mvc/spring-mvc.xsd">
<context:component-scan base-package="com.bandit.controller"/>
<mvc:default-servlet-handler />
<mvc:annotation-driven />
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="InternalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
beans>
2.配置web.xml和非注解一样,此外加上乱码过滤器部分
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<servlet>
<servlet-name>springmvcservlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServletservlet-class>
<init-param>
<param-name>contextConfigLocationparam-name>
<param-value>classpath:springmvc-servlet.xmlparam-value>
init-param>
<load-on-startup>1load-on-startup>
servlet>
<servlet-mapping>
<servlet-name>springmvcservlet-name>
<url-pattern>/url-pattern>
servlet-mapping>
<filter>
<filter-name>encodingfilter-name>
<filter-class>org.springframework.web.filter.CharacterEncodingFilterfilter-class>
<init-param>
<param-name>encodingparam-name>
<param-value>utf-8param-value>
init-param>
filter>
<filter-mapping>
<filter-name>encodingfilter-name>
<url-pattern>/*url-pattern>
filter-mapping>
web-app>
注意:过滤器url部分是 /* 过滤所有文件,否注静态资源的乱码过滤不了
3.在com.bandit.controller包下建立HelloController类
@Controller
@RequestMapping("/hello")
public class HelloController {
//真实访问地址 : 项目名/HelloController/hello
@RequestMapping("/h1")
public String Hello(Model model){
//向模型中添加属性msg与值,可以在JSP页面中取出并渲染
model.addAttribute("msg","SpringMVC注解实现");
return "hello";//return一个字符串拼接视图,WEB-INF/jsp/hello.jsp
}
}
4.在WEB-INF下建立jsp文件夹,新建hello.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
hello标题
${msg}
5.配置tomcat并输出
打开Project Structure进行如图操作
保证DispatcherServlet的url为:/ ,因为/*会让jsp文件等静态资源无法访问
来看一下对比:
传统方法:http://localhost:8080/t1?a=1&b=1
RESTful:http://localhost:8080/t1/1/1
RESTful风格能隐藏我们数据的传递,一定程度上保证了安全性
1.在com.bandit.controller包下新建RestFullController类
package com.bandit.controller;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
@Controller
public class RestFullController {
//传统方法:http://localhost:8080/t1?a=1&b=1
@RequestMapping("/t1")
public String Test(int a, int b, Model model){
int res = a + b;
model.addAttribute("msg","结果:"+res);
return "test";
}
//restfull:http://localhost:8080/t1/1/1
@RequestMapping("/t2/{a}/{b}")
public String Test2(@PathVariable int a,@PathVariable int b, Model model){
int res = a + b;
model.addAttribute("msg","结果:"+res);
return "test";
}
//@RequestMapping(value = "/t3",method = RequestMethod.POST)等价PostMapping
//post方式自动采用旧版格式,/t3?a= ,b=
@RequestMapping(value = "/t3",method = RequestMethod.POST)
public String Test3(int a, int b, Model model){
int res = a + b;
model.addAttribute("msg","结果:"+res);
return "test";
}
}
2.在web文件夹下建立一个表单,action为 /t3
form
/t1 : 采用传统方法,访问http://localhost:8080/t1?a=1&b=1
/t2 : 采用RESTful方法,访问http://localhost:8080/t1/1/1
/t3+form.jsp : 采用表单提交的方式,其会默认采用旧格式将值传递到该页面
上例中,@RequsetMapping这样写了
@RequestMapping(value = "/t3",method = RequestMethod.POST)
value为地址,也可以写成path,path和value互为别名
method即为其提交方式,如下图可以有这些方式:GET,HEAD,POST,PUT,PATCH,DELETE,OPTIONS,TRACE
则对应的@RequsetMapping有子类
@GetMapping
@PostMapping
@PutMapping
@PatchMapping
@DeleteMapping
按照注解版搭建方式新建一个Module
1.在com.bandit.controller包下建立ServletController类
@Controller
public class ServletController {
@RequestMapping("/t1")
public String test(HttpServletRequest req, HttpServletResponse resp) throws IOException {
req.setCharacterEncoding("GBK");
resp.setCharacterEncoding("GBK");
req.getSession().setAttribute("msg","Servlet方式设置msg");
resp.getWriter().write("测试1");
return "test";
}
@RequestMapping("/t2")
public void test2(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
req.getSession().setAttribute("msg","这是转发");
req.getRequestDispatcher("/WEB-INF/jsp/re.jsp").forward(req,resp); //转发可以访问web-inf里的,重定向不行
}
@RequestMapping("/t3")
public void test3(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
req.getSession().setAttribute("msg","这是重定向");
resp.sendRedirect("/redirect.jsp");
}
}
Servlet的方式:
给页面元素赋值:req.getSession().setAttribute(“msg”,“Servlet方式设置msg”);
转发:req.getRequestDispatcher("/WEB-INF/jsp/re.jsp").forward(req,resp);
重定向:resp.sendRedirect("/redirect.jsp");
注意:转发可以访问web-inf里的,重定向不行
2.在/WEB-INF/jsp下新建re.jsp,在web下新建redirect.jsp
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
转发
转发到此
${msg}
重定向到此
重定向到此
${msg}
3.配置Tomcat测试
@Controller
public class SpringController {
@RequestMapping("/s1")
public String test(Model model){
model.addAttribute("msg","默认为转发");
return "test";
}
@RequestMapping("/s2")
public String test2(Model model){
model.addAttribute("msg","前缀为forward,显示设置为转发,不会经过视图解析器");
return "forward:/WEB-INF/jsp/re.jsp";
}
@RequestMapping("/s3")
public String test3(Model model){
model.addAttribute("msg","前缀为redirect,显示设置为重定向,不会经过视图解析器");
return "redirect:/redirect.jsp";
}
}
springmvc中return就是跳转页面
JSON(JavaScript Object Notation, JS 对象简谱) 是一种轻量级的数据交换格式。它基于 ECMAScript (欧洲计算机协会制定的js规范)的一个子集,采用完全独立于编程语言的文本格式来存储和表示数据。简洁和清晰的层次结构使得 JSON 成为理想的数据交换语言。 易于人阅读和编写,同时也易于机器解析和生成,并有效地提升网络传输效率。
在前后端分离的项目中就是用json传输数据的
两种方式所需要的依赖:
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.12.3version>
dependency>
<dependency>
<groupId>com.alibabagroupId>
<artifactId>fastjsonartifactId>
<version>1.2.60version>
dependency>
1.建一个实体类User
@Data
@AllArgsConstructor
@NoArgsConstructor
public class User {
private int id;
private String name;
private int age;
}
2.建立UserController类和JsonUtils类,其中/json5就是JsonUtils封装后简化的代码
@Controller
public class UserController {
@RequestMapping("/json1")
@ResponseBody //@ResponseBody标记后不会走视图解析器
public String json1() throws JsonProcessingException {
//创建一个jackson的对象映射器,用来解析数据
ObjectMapper mapper = new ObjectMapper();
//创建一个对象
User user = new User(1,"bandit",20);
//将我们的对象解析成为json格式
String str = mapper.writeValueAsString(user);
//由于@ResponseBody注解,这里会将str转成json格式返回;
return str;
}
@RequestMapping("/json2")
@ResponseBody
public String json2() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
User user1 = new User(1,"bandit",20);
User user2 = new User(2,"bandit1",21);
User user3 = new User(3,"bandit2",22);
User user4 = new User(4,"bandit3",23);
List<User> users = new ArrayList<>();
users.add(user1);
users.add(user2);
users.add(user3);
users.add(user4);
String str = mapper.writeValueAsString(users);
return str;
}
@RequestMapping("/json3")
@ResponseBody
public String json3() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
//创建时间一个对象,java.util.Date
Date date = new Date();
//将我们的对象解析成为json格式
String str = mapper.writeValueAsString(date);
return str;
}
@RequestMapping("/json4")
@ResponseBody
public String json4() throws JsonProcessingException {
ObjectMapper mapper = new ObjectMapper();
//不使用时间戳的方式
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//自定义日期格式对象
SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
//指定日期格式
mapper.setDateFormat(sdf);
Date date = new Date();
String str = mapper.writeValueAsString(date);
return str;
}
@RequestMapping("/json5")
@ResponseBody
public String json5() throws JsonProcessingException {
Date date = new Date();
String json = JsonUtils.getJSON(date);
return json;
}
}
public class JsonUtils {//封装成utils类
public static String getJSON(Object object){
return getJSON(object,"yyyy-MM-dd HH:mm:ss");
}
public static String getJSON(Object object,String dateFormat){
ObjectMapper mapper = new ObjectMapper();
//不使用时间戳的方式
mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
//自定义日期格式对象
SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
//指定日期格式
mapper.setDateFormat(sdf);
try {
return mapper.writeValueAsString(object);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return null;
}
}
public class FastJson {
public static void main(String[] args) {
//创建一个对象
User user1 = new User(1,"bandit",20);
User user2 = new User(2,"bandit1",21);
User user3 = new User(3,"bandit2",22);
User user4 = new User(4,"bandit3",23);
List<User> list = new ArrayList<User>();
list.add(user1);
list.add(user2);
list.add(user3);
list.add(user4);
System.out.println("*******Java对象 转 JSON字符串*******");
String str1 = JSON.toJSONString(list);
System.out.println("JSON.toJSONString(list)==>"+str1);
String str2 = JSON.toJSONString(user1);
System.out.println("JSON.toJSONString(user1)==>"+str2);
System.out.println("\n****** JSON字符串 转 Java对象*******");
User jp_user1=JSON.parseObject(str2,User.class);
System.out.println("JSON.parseObject(str2,User.class)==>"+jp_user1);
System.out.println("\n****** Java对象 转 JSON对象 ******");
JSONObject jsonObject1 = (JSONObject) JSON.toJSON(user2);
System.out.println("(JSONObject) JSON.toJSON(user2)==>"+jsonObject1.getString("name"));
System.out.println("\n****** JSON对象 转 Java对象 ******");
User to_java_user = JSON.toJavaObject(jsonObject1, User.class);
System.out.println("JSON.toJavaObject(jsonObject1, User.class)==>"+to_java_user);
}
}
测试:
在springmvc-servlet.xml新增
<mvc:annotation-driven>
<mvc:message-converters register-defaults="true">
<bean class="org.springframework.http.converter.StringHttpMessageConverter">
<constructor-arg value="UTF-8"/>
bean>
<bean class="org.springframework.http.converter.json.MappingJackson2HttpMessageConverter">
<property name="objectMapper">
<bean class="org.springframework.http.converter.json.Jackson2ObjectMapperFactoryBean">
<property name="failOnEmptyBeans" value="false"/>
bean>
property>
bean>
mvc:message-converters>
mvc:annotation-driven>