SpringMVC

in 编程
关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9

1 转发和重定向

// 利用原生的request和response
    @RequestMapping("login5.do")
    public void login5(HttpServletRequest request, HttpServletResponse response) throws Exception {
        // 重定向
        // response.sendRedirect("success.jsp");
        // 转发
        request.getRequestDispatcher("success.jsp").forward(request, response);
    }

    // 返回字符串的形式
    @RequestMapping("login6.do")
    public String login6(){
        // 重定向
        return "redirect:success.jsp";
        // return "forward:success.jsp";
    }
    // 携带数据进行传输
    @RequestMapping("login7.do")
    public String login7(ModelMap modelMap, HttpServletRequest request){
        String userName = request.getParameter("userName");
        // 转发
        modelMap.put("userName", userName);
        return "forward:success.jsp";
    }

    @RequestMapping("login8.do")
    public String login8(HttpServletRequest request, RedirectAttributes r){
        String userName = request.getParameter("userName");
        r.addFlashAttribute("userName", userName);
        return "redirect:success.do";
    }
    @RequestMapping("success.do")
    public String success(HttpServletRequest request){
        String userName = request.getParameter("userName");
        request.setAttribute("userName", userName);
        return "success.jsp";
    }

2 数据处理

2.1 登录视图


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="login1.do" method="post">
        <label>姓名:<input type="text" name="userName"></label>
        <label><input type="submit" value="登陆"></label>
    </form>
    <form action="login2.do" method="post">
        <label>姓名:<input type="text" name="userName"></label>
        <label><input type="submit" value="登陆"></label>
    </form>
    <form action="login3.do" method="post">
        <label>编号:<input type="text" name="uid"></label>
        <label>姓名:<input type="text" name="uname"></label>
        <label>密码:<input type="text" name="upass"></label>
        <label><input type="submit" value="登陆"></label>
    </form>
    <form action="login4.do" method="post">
        <label>姓名:<input type="text" name="userName"></label>
        <label><input type="submit" value="登陆"></label>
    </form>
    <form action="login5.do" method="post">
        <label>姓名:<input type="text" name="userName"></label>
        <label><input type="submit" value="登陆"></label>
    </form>
    <form action="login6.do" method="post">
        <label>姓名:<input type="text" name="userName"></label>
        <label><input type="submit" value="登陆"></label>
    </form>
    <form action="login7.do" method="post">
        <label>姓名:<input type="text" name="userName"></label>
        <label><input type="submit" value="登陆"></label>
    </form>
    <form action="login8.do" method="post">
        <label>姓名:<input type="text" name="userName"></label>
        <label><input type="submit" value="登陆"></label>
    </form>
</body>
</html>

2.2 数据处理方式

// 为控制器指定处理哪些URL的请求
    @RequestMapping("login1.do")
    public String login1(HttpServletRequest request){
        // 通过request对象获取值
        String userName = request.getParameter("userName");
        System.out.println("进行登陆业务:"+userName);
        request.setAttribute("userName", userName);
        return "success.jsp";
    }
    @RequestMapping("login2.do")
    public String login2(String userName, Model model){
        // 直接在普通的方法里面,加上一个参数,参数名称要和input里面的name一样
        System.out.println("进行登陆业务2:"+userName);
        // Model就是专门用来传递数据的对象
        model.addAttribute("userName", userName);
        return "success.jsp";
    }
    @RequestMapping("login3.do")
    public String login3(UserEntity userEntity, ModelMap modelMap, Map<String, String> map){
        // 参数里面有一个实体类, 实体类的属性名称要和input的name要一样
        System.out.println("进行登陆业务3:"+userEntity.getUname());
        // modelMap.put("userName", userEntity.getUname());
        map.put("userName", userEntity.getUname());
        return "success.jsp";
    }
    @RequestMapping("login4.do")
    public ModelAndView login4(@RequestParam("userName") String userName){
        // ModelAndView 数据和视图
        ModelAndView mv = new ModelAndView("success.jsp");
        mv.addObject("userName", userName);
        System.out.println("进行登陆业务4:"+userName);
        return mv;
    }

3 乱码处理

3.1 配置文件

 <!--设置默认的编码方式-->
    <filter>
        <filter-name>charsetEncoding</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>charsetEncoding</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>

4文件上传

4.1 配置文件

<bean  
     < class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
    <!-- 设置编码格式 -->
    <property name="defaultEncoding" value="utf-8"></property>
     <!-- 设置上传文件总大小,单位字节 -->
      <property name="maxUploadSize" value="20971520"></property>
</bean>

4.2 页面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <title>Title</title>
</head>
<body>
    <form action="register.do" enctype="multipart/form-data" method="post">
        <label>编号:<input name="uid" type="text"></label><br>
        <label>用户名:<input name="uname" type="text"></label><br>
        <label>密码:<input name="upass" type="text"></label><br>
        <label>头像:<input type="file" name="headImage"></label><br>
        <label><input type="submit" value="注册"></label>
    </form>
</body>
</html>

4.3 具体代码

public class RegisterController {
    @RequestMapping("register.do")
    public String register(MultipartFile headImage, HttpServletRequest request, UserEntity userEntity) throws Exception {
        // 构建保存路径
        String upload = request.getServletContext().getRealPath("/upload");
        File file = new File(upload);
        if (!file.exists()){
            file.mkdirs();
        }
        String name = upload + File.separator+ UUID.randomUUID().toString().replaceAll("-", "")+
                headImage.getOriginalFilename();
        // 构建输入流
        FileOutputStream fos = new FileOutputStream(name);
        // 构建输出流
        FileCopyUtils.copy(headImage.getInputStream(), fos);
        return "success.jsp";
    }
}

5 处理ajax请求

5.1 页面


<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
    <script src="https://cdn.bootcss.com/jquery/3.4.1/jquery.min.js"></script>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>Title</title>
</head>
<body>
    <button id="btn1">得到json字符串</button>
    <label id="msg1"></label>
    <br>
    <button id="btn2">得到实体对象</button>
    <label id="msg2"></label>
    <br>
    <button id="btn3">得到list集合</button>
    <label id="msg3"></label>
    <script type="text/javascript">
        $(function () {
            $("#btn1").click(function () {
                $.ajax({
                    url:"ajax1.do",
                    type: "post",
                    success: function (json) {
                        $("#msg1").html(json);
                    }
                });
            });
            $("#btn2").click(function () {
                $.ajax({
                    url:"ajax2.do",
                    type:"post",
                    success: function (data) {
                        $("#msg2").html(data.uname);
                    }
                });
            });
            $("#btn3").click(function () {
                $.ajax({
                    url:"ajax3.do",
                    type:"post",
                    success: function (data) {
                        $("#msg3").html(data[1].uname);
                    }
                });
            });
        });
    </script>
</body>
</html>

5.2 具体代码

package com.web;

import com.entity.UserEntity;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.ArrayList;
import java.util.List;

@Controller
public class AjaxController {
    @RequestMapping("ajax1.do")
    @ResponseBody   // springmvc处理ajax请求,需要加上这个注解
    public String ajax1(){
        // 处理普通的ajax请求,返回普通的json串
        String json = "{'name':'jack', 'age':'88'}";
        System.out.println(json);
        return json;
    }
    @RequestMapping("ajax2.do")
    @ResponseBody
    public UserEntity ajax2(){
        // 处理普通的ajax请求,返回的是一个的实体类对象
        UserEntity userEntity = new UserEntity();
        userEntity.setUid("1");
        userEntity.setUname("jack");
        userEntity.setUpass("123");
        return userEntity;
    }
    @RequestMapping("ajax3.do")
    @ResponseBody
    public List<UserEntity> ajax3(){
        List<UserEntity> list = new ArrayList<>();
        UserEntity userEntity = new UserEntity();
        userEntity.setUid("1");
        userEntity.setUname("jack");
        userEntity.setUpass("123");

        UserEntity userEntity1 = new UserEntity();
        userEntity1.setUid("2");
        userEntity1.setUname("rose");
        userEntity1.setUpass("999");
        list.add(userEntity);
        list.add(userEntity1);
        return list;
    }
}

6 拦截器

6.1 配置文件

<mvc:interceptors>
     <bean   class="com.intercept.MyIntercept"></bean>
</mvc:interceptors>

6.2 具体代码

package com.intercept;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class MyIntercept implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        System.out.println("执行请求之前"+request.getServletContext());
        if ("jack".equals(request.getParameter("userName"))){
            //当前请求被拦截了,不会执行目标方法了
            return false;
        }
        //当前请求不拦截
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        //就代表当前我们的请求处理完毕,只需要返回页面给用户了!!!
        System.out.println("返回视图之前");
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        //一般情况下,这个会释放一些资源
        System.out.println("返回视图之后");
    }
}

关注公众号【好便宜】( ID:haopianyi222 ),领红包啦~
阿里云,国内最大的云服务商,注册就送数千元优惠券:https://t.cn/AiQe5A0g
腾讯云,良心云,价格优惠: https://t.cn/AieHwwKl
搬瓦工,CN2 GIA 优质线路,搭梯子、海外建站推荐: https://t.cn/AieHwfX9
扫一扫关注公众号添加购物返利助手,领红包
Comments are closed.

推荐使用阿里云服务器

超多优惠券

服务器最低一折,一年不到100!

朕已阅去看看