您好, 我正在研究JSP Servlet项目,因为我创建了一个CommonServlet类,从我转发请求到重定向JSP页面,我的代码如下所示
Class CommonServlet extends HTTPServlet{
protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
super.doGet(req, resp);
String url="/file/myfolder/jsp/login.jsp";
RequestDispatcher requestDispatcher = req.getRequestDispatcher(url);
requestDispatcher.forward(req, resp);
}
}
Web.xml
<servlet>
<servlet-name>common</servlet-name>
<servlet-class>com.server.CommonServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>common</servlet-name>
<url-pattern>/common/*.jsp</url-pattern>
</servlet-mapping>
但是这不起作用它会为所有其他文件获得相同的公共路径。 有谁能够帮我?
答案 0 :(得分:0)
首先,我假设您的index.jsp
web.xml
映射
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
所以首先服务器读取web.xml并在你执行
时加载index.jsphttp://localhost:8080/yourProjectName
在index.jsp
中有一个像这样调用servlet的表单
<form method="get" action="common" name="form">
<input type="submit" value="LOGIN"/>
</form>
最后在yourServletClass的doGet()
中
将此重定向到login.jsp(假设您的login.jsp位于webcontent/login.jsp
)
RequestDispatcher rd=req.getRequestDispatcher("login.jsp");
rd.include(request,response);
修改:尝试这样的事情
将您在web.xml
中的网址映射更改为
<url-pattern>/myservlet</url-pattern>
在web.xml
<filter>
<filter-name>yourFilter</filter-name>
<filter-class>org.yourpackage.YourFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>yourFilter</filter-name>
<url-pattern>/common/*</url-pattern>
</filter-mapping>
然后是过滤类
public class YourFilter implements javax.servlet.Filter {
@Override
public void destroy() {
}
@Override
public void doFilter(ServletRequest req, ServletResponse res, FilterChain fc)
throws IOException, ServletException {
HttpServletRequest request = (HttpServletRequest) req;
String url = request.getRequestURL().toString();
if(url.endsWith(".jsp")) {
RequestDispatcher dispatcher = request.getRequestDispatcher("/myserlvet");
dispatcher.forward(req, res);
}
}
@Override
public void init(FilterConfig fc) throws ServletException {
}}