Spring MVC应用

目录

实验目的

实验内容

实验步骤

测试:

实验总结

实验中遇到的问题及解决办法

总结


实验目的

掌握SpringMVC的配置(三大件)以及一般开发流程;掌握Spring MVC的常用注解;理解Spring MVC 与Spring的整合方式。

实验内容

(1) 配置applicationContext.xml以及web.xml文件,进行Spring MVC和Spring的相关设置;

(2) 引入SpringMVC 重构Spring、SpringJDBCTemplate的内容

实验步骤

配置applicationContext.xml



    
    
    
    
        
        
        
        
    

    
    
        
    

    
        
    

    
    
        
    
    



配置web.xml:





  Archetype Created Web Application

  
    contextConfigLocation
    classpath:applicationContext.xml
  
  
    characterEncodingFilter
    com.txq.bmms.filter.CharacterEncodingFilter
  
  
    characterEncodingFilter
    /*
  
  
    org.springframework.web.context.ContextLoaderListener
  

  
    springmvc
    org.springframework.web.servlet.DispatcherServlet
    
      contextConfigLocation
      classpath:springmvc_servlet.xml
    
    1
  

  
    springmvc
    /
  



导入spring MVC依赖:


        
        
            org.springframework
            spring-webmvc
            5.1.4.RELEASE
        

新建spring MVC配置文件springmvc_servlet.xml,并配置处理映射器,处理适配器,处理解析器。



    
    
    
    
    
    
    
    
    
    
    
    
        
        
    
    
       


编写HelloController,实现Controller接口

Spring MVC应用_第1张图片

package com.txq.bmms.controller;

import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.mvc.Controller;

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

public class HelloController implements Controller {
    @Override
    public ModelAndView handleRequest(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) {
        ModelAndView mv = new ModelAndView();
        mv.setViewName("hello");
        mv.addObject("msg","Welcome to springmvc");
        return mv;

    }
}

web目录的web-inf下新建一个jsp目录,在jsp目录中建立一个hello.jsp文件:

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


    Title


${msg}





   

利用login跳转到HelloController:

成功:

Spring MVC应用_第2张图片

DispatcherServlet把用户的请求转发给处理类中的HandlerHandler对用户的请求进行处理。传统的处理器类需要实现Controller接口,再去配置文件中进行配置。

现在@Controller标注在普通类上,通过Spring的扫描机制找到标注了该注解的java类,就称为了处理器类。

注意:需要告诉Spring,扫描注解的位置。


  

其中context声明空间中的component-scan标签的base-pachage属性指明了需要扫描的包及其子包下的java类。

Spring启动后,会在context:component-scan 的属性base-package指定的目录下扫描;如果被扫描的Java类中带有@Controller@Service@Repository@Component等注解,把这些类注册为Bean,并放在Spring工厂中。(注意@Service@Repository@Component 注解后面会讲到)

 @RequestMapping:

使用@Controller 注解可以将普通的类声明成Spring MVC的处理器,但是Spring MVC框架此时并不能确定当前Web请求由哪个Handler进行处理。

@RequestMapping可以为Handler提供必要的映射信息,建立请求URLHandler之间的映射关系。该注解以标注在类上或方法上。

注意,此时需要在Spring的配置文件中配置处理器映射器和处理器适配器。

  
  

@RequestMapping 这个注解标注的位置有两个:

引入SpringMVC 重构上次实验的内容:

重构后的UserController
@Controller

public class UserController {

    @RequestMapping("/userController")
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // req.setCharacterEncoding("utf-8");
        // resp.setCharacterEncoding("utf-8");
        String method = req.getParameter("method");
        switch (method){

            case  "add": insertUser(req,resp);break;
            case  "delete":deleteUser(resp,req);break;
            case  "alter":updateUser(req,resp);break;
            case  "show":queryUser(req,resp);break;
            default: resp.sendRedirect(req.getContextPath() +"/error.jsp");

        }

    }

    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        this.doGet(req, resp);
    }


    private  void insertUser(HttpServletRequest request,HttpServletResponse response){
        User user =new User();
        user.setAccount(request.getParameter("account"));
        user.setBalance(Double.parseDouble(request.getParameter("balance")));
        user.setPassword(request.getParameter("password"));

        ApplicationContext acx = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) acx.getBean("userService");

        userService.insertUser(user);



    }
    private void deleteUser(HttpServletResponse response,HttpServletRequest request){
       int id = Integer.parseInt(request.getParameter("id"));

        ApplicationContext acx = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) acx.getBean("userService");
       userService.deleteUser(id);
    }
    private void updateUser(HttpServletRequest request,HttpServletResponse response){
        User user =new User();
        user.setAccount(request.getParameter("account"));
        user.setBalance(Double.parseDouble(request.getParameter("balance")));
        user.setPassword(request.getParameter("password"));
        user.setId(Integer.parseInt(request.getParameter("id")));

        ApplicationContext acx = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) acx.getBean("userService");
        userService.updateUser(user.getAccount(),user.getBalance(),user.getPassword(),user.getId());

    }
    private void queryUser(HttpServletRequest request,HttpServletResponse response){
        int id = Integer.parseInt(request.getParameter("id"));

        ApplicationContext acx = new ClassPathXmlApplicationContext("applicationContext.xml");
        UserService userService = (UserService) acx.getBean("userService");
        userService.queryUser(id);
        try {
            request.getRequestDispatcher("/result.jsp").forward(request,response);
        } catch (ServletException e) {
            throw new RuntimeException(e);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }
}
将jsp文件放到WEB-INF中的jsp目录中,由于WEB-INF目录下的jsp文件无法直接访问,不能使用重定向,需要使用转发。所以我创建了一个process过程用来转接login到WEB-INF中的jsp具体操作如下:
@Controller
public class Process {

    @RequestMapping("/testWithViewS")
    public String test2(String way) {
        switch (way) {
            case "forward1":
                return "forward:/WEB-INF/jsp/add.jsp";
            case "forward2":
                return "forward:/WEB-INF/jsp/alter.jsp";
            case "forward3":
                return "forward:/WEB-INF/jsp/delete.jsp"; //forward是发给tomcat服务器,解析"/"为当前应用"主机ip:8080/smvc"

            case "forward4":
                return "redirect:/WEB-INF/jsp/show.jsp";

            default:
                return null;//与无返回值时效果一样,解析成请求资源地址/WEB-INF/jsp/testWithViewS.jsp
        }
    }


}
修改登录成功的主页代码:

测试:

登录成功主页:

Spring MVC应用_第3张图片

增加信息:

Spring MVC应用_第4张图片

Spring MVC应用_第5张图片

修改信息:

Spring MVC应用_第6张图片

Spring MVC应用_第7张图片

其他操作类似就不一一展示了。

实验总结

实验中遇到的问题及解决办法

遇到问题:

Spring MVC应用_第8张图片

解决方法:

Spring MVC应用_第9张图片

再创建一个process的servlet来接受WEB-INF中的资源跳转。

总结

本次实验旨在学习Spring MVC和Spring框架的配置以及进行代码重构的过程。主要包括了对Spring MVC的配置、注解方式的请求映射、以及代码重构的步骤。

在实验中,首先进行了配置文件的编辑,包括ApplicationContext.xml和web.xml,确保Spring容器和Spring MVC能够正确初始化。在配置文件中进行了包扫描、数据源配置和事务管理的设置,为后续的项目搭建奠定基础。

随后,进行了代码重构的工作,将之前使用的Spring和SpringJDBCTemplate的相关配置和代码移植到新的Spring MVC项目中。这一步骤的目的是保留之前功能的同时,使之适应新项目的结构和特性。

接着,编写了一个简单的Controller类,利用注解方式进行请求映射。这一步骤验证了项目的配置是否正确,确保了请求的正确路由和相应视图的返回。

实验结果表明,通过正确配置和代码重构,成功搭建了一个基本的Spring MVC项目。之前的功能得以继承,同时利用了Spring MVC的新特性来更好地组织代码结构。通过Controller的定义,能够成功处理Web请求,并在视图中呈现数据。

总体而言,这次实验让我更深入地了解了Spring MVC和Spring框架的配置和使用,提升了我的问题解决能力。通过实际操作,我对框架的理解更加深刻,为今后的项目开发打下了坚实的基础。在实验过程中,参考了Spring官方文档、Spring MVC文档以及相关的在线教程,这些资料对我理解框架的使用和配置方式起到了关键作用。

你可能感兴趣的:(spring,mvc,java)