servlet
1.创建空项目
2.配置web项目
3.配置Tomcat
4.加载Tomcat包
5.创建HelloWorldServlet类
java
public class controller extends HttpServlet {
@Override
//get请求
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//页面显示servlet
resp.getWriter().println("servlet");
}
@Override
//post请求
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
}
}
6.配置web.xml
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请求
html
<!-- /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>
java
public class controller 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 userName = req.getParameter("userName");
String passWord = req.getParameter("passWord");
resp.getWriter().println(userName);
resp.getWriter().println();
resp.getWriter().println(passWord);
}
@Override
protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
doGet(req,resp);
}
}