普通的Maven项目转化为Maven Web项目
阅读原文时间:2021年04月20日阅读:1

建立项目前的准备工作和配置见(eclipse的基础设置和配置maven集成服务器等);

建立项目

首先建立一个普通的maven project,不要使用模板建立项目,然后填写组名和项目名称,注意的是,打包方式选择war,然后finish就完事了

修改配置,解决报错

可能会遇到“web.xml is missing and is set to true ”的错误:

右击项目,点击Java EE Tools,点击Genarate Deployment Descriptor Stub即可。意思是帮你找到或编写Web.xml文件

可能会遇到“The superclass "javax.servlet.http.HttpServlet" was not found on the Java Build Path   ”的错误:

右击项目,点击Build Path,选择configure build path,在右边Libraries页面,点击add Library ,然后选择Run Time,选择你配置的服务器,finish,最后记得apply。

可能会遇到你的jdk是1.8版本,但是项目却是1.5之类的,同样在Libraries页面,点击Jdk那个包,Eidt,然后选择你的jdk版本,记得apply

然后你需要修改配置Java Compiler。右击项目,选择Propertier,然后选择Java Compiler,在右边的页面修改版本。

可能会弹出下面的框,点击确认就行

还需要修改的是Project Facets。右击项目,选择Propertier,然后选择Project Facets,在右边的页面修改Dynamic Web  muddle,修改为3.0及以上,然后修改java为1.6以上。然后确认,apply。

测试一下

目录结构

FirstServlet.java:

package com;

import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/FirstServlet")
public class FirstServlet extends HttpServlet {
    private static final long serialVersionUID = 1L;

    public FirstServlet() {
        super();
    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.getSession().setAttribute("name", "xiaoxi");
        response.sendRedirect("second.jsp");
    }
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }

}

first.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<a href="FirstServlet">点击这个获取name属性值</a>
</body>
</html>

second.jsp

<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
name的属性值为:<%=request.getSession().getAttribute("name") %>
</body>
</html>

效果图