您的位置:首页 > Web前端 > JavaScript

JSP入门3 Servlet

2013-10-23 15:46 344 查看
需要继承类HttpServlet

服务器在获得请求的时候会先根据jsp页面生成一个java文件,然后使用jdk的编译器将此文件编译,最后运行得到的class文件处理用户的请求返回响应。如果再有请求访问这jsp页面,服务器会先检查jsp文件是否被修改过,如果被修改过,则重新生成java重新编译,如果没有,就直接运行上次得到的class。



因为jsp虽然比servlet灵活,却容易出错,你找不到良好的方式来测试jsp中代码,尤其在需要进行复杂的业务逻辑时,这一点儿很可能成为致命伤。所以一般都不允许在jsp里出现业务操作有关的代码

servlet是一个java类,需要编译之后才能使用,虽然显示页面的时候会让人头疼,不过在进行业务操作和数据运算方面就比jsp稳健太多了

因此我们就要结合两者的优点,在servlet进行业务操作和请求转发,jsp全面负责页面显示,这也是目前公司企业里常用的开发方式。

web.xml配置

servlet的配置

1.对应类

2.对应地址

<servlet>
<servlet-name>ContactServlet</servlet-name>

<servlet-class>anni.ContactServlet</servlet-class> </servlet>
<servlet-mapping>
<servlet-name>ContactServlet</servlet-name>

<url-pattern>/contact.do</url-pattern>

</servlet-mapping>

继承HttpServlet,不过这次实现两个方法doGet()和doPost()分别处理http的GET和POST方式的请求

/**
* 处理get请求. */
public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
this.process(request, response); }
/**
* 处理post请求 */
public void doPost(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
this.process(request, response);}

/**
* 处理请求. */
public void process(HttpServletRequest request,HttpServletResponse response) throws ServletException, IOException {
request.setCharacterEncoding("gb2312");
String method = request.getParameter("method");

if (method == null) { method = "list"; }

try { // 分发请求

if ("list".equals(method)) {

this.list(request, response); }

else if ("save".equals(method)) { this.save(request, response); }

else if ("edit".equals(method)) { this.edit(request, response); }

else if ("update".equals(method)) { this.update(request, response); }

else if ("remove".equals(method)) { this.remove(request, response); }
} catch(Exception ex) { System.err.println(ex) }

}

默认的索引页面index.jsp中,将list.jsp改成
contact.do?method=list,把请求转发到contact.do顺便再带上操作参数。

public void list(HttpServletRequest request,HttpServletResponse response) throws Exception {
List list = contactDao.getAll(); request.setAttribute("list", list);
request.getRequestDispatcher("/list.jsp").forward(request, response); }
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: