大三东软暑期实训-springmvc篇

  • springmvc导spring-webmvc,创建webapp骨架项目(部署到服务器)

在这里插入图片描述

  • 服务器不会加载springmvc,xml,服务器会加载web.xml,因此要把springmvc.xml导入到web.xml
<servlet>
		<servlet-name>springmvc</servlet-name>
		<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
		
		<!-- 指定springmvc的核心配置文件的位置 -->
		<init-param>
			<param-name>contextConfigLocation</param-name>
			<!--classpath表示类路径,表示resources目录-->
			<param-value>classpath:springmvc-config.xml</param-value>
		</init-param>
		
	</servlet>
	<servlet-mapping>
		<servlet-name>springmvc</servlet-name>
		
		<!-- 拦截所有请求 -->
		<url-pattern>/</url-pattern>
	</servlet-mapping>

  • 当服务器启动的时候,首先会去加载web.xml文件(可以理解问web应用程序的入口)
    凡是放在WEN-INF文件夹下面的资源都是受保护的,不能通过浏览器直接访问,可以通过转发或者重定向进行访问

  • servlet-api

  • 表单传参使用name的属性值作为参数传到服务器,表单服务器的参数名和表单的name属性值一致即可

  • 浏览器传入到服务器的参数都是String类型的,但是对于数字类型的字符串,在服务端可以使用Integer来接收。因为springmvc框架自动完成类型转换。

  • 数据的提交方式有get请求和post请求:
    区别:
    –get请求会将表单的数据暴露在浏览器的地址栏,对于重要的数据时不安全的。
    –post请求是将表单数据封装在请求行里面,数据比较安全
    –get请求提交的数据量比post的要小

  • session 和cookie的区别,有什么作用?
    记录用户状态(数据)
    session 将数据绑定在客户端,由session 绑定的数据可以实现数据共享:比如有很多个controller,在其中一个controller绑定数据,其他controller可以通过唯一key获取value
    cookie将数据保存在客户端(浏览器端)

  • 地址栏暴露参数
    解决方案:<form action="/doLogin" method="post">

  • 当表单的name属性值与实体类的属性值一致的时候,springmvc会将表单数据自动封装到实体类中,那么,可以在服务器端直接传入对象即可

  • 转发和重定向
    转发:httpServletRequest.getRequestDispatcher("要去的页面").forward(httpServletRequest,httpServletResponse);
    重定向:,httpServletResponse.sendRedirect();
    转发只能在项目内部进行,而重定向可以跳转到项目外部任意页面;转发是一次请求,重定向是两次请求

 @RequestMapping("/login")
    public String login(){
        return "login";//默认转发
    }
  @RequestMapping("/register")
    public String register(){
        return "redirect:register";//重定向
    }

转发地址栏的请求路径不会变,而重定向地址栏会发生改变
?后面加参数为get请求

  • 前端使用 参 数 名 得 到 的 仍 是 {参数名}得到的仍是 {参数名},引入<%@ page isELIgnored="false" %>
  • 在ssm框架中,处理中文乱码问题,在web.xml中配置由spring框架提供的过滤器
<!-- 编码过滤器,以UTF8编码 -->
  <filter>
    <filter-name>encodingFilter</filter-name>
    <filter-class>org.springframework.web.filter.CharacterEncodingFilter</filter-class>
    <init-param>
      <param-name>encoding</param-name>
      <param-value>UTF8</param-value>
    </init-param>
  </filter>
  <filter-mapping>
    <filter-name>encodingFilter</filter-name>
    <!--过滤所有请求-->
    <url-pattern>/*</url-pattern>
  </filter-mapping>
  • web.xml文件组件顺序:
    在这里插入图片描述
<!ELEMENT web-app (icon?, display-name?, description?, distributable?,
context-param*, filter*, filter-mapping*, listener*, servlet*,
servlet-mapping*, session-config?, mime-mapping*, welcome-file-list?,
error-page*, taglib*, resource-env-ref*, resource-ref*, security-constraint*,
login-config?, security-role*, env-entry*, ejb-ref*,  ejb-local-ref*)>
  • jsp使用el表达式乱码(接收参数出现乱码)
  • 首先保证项目的编码一致:
    在这里插入图片描述

1.get请求:
1.1.本地tomcat环境下jsp使用el表达式乱码之tomcat配置文件解决:

    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="utf-8"/>
    <!-- A "Connector" using the shared thread pool-->
    <Connector port="8080" protocol="HTTP/1.1"
               connectionTimeout="20000"
               redirectPort="8443" URIEncoding="utf-8"/>
    <!-- A "Connector" using the shared thread pool-->

1.2.maven项目tomcat插件解决方法:

<!--tomcat插件-->
<plugin>
    <groupId>org.apache.tomcat.maven</groupId>
    <artifactId>tomcat7-maven-plugin</artifactId>
    <configuration>
        <port>8080</port>
        <path>/</path>
        <uriEncoding>UTF-8</uriEncoding>
    </configuration>
</plugin>

2.post请求
web.xml

<!--post请求乱码过滤器-->
<filter>
    <filter-name>characterEncodingFilter</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>characterEncodingFilter</filter-name>
    <url-pattern>/*</url-pattern>
</filter-mapping>

3.控制台乱码:
程序中用System.out.println输出中文的时候显示乱码,但是前台的中文显示、数据库的中文、debug时变量中中文都正常,只有控制台中文乱码。

在maven启动中添加以下VM Options参数就可以解决控制台中文乱码:-Dfile.encoding=GB2312
在这里插入图片描述

 @RequestMapping("/t7")
    public void t7(HttpServletResponse response) throws IOException {
    //获取输出流
        PrintWriter writer = response.getWriter();
        //告诉浏览器输出内容
        response.setContentType("text/html;charset=utf-8");
        //写内容到浏览器
        writer.println("服务器正在忙,请稍后重试");
        writer.close();
    }

乱码解决:

@RequestMapping("/t7")
    public void t7(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("服务器正在忙,请稍后重试");
        writer.close();
    }
  • 服务端返回JSON数据给客户端
    获取某个对象firstName的值
    var a = i.employees;//获取数组
    var firstName = a[2].firstName;
{
"employees": [
{ "firstName":"Bill" , "lastName":"Gates" },
{ "firstName":"George" , "lastName":"Bush" },
{ "firstName":"Thomas" , "lastName":"Carter" }
]
}

json的使用:
导入依赖:json-databind

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.core/jackson-databind -->
<dependency>
    <groupId>com.fasterxml.jackson.core</groupId>
    <artifactId>jackson-databind</artifactId>
    <version>2.9.8</version>
</dependency>

@RequestMapping("/t8")
    @ResponseBody//将方法返回的数据转成Json字符串
        public User t8(){
            User user = new User();
            user.setUsername("李四");
            user.setPwd("123456");
            user.setTel("123");
            //“{“username":"李四","tel":"123456","pwd":"123"}”
            return user;
    }

之前demo

@RequestMapping("/t9")
    @ResponseBody//将方法返回的数据转成Json字符串
    public String t9(){
        return "123";
    }

失败是因为没有导入json依赖,springmvc会帮转,但“有气无力”。

  • springmvc异常处理
    机制:
    try{}catch(){}
    throws
    throw

当前controller处理异常的方法(局部处理异常):

//写一个方法,用来处理controller异常
    //@ExceptionHandler()要指定方法能够处理什么异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String,Object> doExcetion(Exception e){
        Map<String,Object> map = new HashMap<>();
        map.put("state",500);
        map.put("msg","服务器正忙,请稍后重试");
        return map;
    }

全局异常处理:
编写一个exception.ExceptionHandlerController类:
方法为:

//写一个方法,用来处理controller异常
    //@ExceptionHandler()要指定方法能够处理什么异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String,Object> doExcetion(Exception e){
        Map<String,Object> map = new HashMap<>();
        map.put("state",500);
        map.put("msg","服务器正忙,请稍后重试");
        return map;
    }

全局跳转失败可能是spring-webmvc依赖版本过低

  • 一些前后端交互Session,model,modelandview等等数据获取、封装并返回视图案例,附加json返回
 @RequestMapping("/test1")
    public void test1(String name , String age){
        System.out.print(name);
        System.out.print(age);
    }

    @RequestMapping("/test2")
    public void test2(HttpServletRequest httpServletRequest){
        String name = httpServletRequest.getParameter("name");
        Integer age = Integer.parseInt(httpServletRequest.getParameter("age"));
        System.out.print(name);
        System.out.print(age);
    }

    @RequestMapping("/login")
    public String login(){
        return "login";
    }

//    @RequestMapping("/doLogin")
//    public void doLogin(String username,Integer pwd){
//        System.out.println(username);
//        System.out.println(pwd);
//    }

    @RequestMapping("/doLogin")
    public void doLogin(HttpServletRequest httpServletRequest){
        String username = httpServletRequest.getParameter("username");
        String pwd = httpServletRequest.getParameter("pwd");
        System.out.print(username);
        System.out.print(pwd);

    }

    @RequestMapping("/register")
    public String register(){
        return "register";
    }

    @RequestMapping("/addUser")
    public void addUser( User user){
        System.out.println(user);
    }

    @RequestMapping("/toT1")
    public String toT1Page(){
        return "t1";
    }

    @RequestMapping("/toOrderData")
    public String toOrderData(String name, Model model){
       model.addAttribute("username",name);
       return "t2";
    }

    @RequestMapping("/t3")
    public String t3(HttpServletRequest request){
        request.setAttribute("salry",2000);
        request.setAttribute("username","黎明");
        return "t2";
    }

    @RequestMapping("/t4")
    public ModelAndView t4(ModelAndView modelAndView){
        modelAndView.addObject("age",20);
        modelAndView.addObject("username","黎明");
        modelAndView.setViewName("t2");
        return modelAndView;
    }

    @RequestMapping("/t5")
    public String t5(HttpServletRequest request){
        HttpSession session = request.getSession();
        session.setAttribute("heigth",180);
       return "t2";
    }

    /*@RequestMapping("/t5")
    public String t5(HttpSession session){
        session.setAttribute("heigth",180);
        return "t2";
    }*/

    @RequestMapping("/t6")
    public String t6(HttpServletRequest request){
        ServletContext servletContext = request.getServletContext();
        servletContext.setAttribute("weigth",120);
        return "t2";
    }

    @RequestMapping("/t7")
    public void t7(HttpServletResponse response) throws IOException {
        response.setContentType("text/html;charset=utf-8");
        PrintWriter writer = response.getWriter();
        writer.println("服务器正在忙,请稍后重试");
        writer.close();
    }

    @RequestMapping("/t8")
    @ResponseBody//将方法返回的数据转成Json字符串
        public User t8(){
            User user = new User();
            user.setUsername("李四");
            user.setPwd("123456");
            user.setTel("123");
            //“{“username":"李四","tel":"123456","pwd":"123"}”
            return user;
    }

    @RequestMapping("/t9")
    @ResponseBody//将方法返回的数据转成Json字符串
    public String t9(){
        return "123";
    }

    @RequestMapping("/t10")
    @ResponseBody
    public List<User> t10(){
        ArrayList list = new ArrayList();
        User user1 = new User();
        user1.setUsername("李四");
        user1.setPwd("123456");
        user1.setTel("123");

        User user2 = new User();
        user2.setUsername("郭德纲");
        user2.setPwd("6666");
        user2.setTel("5555");

        list.add(user1);
        list.add(user2);

        return list;
    }

    @RequestMapping("/t11")
    @ResponseBody
    public Map<String,Object> t11(){
        Map<String , Object> map = new HashMap<>();
        map.put("state",200);
        map.put("msg","手机验证码已发送");
        return map;
    }

    @GetMapping("/t12")
    public String t12(Model model){
        String str = null;
        str.toString();
        model.addAttribute("email","150@qq.com");
        return "t2";
    }

    /*//写一个方法,用来处理controller异常
    //@ExceptionHandler()要指定方法能够处理什么异常
    @ExceptionHandler(Exception.class)
    @ResponseBody
    public Map<String,Object> doExcetion(Exception e){
        Map<String,Object> map = new HashMap<>();
        map.put("state",500);
//        map.put("msg","服务器正忙,请稍后重试");
        map.put("msg",e.getMessage());
        return map;
    }*/
  • 日期类型2017/06/08就正确,怎么2017-06-08就出错了呢?400错误,参数类型不匹配错误。springmvc默认日期格式用斜杠隔开。
    使用@InitBinder注解,指定自定义的日期转换格式
@InitBinder	//日期转换设定
	public void InitBinder (ServletRequestDataBinder binder){
		binder.registerCustomEditor(
		java.util.Date.class, 
		new CustomDateEditor(new SimpleDateFormat("yyyy-MM-dd"), true));
	}

测试:
http://localhost:8060/add?id=10&name=tony&birthday=2018-10-11

  • ModelAndView的使用,使用ModelAndView的时候controller一定要返回ModelAndView,不能返回字符串,否则ModelAndView绑定的属性在前端使用el表达式获取不到,要不怎么会有 modelAndView.setViewName("");这个方法呢,同时传参也需要 ModelAndView。如果只用Model可以返回字符串。
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Fire king

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值