jsp:
<!DOCTYPE html>
<form action="/{insert your context here}/p/hello" method="post" enctype="multipart/form-data">
<input type="file" name="data">
<button>Go</button>
</form>
小服务程序:
@WebServlet
public class HelloServlet extends HttpServlet {
private static final long serialVersionUID = 1;
@Override
protected void doPost( HttpServletRequest request, HttpServletResponse response )
throws IOException, ServletException {
if ( request.getPart( "data" ) != null ) {
response.getWriter().print( "It worked\n\n" );
} else {
response.getWriter().print( "IT IS NOT WORKING!\n\n" );
}
}
}
筛选
@WebFilter( filterName = "hello" )
public class HelloFilter implements Filter {
@Override
public void init( FilterConfig config ) throws ServletException {}
@Override
public void doFilter( ServletRequest request, ServletResponse response, FilterChain chain )
throws IOException, ServletException {
request
.getRequestDispatcher( "/hello" )
.include( request, response );
request
.getRequestDispatcher( "/hello.jsp" )
.include( request, response );
}
@Override
public void destroy() {}
}
听众
@WebListener
public class HelloListener implements ServletContextListener {
@Override
public void contextInitialized( ServletContextEvent event ) {
ServletContext context = event.getServletContext();
Dynamic hello = context.addServlet( "hello", HelloServlet.class );
hello.addMapping( "/hello" );
hello.setMultipartConfig( getMultiPartConfig() );
}
@Override
public void contextDestroyed( ServletContextEvent event ) {}
private MultipartConfigElement getMultiPartConfig() {
String location = "";
long maxFileSize = -1;
long maxRequestSize = -1;
int fileSizeThreshold = 0;
return new MultipartConfigElement(
location,
maxFileSize,
maxRequestSize,
fileSizeThreshold
);
}
}
我的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:jsp="http://java.sun.com/xml/ns/javaee/jsp" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>{insert the context here}</display-name>
<jsp-config>
<jsp-property-group>
<url-pattern>*.jsp</url-pattern>
<page-encoding>UTF-8</page-encoding>
</jsp-property-group>
</jsp-config>
<filter-mapping>
<filter-name>hello</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
</web-app>
当我提交表单时,我收到输出“它不工作!” 在响应的第一行。如果我将请求的路径从更改为/{insert your context here}/p/hello
有效/{insert your context here}/hello
,为什么?
使用:
JBoss EAP 6.1