博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
springMVC 5.1.6版本
阅读量:6175 次
发布时间:2019-06-21

本文共 8596 字,大约阅读时间需要 28 分钟。

hot3.png

入门

导包

c6659849001ceb65e25aff9a235412eb630.jpg

配置 web.xml,所有的请求由springMVC管理

DispatcherServlet
org.springframework.web.servlet.DispatcherServlet
1
DispatcherServlet
*.do

在 WEB-INF 下创建 DispatcherServlet-servlet.xml

创建 UserController

package com.company.web.controller;import org.springframework.web.servlet.ModelAndView;import org.springframework.web.servlet.mvc.Controller;public class UserController implements Controller {    @Override    public ModelAndView handleRequest(javax.servlet.http.HttpServletRequest httpServletRequest, javax.servlet.http.HttpServletResponse httpServletResponse) throws Exception {        ModelAndView modelAndView = new ModelAndView("user/userlist");        modelAndView.addObject("name", "tom");        return modelAndView;    }}

创建接收tom的jsp文件 userlist.jsp

<%--  Created by IntelliJ IDEA.  User: mac  Date: 2019-04-18  Time: 14:06  To change this template use File | Settings | File Templates.--%><%@ page contentType="text/html;charset=UTF-8" language="java" %>    Title${name}

目录结构

e4e313dd09d82a1b2e10cfb2b5ef3f63e5a.jpg

浏览器输入 

3ca14730244643c92eca4e3673cf634856d.jpg

url处理映射

方式一

即入门 DispatcherServlet-servlet.xml

方式二

userController

方式三 --未实现待整理

原因:ControllerClassNameHandlerMapping 未找到

控制器处理适配器

方式一

即入门 DispatcherServlet-servlet.xml

方式二

package com.company.web.controller;import org.springframework.web.HttpRequestHandler;import javax.servlet.ServletException;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;import java.io.IOException;public class UserControllerHttp implements HttpRequestHandler {    @Override    public void handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws ServletException, IOException {        httpServletRequest.setAttribute("name", "tom");        httpServletRequest.getRequestDispatcher("/WEB-INF/views/user/userlist.jsp").forward(httpServletRequest, httpServletResponse);    }}

注解

配置 DispatcherServlet-servlet.xml

package com.company.web.controller;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;@Controller@RequestMapping("/user")public class UserController1 {    //@RequestMapping("list")    //@RequestMapping("/list")    @RequestMapping(value = "list", method = RequestMethod.GET)    public String list() {        return "user/userlist";    }}

1b23f781a70fa0fa0562e1fdb31a04a64aa.jpg

接收表单参数

方式一

@RequestMapping("add")    public String add(String username, String password) {        return "user/info";    }

方式二

@RequestMapping("add")    public String add(User user) {        return "user/info";    }

方式三

public class UserExt {    private User user;    private List
userList = new ArrayList<>(); private Map
infos = new HashMap<>();
@RequestMapping("add")    public String add(UserExt userExt) {        return "user/info";    }

1.模型

2.list


3.map

使用Model存储数据

@RequestMapping("list2")    public String list2(Model model) {        List
list = new ArrayList
(); User user = new User("zhangsan", "123456"); list.add(user); User user1 = new User("lisi", "123"); list.add(user1); model.addAttribute("userlist", list); return "user/userlist"; }

@PathVariable

@RequestMapping("edit/{id}")    public String edit(@PathVariable int id, Model model) {        return "user/userlist";    }

转发和重定向

//转发    @RequestMapping("test")    public String test() {        //同一个控制器        //return "forward:list.do";                //不同一个控制器        return "forward:/user/list.do";    }        //重定向    @RequestMapping("test")    public String test() {        //同一个控制器        //return "redirect:list.do";        //不同一个控制器        return "redirect:/user/list.do";    }

@RequestParam

@RequestMapping("test2")    /**     * value:参数名称     * required:默认值     * defaultValue:参数是否必须有值     * */    public String test3(@RequestParam(value = "id", required = true, defaultValue = "30") int id) {        return "user/userlist";    }

@RequestBody 和 @ResponseBody

  • @RequestBody     把json数据转成模型数据
  • @ResponseBody   返回json对象

导包

f9776c3b817e9ba01c9c4b212ff4a100e96.jpg

1a63137df40c9e921869b3105c447230edb.jpg

配置文件 DispatcherServlet-servlet.xml

接收和响应json数据

adduser.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>    Title        

 

@RequestMapping("save")    public @ResponseBody User save(@RequestBody User user) {        System.out.println(user);        return user;    }

响应json数据

<%@ page contentType="text/html;charset=UTF-8" language="java" %>    Title

 

@RequestMapping("save")    public @ResponseBody User save(User user) {        System.out.println(user);        return user;    }

关于多视图错误

org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.view.ContentNegotiatingViewResolver#0' defined in ServletContext resource [/WEB-INF/DispatcherServlet-servlet.xml]: Cannot create inner bean 'org.springframework.web.servlet.view.xml.MarshallingView#7675bdb0' of type [org.springframework.web.servlet.view.xml.MarshallingView] while setting bean property 'defaultViews' with key [1]; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.web.servlet.view.xml.MarshallingView#7675bdb0' defined in ServletContext resource [/WEB-INF/DispatcherServlet-servlet.xml]: Cannot create inner bean 'org.springframework.oxm.jaxb.Jaxb2Marshaller#618ea1bf' of type [org.springframework.oxm.jaxb.Jaxb2Marshaller] while setting constructor argument; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'org.springframework.oxm.jaxb.Jaxb2Marshaller#618ea1bf': Lookup method resolution failed; nested exception is java.lang.IllegalStateException: Failed to introspect Class [org.springframework.oxm.jaxb.Jaxb2Marshaller] from ClassLoader [ParallelWebappClassLoader...

需要导包

766c09c3f86afc58a31d2673428e2bd1937.jpg

springmvc拦截器

配置拦截器 DispatcherServlet-servlet.xml 

LoginInterceptor

package com.company.web.interceptor;import org.springframework.web.servlet.HandlerInterceptor;import org.springframework.web.servlet.ModelAndView;import javax.servlet.http.HttpServletRequest;import javax.servlet.http.HttpServletResponse;public class LoginInterceptor implements HandlerInterceptor {    @Override    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {        //排除不需要拦截路径        System.out.println("客户端访问资源的路径:" + request.getRequestURI());        if (request.getRequestURI().endsWith("login.do")) {            return true;//放行        }        //如果已经登录,也要放行        if (request.getSession().getAttribute("user") != null) {            return true;        }        //进入到login页面        request.getRequestDispatcher("/WEB-INF/views/login.jsp").forward(request, response);        return false;    }    @Override    public void postHandle(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, ModelAndView modelAndView) throws Exception {        System.out.println("未返回视图前 后处理");    }    @Override    public void afterCompletion(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Object o, Exception e) throws Exception {        System.out.println("返回视图前 后处理");    }}

默认跳转到登录页面

index.jsp

<%@ page contentType="text/html;charset=UTF-8" language="java" %>    Title

 

转载于:https://my.oschina.net/gwlCode/blog/3038571

你可能感兴趣的文章
Android Studio导出jar包
查看>>
通过python 爬取网址url 自动提交百度
查看>>
我的友情链接
查看>>
乔布斯走了,苹果会坠落吗?
查看>>
EFI分区不格盘,不重新分区,不丢数据安装32位win7方法
查看>>
java高级_01
查看>>
win8重装成win8.1后把hyperv的虚拟机导入
查看>>
linux命令汇总(mkdir、rmdir、touch、dirname、basename)
查看>>
mv或者cp带小括号文件名解析问题总结
查看>>
Elasticsearch学习笔记3: bulk批量处理
查看>>
EBS12.2.5 升级到EBS12.2.6的问题及跟踪处理
查看>>
网站访问流程
查看>>
java的日志工具log4j的配置方法
查看>>
jQuery on()方法
查看>>
步调一致才能得胜利
查看>>
mysql 锁机制
查看>>
add_header X-Frame-Options "SAMEORIGIN";NGINX
查看>>
java -- ==与equals的区别
查看>>
获取当前日期前x天日期
查看>>
linux中的计划任务
查看>>