servlet
- 1.创建空项目
- 2.配置web项目
- 3.配置Tomcat
- 4.加载Tomcat包
- 5.创建HelloWorldServlet类
- 6.配置web.xml
- 7.运行
- get与post请求
1.创建空项目
2.配置web项目
3.配置Tomcat
4.加载Tomcat包
5.创建HelloWorldServlet类
public class controller extends HttpServlet {@Override//get请求protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//页面显示servletresp.getWriter().println("servlet");}@Override//post请求protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {}
}
6.配置web.xml
<?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_4_0.xsd"version="4.0"><servlet>
<!-- java类路径别名--><servlet-name>hello</servlet-name>
<!-- 引入java类--><servlet-class>com.lx.controller</servlet-class></servlet><servlet-mapping>
<!-- 使用别名--><servlet-name>hello</servlet-name>
<!-- 浏览器资源路径--><url-pattern>/hello</url-pattern></servlet-mapping>
</web-app>
7.运行
get与post请求
<!-- /servletWebDemo:是配置Tomcat中指定的地址-->
<!-- /login:是web.xml中的<url-pattern>/login</url-pattern>--><form action="/servletWebDemo/login" method="get"><label>用户名:</label><input type="text" name="userName"><br><br><label>密码:</label><input type="password" name="passWord"><br><br><button type="submit">提交</button></form>
public class controller extends HttpServlet {@Overrideprotected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {//设置请求中文字符req.setCharacterEncoding("utf-8");//设置响应中文字符resp.setContentType("text/html;charset=utf-8");String userName = req.getParameter("userName");String passWord = req.getParameter("passWord");resp.getWriter().println(userName);resp.getWriter().println();resp.getWriter().println(passWord);}@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {doGet(req,resp);}
}