JavaWeb项目【源码】——图书项目1.0:Tomcat版本 + Servlet + Filter + Jsp + bootstrap & JavaScript初步 + Ajax初步
由于原始代码已经是一个较为完整的JavaWeb项目,下面我们提取核心代码来回答这个问题。
web.xml
配置文件:
<web-app ...>
<filter>
<filter-name>EncodingFilter</filter-name>
<filter-class>com.example.book.filter.EncodingFilter</filter-class>
<init-param>
<param-name>charset</param-name>
<param-value>UTF-8</param-value>
</init-param>
</filter>
<filter-mapping>
<filter-name>EncodingFilter</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<servlet>
<servlet-name>BookServlet</servlet-name>
<servlet-class>com.example.book.servlet.BookServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>BookServlet</servlet-name>
<url-pattern>/book</url-pattern>
</servlet-mapping>
</web-app>
EncodingFilter
类:
package com.example.book.filter;
import javax.servlet.*;
import java.io.IOException;
public class EncodingFilter implements Filter {
private String charset;
@Override
public void init(FilterConfig filterConfig) throws ServletException {
charset = filterConfig.getInitParameter("charset");
}
@Override
public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
throws IOException, ServletException {
request.setCharacterEncoding(charset);
response.setContentType("text/html; charset=" + charset);
chain.doFilter(request, response);
}
@Override
public void destroy() {
// 空实现
}
}
BookServlet
类:
package com.example.book.servlet;
import com.example.book.dao.BookDAO;
import com.example.book.dao.impl.BookDAOImpl;
import com.example.book.model.Book;
import javax.servlet.*;
import javax.servlet.http.*;
import java.io.IOException;
import java.util.List;
public class BookServlet extends HttpServlet {
private BookDAO bookDAO = new BookDAOImpl();
@Override
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
List<Book> books = bookDAO.findAll();
request.setAttribute("books", books);
request.getRequestDispatche
评论已关闭