(八)Spring与Web

   在Web项目中使用Spring框架,实际上是在Web层获取Spring容器,便可从容器中获取到Service对象。为了简便起见,基于上个项目来构建我们的Web项目:

1、创建Web项目

  • 选择Web Application项目:
  • 在 WEB-INF 目录下,创建 classes(用于存放编译的字节码文件) 和 lib(用于存放引用的jar包) 两个目录:
  • 将项目输出路径改为之前创建的 classes 路径:
  • 添加项目依赖路径:
  • 配置打包方式Artifacts:勾选“Build on make”,表示编译的时候就打包部署;勾选“Show content of elements”,表示显示详细的内容列表;
  • 新建Tomcat Server:
  • 配置Tomcat Server:

   取消勾选“After launch”,表示取消自动打开浏览器。

   添加部署到Tomcat的项目,设置url路径:

  • 修改index.jsp文件:
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
  <head>
    <title>hello world</title>
  </head>
  <body>
  hello world
  </body>
</html>
  • 打开浏览器,测试网页是否正确运行(注意url路径需与上面设的一致):

2、导入jar包、源代码

  • 导入上个项目((七)Spring集成MyBatis)的jar包、源码
  • 需要额外导入Tomcat目录下的 servlet-api.jar 包,spring的 spring-web-5.1.9.RELEASE.jar,以及jsp中会用到的 jstl.jar 、standard.jar

3、编写Web项目代码

  • 目录结构
  • index.jsp,作为添加Student表数据的初始网页:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<html>
  <head>
    <title>index</title>
  </head>
  <body>
  <div align="center">
    <form action="register" method="post">
      姓名:<input name="name" type="text"/><br/>
      年龄:<input name="age" type="text"><br/>
      <input type="submit" value="提交" />
    </form>
  </div>
  </body>
</html>
  • result.jsp,作为展示Student表数据的网页:
<%@ page contentType="text/html;charset=UTF-8" language="java" isELIgnored="false"%>
<%@ taglib uri="http://java.sun.com/jsp/jstl/core" prefix="c"%>
<html>
<head>
    <title>result</title>
</head>
<body>
<br/>
<table align="center" border="1" cellpadding="5" cellspacing="0" style="text-align: center">
    <caption style="font-size: x-large"><strong>Student表数据</strong></caption>
    <tr><td>姓名</td><td>年龄</td></tr>
    <c:forEach var="students" items="${students}">
        <tr>
            <td>${students.name}</td><td>${students.age}</td>
        </tr>
    </c:forEach>
</table>
</body>
</html>
  • RegisterServlet.java,在Servlet获取spring容器对象(WebApplicationContext 继承于ApplicationContext类),处理表数据:
public class RegisterServlet extends HttpServlet{

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html;charset=utf-8");
        String strName = req.getParameter("name");
        String age = req.getParameter("age");

        // 使用框架提供的方法,获取容器对象
        WebApplicationContext ctx = WebApplicationContextUtils.getRequiredWebApplicationContext(getServletContext());

        StudentService service = (StudentService)ctx.getBean("studentService");
        Student student = new Student();student.setName(strName);student.setAge(Integer.parseInt(age));
        service.addStudent(student);

        List<Student> students = service.queryStudent();
        req.setAttribute("students", students);

        // 跳转到结果页面
        req.getRequestDispatcher("/result.jsp").forward(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
  • 在WEB-INF目录下的web.xml,配置Servlet、注册监听器:
<?xml version="1.0" encoding="UTF-8"?>
<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_3_1.xsd"
         version="3.1">
    
    <servlet>
        <servlet-name>RegisterServlet</servlet-name>
        <servlet-class>com.lyj.servlet.RegisterServlet</servlet-class>
    </servlet>
    <servlet-mapping>
        <servlet-name>RegisterServlet</servlet-name>
        <url-pattern>/register</url-pattern>
    </servlet-mapping>

    <!--
        注册监听器:会先创建spring的容器对象,再把容器对象放入到ServletContext,供Servlet调用。
        监视器启动时,默认会到WEB-INF路径下找applicationContext.xml配置文件。
    -->
    <!-- 也可以指定配置文件路径 -->
    <context-param>
        <param-name>contextConfigLocation</param-name>
        <param-value>classpath:com/lyj/applicationContext.xml</param-value>
    </context-param>
    <listener>
        <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
    </listener>
</web-app>
  • 运行测试:
  • 结果页面:
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值