I put index.jsp inside WEB-INF. Then I have a servlet which dispatch request to that file.
#WebServlet(name="Home", urlPatterns={"/"})
public class Home extends HttpServlet {
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
request.getRequestDispatcher("/WEB-INF/index.jsp").forward(request, response);
}
}
I have a css folder which is outside the WEB-INF folder. It contains the css.css file.
The This is the content of index.jsp file:
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" href="<c:url value="/css/css.css" />" rel="stylesheet">
<title>JSP Page</title>
</head>
<body>
<h1>Hello World!</h1>
</body>
</html>
The content of css file:
body {
color: red;
}
Question: Why doesn't the sentence "Hello World" turn red? Why can't the index.jsp file access the css file?
It looks like you are mapping your servlet "Home" for all incoming requests. So when the browser makes a request for the css url, it is intercepted by the servlet and it is unable to find it.
You can change the servlet mapping for the home servlet so that it does not intercept all requests
#WebServlet(name="Home", urlPatterns={"/home"})
Add following in your jsp
<link rel="stylesheet" type="text/css" href="/project-context-root-name/css/myfile.css"/>
If it did not work further then do below step.
In your web.xml file add following
<servlet-mapping>
<servlet-name>servlet-name</servlet-name>
<url-pattern>/css/*</url-pattern>
</servlet-mapping>
Related
Question:
I want to set servlet 'main' as welcome file in web.xml but it shows warning "File name references to main that does not exist in web content"
Browser can't access CSS files but can access Images which both fall under same parent directory 'assests'
I want to know if both these problems are related and how to solve them
What I've already referenced:
how-to-include-external-css-file-in-jsp
Similar SO questions: 1, 2, 3
Result:
http://localhost:8080/SampleApplication fetches main page as the homepage
http://localhost:8080/SampleApplication/main also fetches main page
But in both cases, doesn't load any CSS files.
I've tested the Front-end in Brackets independently and works fine.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app id="WebApp_ID" version="3.1"
xmlns="http://xmlns.jcp.org/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/web-app_3_1.xsd">
<display-name>SampleApplication</display-name>
<welcome-file-list>
<welcome-file>main</welcome-file>
</welcome-file-list>
</web-app>
MainServlet.java
#WebServlet(name = "main", urlPatterns = { "/main" })
public class MainServlet extends HttpServlet {
private static final long serialVersionUID = 1L;
public MainServlet() {
super();
}
/**
* Forwards to the main page.
*/
#Override
protected void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
RequestDispatcher dispatcher
= this.getServletContext().getRequestDispatcher("/WEB-INF/views/MainView.jsp");
dispatcher.forward(request, response);
}
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
//Additional Logic
}
MainView.jsp
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Ship Short Dated Products</title>
<!-- ---------------------- BOOTSTRAP AND CUSTOM STYLESHEETS ----------------------- -->
<link rel="stylesheet" type="text/css"
href="<c:url value="http://fonts.googleapis.com/css?family=Roboto:400,100,300,500" />">
<link rel="stylesheet" type="text/css"
href="<c:url value="/assets/bootstrap-3.3.7-dist/css/bootstrap.min.css" />">
<link rel="stylesheet" type="text/css"
href="<c:url value="/assets/font-awesome/css/font-awesome.min.css" />">
<link rel="stylesheet" type="text/css"
href="<c:url value="/assets/css/form-elements.css" />">
<link rel="stylesheet" type="text/css"
href="<c:url value="/assets/css/main-layout.css" />">
<!--
--------------------------- JQUERY AND BOOTSTRAP PLUGINS -------------------------------
--------------------------- Please maintain the order for libs -------------------------
-->
<script
src="<c:url value="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js" />"></script>
<script
src="<c:url value="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js" />"></script>
<!--[if lt IE 9]>
<script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
<script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
<![endif]-->
</head>
<body>
<!-- -------------------------------- IMAGE CONTENT -------------------------------- -->
<img class="img-responsive" src="assests/images/HMSGradient.jpg">
<!-- IMAGE CONTENT End -->
</body>
</html>
Directory Structure
Thanks!
You should define a list of welcome files in the <welcome-file> element. So please try changing it to <welcome-file>MainView.jsp</welcome-file> and move the jsp file into WebContent/main/. In addition, you don't need to have MainServlet.java.
I work with a Java/Spring project and the project structure is provided below,
I need to reference the app.css in the index.jsp file. Currently, I reference the following way in the index.jsp and the app doesn't get the CSS information's.
<%# page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>Bitcoin Wallet</title>
<link href="${pageContext.request.contextPath}/resources/css/app.css" rel="stylesheet" type="text/css"/>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
</html>
In the dispatcher-servlet.xml, I provided the resources path as below,
The page I get in the localhost clearly doesn't have the css. How to solve the issue?
To use resources in spring mvc project you have to declare mvc:resources, to map url to a physical file path location.
<mvc:resources mapping="/resources/**" location="/resources/css/"
When you use /resources/ in jsp file spring will map this url to /resources/css/.
Next you can reference css file in jsp file:
<link href="<c:url value="/resources/css/app.css" />" rel="stylesheet">
And move resources folder into webapp folder as
Hope someone just could give a hint where to look for the source of the problem.
Class Login Action
enter code here
#Namespace("/")
public class LoginAction extends ActionSupport {
private static final long serialVersionUID = 1L;
#Override
#Action(value = "/welcome", results = { #Result(name = SUCCESS, location = "/WEB-INF/content/welcome.jsp") })
When I exectute my index.jsp to execute welcome.jsp didn't work.
index.jsp
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
</head>
<body>
<h3>Welcome to Struts 2</h3>
<s:form action="home">
<s:textfield name="username" label="User Name"></s:textfield>
<s:textfield name="password" label="Password" type="password"> </s:textfield>
<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>
welcome.jsp
enter code here
<%# page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<%# taglib uri="/struts-tags" prefix="s"%>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=IUTF-8">
<title>Welcome To Struts 2</title>
</head>
<body>
<h3>
Welcome
<s:property value="username"></s:property>
!
</h3>
</body>
Result
Struts Problem Report
Struts has detected an unhandled exception:
Messages:
There is no Action mapped for namespace [/] and action name [home] associated with context path [/struts].
In Struts2 you map a form to the action config using s:form tag's action and namespace attributes.
Normally, the action attribute accepts the action name, but it can contain the URL. The form tag is rendered by the template to HTML form where the action attribute have to be URL.
So Struts is getting the action name and generate URL. You can see the source code in the browser. When request is made Struts2 uses the request URI to find the action mapping as explained here.
Usually the 404 error results in missing action configuration on the server that corresponds to the requested URI. When you submitted a form the request is made and resource is requested but the action config is not found, hence Struts2 returns 404 error.
You don't need to use annotations if you are utilizing a convention or rest plugins but the annotation always allows manually override the defaults.
By default the results path is /WEB-INF/contents/ and the action name is without slashes, so you can use annotation:
#Action(value = "welcome", results = #Result(location = "welcome.jsp") )
You can find the references to online resources from this answer.
The one from tutorials read this tutorial.
The solution.
In my index.jsp I wrote "home" in the tag action, form action="home" The correct are the same name at the Action.
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Login Page</title>
</head>
<body>
<h3>Welcome to Struts 2</h3>
<s:form action="home"> **The correct is "welcome"**
<s:textfield name="username" label="User Name"></s:textfield>
<s:textfield name="password" label="Password" type="password"> </s:textfield>
<s:submit value="Login"></s:submit>
</s:form>
</body>
</html>
And in my LoginAction I used value ="/welcome".
package web.actions;
#Action(value = "/welcome", results = { #Result(name = SUCCESS, location = "/WEB-INF/content/welcome.jsp") })
public String execute() throws Exception {
return SUCCESS;
}
The messagem is very clear.
There is no Action mapped for namespace [/] and action name [home] associated with context path [/struts].
But I just saw the mistake doing a lot of examples.
I am new to JSP. This is my simple JSP file:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8" import="java.util.Date"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Insert title here</title>
</head>
<body>
<%!public void jspInit() {
System.out.println("Init called!");
}%>
<h3>Hello World!</h3>
<br />
<%
int i;
for (i = 0; i < 100; i++)
out.print(i + " ");
out.println("èéòçàù<br/>");
%>
<b>The time right now is: <%=new Date()%></b>
<%
if (request.getParameter("name") != null) {
session.setAttribute("name", request.getParameter("name"));
application.setAttribute("name", request.getParameter("name"));
}
%>
<br />
<b>The name that was set for request is: <%=request.getParameter("name")%></b>
<br />
<b>The name that was set for session is: <%=session.getAttribute("name")%></b>
<br />
<b>The name that was set for application is: <%=application.getAttribute("name")%></b>
<br />
</body>
</html>
The jspInit() method is called every time my page is opened. Shouldn't it be called only the first time the page is opened? And can somebody please tell me what are the other JSP methods and how do they work? I can't find precise information on this. Thank you!
Use deployment descriptor for setting mapping:
<servlet>
<servlet-name>Index</servlet-name>
<jsp-file>/index.jsp</jsp-file>
</servlet>
<servlet-mapping>
<servlet-name>Index</servlet-name>
<url-pattern>/Index/*</url-pattern>
</servlet-mapping>
When you opening the page via direct name(index.jsp) the .jsp file isn't working correctly and jspInit() is calling every time when you open the page. But when you open page using url pattern(Index), the page works correctly.
Internet Explorer doesn't support HTML <base> tag and even other browsers do, there are some problems when redirect takes place inservletsto some.jsppages for examplerequest dispatching.`
It's feasible to add ${pageContext.request.contextPath} with each URL
nor request.getServletPath()
JSP relative links for CSS and images with servlets forwarding may change things a lot. This link : Browser can't access/find relative resources like CSS, images and links when calling a Servlet which forwards to a JSP
Is there a better approach with JSP / servlets or it's just an IE issue?
Link : HTML <base> TAG and local folder path with Internet Explorer
And if it is an IE issue:
1. how to fix the IE issue as the above post is unable to give a valid answer?
2. how to solve it with JSP / servlets?
My website is now showing CSS and images.
E.g. HTML output is:
<base href="http://localhost:8080/Alpinema/" /> is not working for
<link media="all" rel="stylesheet" type="text/css" href="css/all.css">
It works in other browsers like Firefox and Chrome.
My JSP code portion:
<head>
<base href="${fn:substring(url, 0, fn:length(url) - fn:length(uri))}${req.contextPath}/" />
<meta charset="utf-8">
<title>Alpinema.com</title>
<link media="all" rel="stylesheet" type="text/css" href="css/all.css">
/css?family=Merriweather|PT+Sans:700|Nobile:400italic' rel='stylesheet' type='text/css'>
</head>
Use <c:url> tag from JSTL to reference CSS/JavaScript resources inside my JSP files. By doing so you can be sure that the CSS/JavaScript resources are referenced always relative to the application context (context path).
Example
index.jsp:
<%# page language="java" contentType="text/html; charset=UTF-8" pageEncoding="UTF-8"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html>
<html>
<head>
<title>Some Title</title>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<link type="text/css" rel="stylesheet" href="<c:url value="/css/main.css" />" />
<script type="text/javascript" src="<c:url value="/js/utils.js" />"></script>
<script type="text/javascript" src="<c:url value="/js/jquery-1.8.3.js" />"></script>
</head>
<body>
...
</body>
</html>
For even more solutions see my answer here:
Adding external resources (CSS/JavaScript/images etc) in JSP.