Servlet与JSP学习笔记(一) 搭建环境
1. Eclipse中建立Dynamic Web Project
项目中的各个目录解析:
- deployment descriptor:部署的描述。
- Web App Libraries:自己加的包可以放在里面。
- build:放入编译之后的文件。
- WebContent:放进写入的页面。
2. 创建jsp文件
首先,你可以注意到Eclipse为你创建的jsp模板编码都是ISO-8859-1。需要到Preferences中改一下。
为jsp文件添加如下代码:
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>jsp搭建环境</title>
</head>
<body>
<%
out.println("Hello World");
%>
</body>
</html>
3. 安装Tomcat
- 下载Tomcat包
- 启动tomcat
- 重启tomcat
- windows浏览器访问
4. 创建servlet文件
写的修改servlet如下:
package com.hbin.servlet.admin;
import java.io.IOException;
import java.text.SimpleDateFormat;
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 com.hbin.service.HuangBinService;
import com.hbin.service.impl.HuangBinServiceImpl;
import com.hbin.vo.HuangBinVO;
@WebServlet("/admin/huangbin-modify-1.let")
public class HBModify1Serlvet extends HttpServlet {
private HuangBinService hbService = new HuangBinServiceImpl();
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("utf-8");
response.setCharacterEncoding("utf-8");
HuangBinVO hb = new HuangBinVO();
hb.setHbId(Integer.valueOf(request.getParameter("hbId")));
hb.setHbName(request.getParameter("hbName"));
try{
hb.setHbSex(Boolean.valueOf(request.getParameter("hbSex")));
}catch(Exception ex){}
hb.setHbTel(request.getParameter("hbTel"));
hb.setHbQq(request.getParameter("hbQq"));
try{
hb.setHbBirthdate(new SimpleDateFormat("yyyy-MM-dd").parse(request.getParameter("hbBirthdate")));
}catch(Exception ex){}
hbService.modify(hb);
try{
request.setAttribute("msg", "修改成功");
request.setAttribute("href", "admin/huangbin-list-1.let");
request.getRequestDispatcher("/admin/msg.jsp").forward(request, response);//显示操作成功页面
}catch(Exception e){
e.printStackTrace();
request.setAttribute("error", "修改失败");
request.setAttribute("href", "admin/huangbin-list-1.let");
request.getRequestDispatcher("/admin/msg.jsp").forward(request, response);
}
}
}
然后右键Run on server就可以了,因为servlet映射已经通过注解配好了。 如果要用web.xml配,则这么写:
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://xmlns.jcp.org/xml/ns/javaee" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd" id="WebApp_ID" version="3.1">
<display-name>demo</display-name>
<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>
来源:oschina
链接:https://my.oschina.net/u/4449491/blog/4357956