目录
实验目的
掌握SpringMVC的配置(三大件)以及一般开发流程;掌握Spring MVC的常用注解;理解Spring MVC 与Spring的整合方式。
实验内容
(1) 配置applicationContext.xml以及web.xml文件,进行Spring MVC和Spring的相关设置;
(2) 引入SpringMVC 重构Spring、SpringJDBCTemplate的内容。
实验步骤
配置applicationContext.xml:
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<context:property-placeholder location="classpath:/db.properties"/>
<!--1. 配置数据源-->
<!-- <bean id="driverManagerDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">-->
<bean id="dbcpDataSource" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
<property name="driverClassName" value="${mysql.driver}"/>
<property name="url" value="${mysql.url}"/>
<property name="username" value="${mysql.userName}"/>
<property name="password" value="${mysql.password}"/>
</bean>
<!--2.配置jdbc模板-->
<bean id="jdbcTemplateDBCP" class="org.springframework.jdbc.core.JdbcTemplate">
<property name="dataSource" ref="dbcpDataSource"/>
</bean>
<bean id="userDAO" class="com.txq.bmms.dao.impl.UserDaoImpl">
<property name="jdbcTemplate" ref="jdbcTemplateDBCP"/>
</bean>
<!--4.配置Service-->
<bean id="userService" class="com.txq.bmms.service.impl.UserServiceImpl">
<property name="userDao" ref="userDAO"/>
</bean>
<import resource="springmvc_servlet.xml"/>
</beans>
配置web.xml:
<!DOCTYPE web-app PUBLIC
"-//Sun Microsystems, Inc.//DTD Web Application 2.3//EN"
"http://java.sun.com/dtd/web-app_2_3.dtd" >
<web-app xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_4_0.xsd"
version="4.0">
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:applicationContext.xml</param-value>
</context-param>
<filter>
<filter-name>characterEncodingFilter</filter-name>
<filter-class>com.txq.bmms.filter.CharacterEncodingFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>characterEncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>springmvc</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:springmvc_servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>springmvc</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
导入spring MVC依赖:
<!--spring web mvc-->
<!-- https://mvnrepository.com/artifact/org.springframework/spring-webmvc -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>5.1.4.RELEASE</version>
</dependency>
新建spring MVC配置文件springmvc_servlet.xml,并配置处理映射器,处理适配器,处理解析器。
<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:context="http://www.springframework.org/schema/context"
xmlns:mvc="http://www.springframework.org/schema/mvc"
xsi:schemaLocation="http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/mvc
http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context.xsd">
<!--1 mvc 注解驱动-->
<mvc:annotation-driven/>
<!--2 静态资源过滤-->
<mvc:default-servlet-handler/>
<!--3 指定注解扫描的位置-->
<context:component-scan base-package="com.txq.bmms.controller"/>
<!--配置处理映射器-->
<bean class="org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping"/>
<!--配置处理适配器-->
<bean class="org.springframework.web.servlet.mvc.SimpleControllerHandlerAdapter"/>
<!--配置视图解析器-->
<bean class="org.springframework.web.servlet.view.InternalResourceViewResolver" id="internalResourceViewResolver">
<property name="prefix" value="/WEB-INF/jsp/"/>
<property name="suffix" value=".jsp"/>
</bean>
<!-- <!–配置后端控制器–>-->
<bean id="/sayHello" class="com.txq.bmms.controller.HelloController"/>
</beans>
编写HelloController,实现Controller接口
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" %>
<html>
<head>
<title>Title</title>
</head>
<body>
${msg}
</body>
</html>
<!-- <!–配置后端控制器–>-->
<bean id="/sayHello" class="com.txq.bmms.controller.HelloController"/>
利用login跳转到HelloController:
成功:
DispatcherServlet把用户的请求转发给处理类中的Handler,Handler对用户的请求进行处理。传统的处理器类需要实现Controller接口,再去配置文件中进行配置。
现在@Controller标注在普通类上,通过Spring的扫描机制找到标注了该注解的java类,就称为了处理器类。
注意:需要告诉Spring,扫描注解的位置。
<!-- 指定注解扫描的位置-->
<context:component-scan base-package="com.yy.bmms.controller"/>
其中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提供必要的映射信息,建立请求URL和Handler之间的映射关系。该注解以标注在类上或方法上。
注意,此时需要在Spring的配置文件中配置处理器映射器和处理器适配器。
<!--1 mvc 注解驱动, 将配置默认的注解处理器和注解适配器-->
<mvc:annotation-driven/>
@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
}
}
}
修改登录成功的主页代码:
<form action="${pageContext.request.contextPath}/testWithViewS">
<input type="hidden" name="way" value="forward1">
<button type="submit">增加信息</button>
</form>
<form action="${pageContext.request.contextPath}/testWithViewS">
<input type="hidden" name="way" value="forward2">
<button type="submit">修改信息</button>
</form>
<form action="${pageContext.request.contextPath}/testWithViewS">
<input type="hidden" name="way" value="forward3">
<button type="submit">删除信息</button>
</form>
<form action="${pageContext.request.contextPath}/testWithViewS">
<input type="hidden" name="way" value="forward4">
<button type="submit">查看信息</button>
</form>
测试:
登录成功主页:
增加信息:
修改信息:
其他操作类似就不一一展示了。
实验总结
实验中遇到的问题及解决办法
遇到问题:
解决方法:
再创建一个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文档以及相关的在线教程,这些资料对我理解框架的使用和配置方式起到了关键作用。