栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Java

SpringMVC注解(二)

Java 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

SpringMVC注解(二)

1.SpringMVC的注解开发

1)一个注解的列子

(1)注解需要的依赖包

    
      org.springframework
      spring-webmvc
      5.1.5.RELEASE
    
    
    
    
      javax.servlet
      javax.servlet-api
      3.0.1
      provided
    
    
    
    
      javax.servlet.jsp
      javax.servlet.jsp-api
      2.2.1
      provided
    
    
    
    
      javax.servlet
      jstl
      1.2
    

(2)在web.xml文件中配置中央控制器


    dispatcherServle
    org.springframework.web.servlet.DispatcherServlet
    
    
      contextConfigLocation
      classpath:springmvc.xml
    
  
  
    dispatcherServle
    /
  

(3)在resources下创建springmvc的配置文件



    
    
    
    
    
    
        
    
    

(4) 创建控制类和请求处理方法

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;
import javax.servlet.http.HttpServletRequest;
@Controller
public class HelloController {
    @RequestMapping("/hello")
    public ModelAndView  helloReq(HttpServletRequest req){
        String username=req.getParameter("username");
        ModelAndView mav=new ModelAndView();
        mav.addObject("myname",username);
        mav.setViewName("test.jsp");
        return mav;
    }
}

(5)创建test.jsp

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


    Title


    测试基于注解的SpringMVC程序====${myname}

(6)配置服务器运行测试

2.SpringMVC的注解开发 @Controller注解:表示我们所编写的java类是一个处理请求的控制器类。

只能作用在java类
        可以使用@Component去代替,在javaweb程序中是分层出来的为了表名
        @Controller中包含有@Component。

@Controller与我们在spring中学习的@Service和@Repository将应用程序标记为不同的层。
    数据访问层:@Repository
    业务访问层:@Service
    Web层【控制层】:@Controller

@RequestMapping---设置请求处理类/请求处理方法的访问路径
             位置:请求处理类:设置类的访问路径
             请求处理方法:设置请求处理方法的访问路径

1)设置路径(value="路径")可以省略value
@Controller

public class TestController {
    @RequestMapping("/testreq")
    public  void  testReq(){
        System.out.println("处理用户请求");
    }
}

测试链接地址: http://localhost:8080/demo/one

服务器响应结果:

 (1)?匹配任何单字符

设置注解

@RequestMapping("/?testreq")

链接地址:
http://localhost:8080/demo3/test/testreq [错误]
http://localhost:8080/demo3/test/Atestreq 【正确】

(2)** :匹配多个路径

设置注解

@RequestMapping("testreq")

链接地址:
http://localhost:8080/demo3/test/testreq【正确】
http://localhost:8080/demo3/test/hello/testreq【正确】
http://localhost:8080/demo3/test/hello/abc/testreq【正确】

2)method限制请求方式

如果什么都不写那么就可以通过任何方式进行访问。

设置为get请求

java代码

测试链接地址: http://localhost:8080/demo/two

服务器响应结果:

设置为post请求

@RequestMapping(value = "/two",method = RequestMethod.POST)

页面结果:服务器不会响应

 

无奈源于不够强大

 

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/759595.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号