SpringMVC#(二)

Controll的应用

使用注解开发Controller的细节解释:
1.用注解@Controller修饰自定义的类,则表示此类用于处理请求
2.具体处理url请求的是Controller类中的方法
3.通过注解可以修改此方法接收什么请求:
用@RequsetMapping(url)修饰,两种都能接收
用@PostMapping(url)修饰,仅仅接收Post方法
用@GetMapping(url)修饰,仅仅接收Get方法
4.此方法的参数可以有Model model数据模型
5.在此方法中处理这个请求后,一般通过return一个字符串,来进行跳转前端页面来显示新的数据模型
6.如果在return后面添加关键词符,比如return “redirect:/index.jsp”;那么就会修改当前url重定向到index.jsp的前端页面中,同理return “forward:/index.jsp”;会转发
7.过滤器可以通过aop方式插入到其中,比如字符过滤器

重点应用的实现:
一.重定向与转发

@Controller
public class ModelTest1 {
    @RequestMapping("/hello")
    public String hello(HttpServletRequest request, HttpServletResponse response){

        HttpSession session = request.getSession();
        System.out.println(session.getId());
        //在配置过视图解析器时重定向:在要重定向的路径前加一个redirect:/,如下:
        return "redirect:/index.jsp";
    }
    @RequestMapping("/Repass")
    public String Repass(){
        //在配置过视图解析器时转发:在要转发的路径前加一个forward:/,如下:
        return "forward:/index.jsp";
    }
}

二.过滤器
实现springMVC提供的过滤器
字符过滤器的实现

public class EncodingFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {

    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        servletRequest.setCharacterEncoding("utf-8");
        servletResponse.setCharacterEncoding("utf-8");

        filterChain.doFilter(servletRequest,servletResponse);
    }

    @Override
    public void destroy() {

    }
}

三.参数传递问题
1.前端传递的参数是普通参数
直接在url后面添加参数名及其参数值
2.可以修改传递的参数名
通过用注解@RequsetParam(“xxx”)来修饰方法中的参数,那么只能通过xxx来传递参数了
3.传递的参数是个对象
自己将对象的成员名和值传入即可,连接通过&

@Controller
@RequestMapping("/user")
public class UserController {
    @GetMapping("/t1")
    public String test1(@RequestParam("username") String name, Model model){
        //1.接收前端参数(用@RequestParam("传参名")修饰)
        System.out.println("接收前端参数:"+name);
        //2.返回结果给前端
        model.addAttribute("msg",name);
        //3.视图跳转
        return "hello";
    }

    @GetMapping("/t2")
    public String test2(User user, Model model){
        //1.接收前端参数,参数类型是对象时,直接用对象的属性进行传参
        System.out.println("接收前端参数:"+user);
        model.addAttribute("msg",user.getName());
        return "hello";
    }
    @GetMapping("/t3")
    public String test3(String name,ModelMap map){
		model.addAttribute("msg",name);
        return "hello";
    }
}

四.RestFul风格问题
1.在参数前面修饰@PathVariable(“参数名”)注解
2.在映射路径那里添加参数,如下

@GetMapping("/t3/{name}")
    public String test3(@PathVariable("name") String name, ModelMap map){
        map.addAttribute("msg",name);
        return "hello";
    }

此时传参的url不用写参数name了

五.json问题
将获得的数据修改为json格式,方便前端使用
第一步:导入将对象转换为json格式的包

        <dependency>
            <groupId>com.fasterxml.jackson.core</groupId>
            <artifactId>jackson-databind</artifactId>
            <version>2.10.0</version>
        </dependency>

第二步:将转化成json格式的API打包成工具类

public class JSONUtils {

    public static String getDateByJson() throws JsonProcessingException {
        return getJson(new Object());
    }

    public static String getJson(Object object) throws JsonProcessingException {
        Date date = new Date();
        return getJson(date,"yyyy-MM-dd HH:mm:ss");
    }

    public static String getJson(Object object,String dateFormat) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        mapper.configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS,false);
        SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
        mapper.setDateFormat(sdf);
        return mapper.writeValueAsString(object);
    }

    public static String getObjectByJson(Object object) throws JsonProcessingException {
        ObjectMapper mapper = new ObjectMapper();
        return mapper.writeValueAsString(object);
    }
}

第三步:将后端的对象数据改为JSON格式传递到前端

@Controller
public class UserController {
    @RequestMapping("/j1")
    @ResponseBody//不会去走视图解析器,直接返回字符串
    public String json1() throws JsonProcessingException {
        //用jackson的ObjetMapper()方法
        ArrayList<User> users = new ArrayList<>();
        for (int i = 0; i < 7; i++) {
            User user = new User(1, "中a", 18);
            users.add(user);
        }
        return JSONutils.getObjectByJson(users);
    }

    @RequestMapping("/j2")
    @ResponseBody//不会去走视图解析器,直接返回字符串
    public String json2() throws JsonProcessingException {
       return JSONutils.getDateByJson();
    }
}

六.与前端接轨,传递数据的方法Ajax
前端通过ajax能够访问到后端提供的数据,大体思路是
1.前端的某某事件触发写好的对应的ajax方法
2.ajax就去访问后端的数据,并且把数据报装在data中
3.ajax的到数据后,通过回调函数对数据进行处理,呈现在前端页面上

举例:
后端:

    @RequestMapping("/a2")
    @ResponseBody
    public List<User> a2(){
        ArrayList<User> userList = new ArrayList<>();

        userList.add(new User("aaa",1,"男女"));
        userList.add(new User("bbb",1,"男女"));
        userList.add(new User("ccc",1,"男女"));

        return userList;
    }

前端:

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html lang="en">
<head>
    <title>数据展示</title>
</head>
<body>

<input type="button" id="btn" value="获取数据">
<table style="width: 80%;align-content: center">
  <tr>
    <td>姓名1</td>
    <td>年龄</td>
    <td>性别</td>
  </tr>
  <tbody id="content">

  </tbody>
</table>
<script src="${pageContext.request.contextPath}/statics/js/jquery-3.6.0.js"></script>
<%--在jsp文件中单独自闭合没有效果,会报错--%>
<script>
    let btn = document.getElementById('btn');
    console.log("aaa");
    btn.onclick = function (){
        console.log("bbb");
        //ajax的另外的参数写法
        $.post("${pageContext.request.contextPath}/a2",function (data){
            console.log(data);
            let html = "";
            for (let i = 0; i < data.length; i++) {
                html += "<tr>"+
                    "<td>"+data[i].name+"</td>"+
                    "<td>"+data[i].age+"</td>"+
                    "<td>"+data[i].sex+"</td>"+
                +"</tr>";
            }
            $("#content").html(html);
        })
    }
</script>

</body>
</html>

七.拦截器应用
要保证不是所有人都能访问网站,所以添加拦截器
举例:登录拦截器
第一步:DispathcherServlet.xml配置文件中添加拦截器配置

<!--    拦截器配置-->
    <mvc:interceptors>
        <mvc:interceptor>
<!--            包括此请求下所有请求-->
            <mvc:mapping path="/**"/>
            <bean class="com.cs.config.MyInterceptor"/>
        </mvc:interceptor>
        <mvc:interceptor>
            <!--            包括此请求下所有请求-->
            <mvc:mapping path="/user/**"/>
            <bean class="com.cs.config.LoginInterceptor"/>
        </mvc:interceptor>
    </mvc:interceptors>

第二步:编写登录拦截器类,控制请求不被拦截

public class LoginInterceptor implements HandlerInterceptor {
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        //什么情况下放行
        HttpSession session = request.getSession();
        //1.登录后
        if(session.getAttribute("userLoginInfo")!= null){
            return true;
        }
        //2.去登录页面
        if(request.getRequestURI().contains("login")){
            return true;
        }
        if(request.getRequestURI().contains("goLogin")){
            return true;
        }
        //没有登录的重定向
        request.getRequestDispatcher("/WEB-INF/jsp/login.jsp").forward(request,response);
        //return HandlerInterceptor.super.preHandle(request, response, handler);
        return false;
    }
}

八.文件上传应用实现

    @RequestMapping("/upload")
    public String upload(@RequestParam("file") CommonsMultipartFile file, HttpServletRequest request) throws IOException {
        String uploadFileName = file.getOriginalFilename();
        if("".equals(uploadFileName)){
            return "redirect:/index.jsp";
        }
        System.out.println("上传文件名:"+ uploadFileName);

        String path = request.getServletContext().getRealPath("/upload");
        File realPath = new File(path);
        if(!realPath.exists()){
            realPath.mkdir();
        }
        System.out.println("文件保存在服务器地址"+realPath);

        InputStream is = file.getInputStream();
        OutputStream os = new FileOutputStream(new File(realPath, uploadFileName));

        int len=0;
        byte[] buffer = new byte[1024];
        while ((len=is.read(buffer))!=-1){
            os.write(buffer,0,len);
            os.flush();
        }
        os.close();
        is.close();
        return "redirect:/index.jsp";
    }

<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>$Title$</title>
  </head>
  <body>
  $END$
  <form action="${pageContext.request.contextPath}/upload" enctype="multipart/form-data" method="post">
    <input type="file" name="file"/>
    <input type="submit" value="upload"/>
  </form>
  </body>
</html>

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值