初步学习http协议

来源:互联网 发布:linux c语言编程 编辑:程序博客网 时间:2024/05/17 03:11

根据老罗视频学习的http协议,总结一下。

File->New->Dynamic Web Project-> 输入project name。

Target runtime配置一下tomcat。

Configuration选择Default Configuration for Apache Tomcat v6.0(我下载的是6.0版本的)。



项目框架如图所示:





index.jsp文件中设置编码格式为UTF-8

具体内容如下:

<%@ page language="java" contentType="text/html; charset=utf-8"    pageEncoding="utf-8"%>    <%String path = request.getContextPath();String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+path+"/";%><!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=ISO-8859-1"><title>测试http协议体的内容</title></head><body>  <form name = "form1" method="post" action="<%=path%>/servlet/LoginActivity">  用户名:<input type="text" name="username" value=""></input><br/>  密码:<input type="password" name="password" value=""></input><br/>  <input type="submit" name="submit" value="提交表单"></input><br/>  </form></body></html>

web.xml文件配置如下:

<?xml version="1.0" encoding="UTF-8"?><web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" id="WebApp_ID" version="2.5">    <servlet>    <description>This is the description of my J2EE component</description>    <display-name>This is the display name of my J2EE component</display-name>    <servlet-name>LoginActivity</servlet-name>    <servlet-class>com.login.manager.LoginActivity</servlet-class>  </servlet>  <servlet-mapping>    <servlet-name>LoginActivity</servlet-name>    <url-pattern>/servlet/LoginActivity</url-pattern>  </servlet-mapping>    <welcome-file-list>    <welcome-file>index.html</welcome-file>    <welcome-file>index.htm</welcome-file>    <welcome-file>index.jsp</welcome-file>    <welcome-file>default.html</welcome-file>    <welcome-file>default.htm</welcome-file>    <welcome-file>default.jsp</welcome-file>  </welcome-file-list></web-app>

LoginActivity.java继承自HttpServlet。重载onPost函数,具体内容如下:

@Overrideprotected void doPost(HttpServletRequest req, HttpServletResponse resp)throws ServletException, IOException {// TODO Auto-generated method stubresp.setContentType("text/html");PrintWriter out = resp.getWriter();String usernameString = req.getParameter("username");String pswdString = req.getParameter("password");System.out.print(usernameString);System.out.print(pswdString);if(usernameString.equals("admin")&&pswdString.equals("123")){out.print("login is success!");}else {out.print("login is error!");}out.flush();out.close();//super.doPost(req, resp);}

注:web.xml要配置<servlet>和<servlet-mapping>否则无法提交数据

index.jsp格式必须是utf-8,否则中文字符串会是乱码的






0 0
原创粉丝点击