IntelliJ IDEA 15 部署 Tomcat 及创建一个简单的Web工程
1. 新建 Java EE 工程
默认勾选了 Create web.xml
工程目录下比一般的 Java 项目多了 web 文件夹
2. 添加 Tomcat 服务器
3. 添加 Tomcat Module
Project Structure -> Modules -> 添加 Library
选择第 2 步添加的 Tomcat
选中之后 Apply
4. 配置本地 Tomcat 服务器
设置 Deployment 目录
设置 Server 属性
5. 运行测试
链接:http://localhost:8089/web/
默认显示的是 index.jsp 的内容
6. Servlet 测试
src 下新建 Servlet,设置 类名,包名
FirstServlet.java
package com.shuai.web;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
/**
* Created by shuai
* on 2017/8/20.
*/
@WebServlet(name = "FirstServlet", urlPatterns = {"/first"})
public class FirstServlet extends HttpServlet {
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
}
}
注意一定要设置 urlPatterns 告诉浏览器哪个路径可以到这个 Servlet
@WebServlet(name = "FirstServlet", urlPatterns = {"/first"}) // “/” 必须有
通过下面这个链接访问 FirstServlet
http://localhost:8089/web/first
Get 方法 获取地址栏参数
doGet 方法
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("UTF-8"); // 防止乱码
System.out.println(request.getParameter("name")); // 地址栏 name 参数的值
}
访问链接
http://localhost:8089/web/first?name=tom
命令行输出
tom
POST 方法 获取表单数据
index.jsp body 标签中添加 Form
<!--添加Form-->
<form action="first" method="post">
用户名: <input type="text" name="name"><br>
密码: <input type="password" name="password"><br>
<input type="submit" value="提交">
</form>
doPost 方法
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
命令行输出
谢帅
GET vs POST
- post 安全,隐式传参数
- get 会在地址栏添加上参数和内容