官网文档
<dependency>
<groupId>javax.servletgroupId>
<artifactId>javax.servlet-apiartifactId>
<version>4.0.1version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servlet.jspgroupId>
<artifactId>jsp-apiartifactId>
<version>2.2.1-b03version>
<scope>providedscope>
dependency>
<dependency>
<groupId>javax.servletgroupId>
<artifactId>jstlartifactId>
<version>1.2version>
dependency>
public class HelloServlet extends HttpServlet {
@Override
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//1. 获取前端参数
String method = req.getParameter("method");
if (method.equals("add")){
req.getSession().setAttribute("msg","执行了add方法");
}
if (method.equals("delete")){
req.getSession().setAttribute("msg","执行了delete方法");
}
//2. 调用业务层
//3. 试图转发或者重定向
req.getRequestDispatcher("/WEB-INF/jsp/test.jsp").forward(req,resp);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doPost(req, resp);
}
}
<servlet>
<servlet-name>helloservlet-name>
<servlet-class>com.chelsea.servlet.HelloServletservlet-class>
servlet>
<servlet-mapping>
<servlet-name>helloservlet-name>
<url-pattern>/hellourl-pattern>
servlet-mapping>
<session-config>
<session-timeout>15session-timeout>
session-config>
<welcome-file-list>
<welcome-file>index.jspwelcome-file>
welcome-file-list>
<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>
web-app>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans
https://www.springframework.org/schema/beans/spring-beans.xsd">
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
bean>
<bean id="/hello" class="com.chelsea.controller.HelloController"/>
beans>
/*首先实现SpringMVC的Controller接口*/
public class HelloController implements Controller {
@Override
public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws Exception {
/*modelAndView*/
ModelAndView mv = new ModelAndView();
//封装对象,放到ModelAndView种
mv.addObject("msg","HelloSpringMVC!");
//封装要跳转的试图,放到ModelAndView中
//WEB-INF/jsp/hello.jsp
mv.setViewName("hello");
return mv;
}
}
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Titletitle>
head>
<body>
${msg}
body>
html>
<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
https://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
https://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.chelsea.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>
/*配置此注解,则不会被视图解析器解析,用于返回json格式的字符串*/
/*@RestController*/
@Controller
public class HelloController {
@RequestMapping("/hello")
public String Hello(Model model){
//封装数据
model.addAttribute("msg","HelloServlet!");
/*这个返回的字符串会被视图解析器处理*/
return "hello";
}
}
@Controller
public class RestFulController {
//使用RestFul风格,目前主要是@PathVaruable注解
//还可以指定这个注解,指定post方法 @PostMapping
//还可以指定这个注解,指定Get方法 @GetMapping
@PostMapping(value = "/add/{a}/{b}")
public String test1(@PathVariable int a, @PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","结果1为:"+res);
return "demo1";
}
//通过这种方式,根据访问方式不同,来进行不同逻辑控制
@GetMapping(value = "/add/{a}/{b}")
public String test2(@PathVariable int a, @PathVariable int b, Model model){
int res = a+b;
model.addAttribute("msg","结果2为:"+res);
return "demo1";
}
}
@Controller
@RequestMapping("/user")
public class UserController {
//@RequsetParam注解用来固定前端传参的对象名,来绑定到形参上,如果名称一样可省略,个人建议加上
@RequestMapping("/t1")
public String test1(@RequestParam("username") String name, Model model){
//接收前端参数
System.out.println("接收到的前端数据为:"+name);
//将返回的结果返回到前端
model.addAttribute("name",name);
//跳转视图
return "demo1";
}
/*
* 1.接受前端用户传递的参数,判断参数的名字,假设名字直接在方法上,可以直接使用
* 2.假设传递的是一个User对象,则会自动匹配User对象中的字段名,如果一样则ok,否则为null
* 实例:url=localhost/user/t1?id=3&username=chelsea&age=20----------------------->结果=User{id=3,name=null,age=20}
*
* */
//假如前端接受的是对象,可以直接将参数设置为对象,会自动匹配
//前端url为:localhost/user/t2?id=1&name=chelsea&age=19
@RequestMapping("/t2")
public String test2(User user){
System.out.println(user);
return "demo1";
}
}
public class EncodingFilter extends HttpFilter {
/*此处继承HttpFilter,也可以实现Filter接口,重写三个方法,init doFilter destory*/
/*记得在webxml文件中配置filter*/
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException, ServletException {
//进行处理
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
//处理后将请求继续转发
chain.doFilter(request,response);
}
}
<filter>
<filter-name>encodingFilterfilter-name>
<filter-class>com.chelsea.filter.EncodingFilterfilter-class>
filter>
<filter-mapping>
<filter-name>encodingFilterfilter-name>
<url-pattern>/*url-pattern>
filter-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>
var obj = {a: 'Hello', b: 'World'}; //这是一个对象,注意键名也是可以使用引号包裹的
var json = '{"a": "Hello", "b": "World"}'; //这是一个 JSON 字符串,本质是一个字符串
//将JSON字符串转换为JS对象
var obj = JSON.parse('{"a": "Hello", "b": "World"}');
//结果是 {a: 'Hello', b: 'World'}
//将JS对象转换为JSOn字符串
var json = JSON.stringify({a: 'Hello', b: 'World'});
//结果是 '{"a": "Hello", "b": "World"}'
<dependency>
<groupId>com.fasterxml.jackson.coregroupId>
<artifactId>jackson-databindartifactId>
<version>2.12.3version>
dependency>
//此处只展示了这两个包,其他的未展示而已
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
@Controller
/*此注解作用:使本类下的所有方法都绕开视图解析器,返回字符串*/
@RestController
public class UserController {
/*@Responsebody配置后,就不会走视图解析器,会直接返回一个字符串*/
@ResponseBody
@RequestMapping(value = "/j1",produces = "application/json;charset=utf-8")
public String json1(){
/*使用jackson,转为json对象*/
ObjectMapper mapper = new ObjectMapper();
User user = new User(1,"韩信",14);
String str = null;
try {
str = mapper.writeValueAsString(user);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
/*
* 如果不适用json,则返回的user对象为:User(id=1, name=chelsea, age=14)
* 使用json后,返回的json类型的对象为:{"id":1,"name":"chelsea","age":14}
*
* */
return str;
}
/*@Responsebody配置后,就不会走视图解析器,会直接返回一个字符串*/
@ResponseBody
@RequestMapping(value = "/j2",produces = "application/json;charset=utf-8")
public String json2(){
/*使用jackson,转为json对象*/
ObjectMapper mapper = new ObjectMapper();
List<User> userList = new ArrayList<User>();
User user = new User(1,"韩信",14);
User user1 = new User(1,"韩信",14);
User user2 = new User(1,"韩信",14);
User user3 = new User(1,"韩信",14);
userList.add(user);
userList.add(user1);
userList.add(user2);
userList.add(user3);
String str = null;
try {
str = mapper.writeValueAsString(userList);
} catch (JsonProcessingException e) {
e.printStackTrace();
}
return str;
}
}