I am trying to check for a file exists and then include the JSP file if true. But I am getting errors from below code.
Syntax error on tokens, delete these tokens
file.handler cannot be resolved to a type
Syntax error on token "=", . expected
This is my code:
String uri = request.getRequestURI();
String pageName = uri.substring(uri.lastIndexOf("/")+1);
String filename = pageName.replace(".jsp", "");
String path = request.getServletPath();
path = path.replace( pageName , "");
String handler=path+"handler/"+filename+"_handler.jsp";
if(null != application.getResource(handler)){
<%#include file="${handler}"%>
}
I am a PHP programmer but I am new to JSP. Please advice
You might try a dispatcher to include a resource
if(null != application.getResource(handler)){
request.getRequestDispatcher(handler).include(request, response);
}
Try with JSP Expression something like:
<%#include file="<%=handler %>" %>
What about <jsp:include page="${handler}"/>?
Related
I am trying to remove the hardcode name from JSP file. I need to give the names in Config file and call in the jsp so that when a user does view page source he should not see the names.
How can I do it in JSP.
My code:
if (((tech == 'google.com') && ((id == 'email') || id == 'domain'))) || ((tech == 'google') && id == 'test')))
window.location = (url.substring(0, res + 5) + ("google/") + url.substring(res + 5, url.length));
now how to remove the hardcoded values and give it in the config file and call it here so that when I view page source I should not see google.com names
My New Code try:
Config.properties
envs=google.com,yahho.com
name= google,yahoo
tokenurl=google/,yahoo/
sample.jsp
<%# page import = "java.util.ResourceBundle" %>
<% ResourceBundle resource = ResourceBundle.getBundle("config");
String names=resource.getString("name");
String env=resource.getString("envs");
String turls=resource.getString("tokenurl");
%>
if (((tech == env[0]) && ((id == 'email') || id == 'domain'))) || ((tech
== 'names[0]') && id == 'test')))
window.location = (url.substring(0, res + 5) + ("turls[0]") +
url.substring(res + 5, url.length));
else if (((tech == env[1]) && ((id == 'email') || id == 'domain'))) ||
((tech == 'names[1]') && id == 'test')))
window.location = (url.substring(0, res + 5) + ("turls[1]") +
url.substring(res + 5, url.length));
But I am not sure this is a proper way of writing code. Can anyone suggest a proper standard way I could follow to achieve in just one line of if condition?
Create a property file in the package with extension '.properties' and use those properties defined in the file in jsp by importing the resource bundle package in the jsp.
config.properties
name=priya
email=priya#gmail.com
phone=22222
sample.jsp
<%# page import = "java.util.ResourceBundle" %>
<% ResourceBundle resource = ResourceBundle.getBundle("config");
String name=resource.getString("name");
String email=resource.getString("email");
String phone=resource.getString("phone");
%>
Name: <input type="text" id="name" value="<%=name %>">
Email: <input type="text" id="email" value="<%=email %>">
Phone: <input type="text" id="phone" value="<%=phone %>">
A classical JSP. Here I use %><% so still no output is written, and one can redirect to another page.
HTTP sends first some header lines, and one empty line and then optional HTML content.
Doing a redirect would be a header line. So still no content has to be written by the JSP. A header line can state the character set/encoding used, cookies, and so on.
So:
<%# page import = "java.util.ResourceBundle"
%><%
ResourceBundle resource = ResourceBundle.getBundle("config");
String names = resource.getString("name");
String[] env = resource.getString("envs").split(",\\s*");
String turls = resource.getString("tokenurl");
String tech = request.getParameter("tech");
if (tech != null && tech.equals("google")) {
String url = response.encodeRedirectURL(env[13]);
response.sendRedirect(url); // Just tell the browser to redirect, load the url.
return;
}
%>
Unfortunately the actual logic is your affair. In contrast to JavaScript's s == 'abc' one has s.equals("abc").
Learning and using JSP tags and the EL, expression language, will make the code smaller.
Using a servlet as controller, to prepare data and then forward to any JSP as view, parametrised with the data (or redirect to some external URL), the model, would be even nicer.
I'm trying to send an HTML email with parameters and attachments.
What i have right now is this code:
<%#include file="/libs/fd/af/components/guidesglobal.jsp" %>
<%#page import="com.day.cq.wcm.foundation.forms.FormsHelper,
org.apache.sling.api.resource.ResourceUtil,
org.apache.sling.api.resource.ValueMap,
org.apache.sling.api.request.RequestParameter,
com.day.cq.mailer.MessageGatewayService,
com.day.cq.mailer.MessageGateway,
org.apache.commons.mail.Email,
org.apache.fulcrum.template.TemplateHtmlEmail,
org.apache.commons.mail.*" %>
<%#taglib prefix="sling" uri="http://sling.apache.org/taglibs/sling/1.0" %>
<%#taglib prefix="cq" uri="http://www.day.com/taglibs/cq/1.0"
%>
<cq:defineObjects/>
<sling:defineObjects/>
<%
String storeContent = "/libs/fd/af/components/guidesubmittype/store";
FormsHelper.runAction(storeContent, "post", resource, slingRequest, slingResponse);
ValueMap props = ResourceUtil.getValueMap(resource);
HtmlEmail email = new HtmlEmail();
String[] mailTo = props.get("mailto", new String[0]);
email.setFrom((String)props.get("from"));
for (String toAddr : mailTo) {
email.addTo(toAddr);
}
String htmlEmailTemplate = props.get("templatePath");
//========Email Attachments===============
for (Map.Entry<String, RequestParameter[]> param : slingRequest.getRequestParameterMap().entrySet()) {
RequestParameter rpm = param.getValue()[0];
if(!rpm.isFormField()) {
EmailAttachment attachment = new EmailAttachment();
attachment.setPath(rpm.getFileName());
attachment.setDisposition(EmailAttachment.ATTACHMENT);
attachment.setDescription("Any Description");
attachment.setName("Any name you can set");
email.embed(new ByteArrayDataSource(rpm.get(), rpm.getContentType()), rpm.getFileName());
}
}
//========Email Attachment END===========
String emailTextToSend = "<p>Company Name: " + slingRequest.getParameter("company-name") + "</p>";
emailTextToSend += "<p>Message: " + slingRequest.getParameter("address") + "</p>";
email.setHtmlMsg(emailTextToSend);
email.setSubject((String)props.get("subject"));
MessageGatewayService messageGatewayService = sling.getService(MessageGatewayService.class);
MessageGateway messageGateway = messageGatewayService.getGateway(HtmlEmail.class);
messageGateway.send(email);
%>
With this code i can send the email, but i want to modify the code to use a path to an html template file (the path is on the variable htmlEmailTemplate.
This is my first question, how to change that code.
My second question is that if in that template i can have something like this:
<span>${company-name}</span>
Where company-name is one of the fields that i want to use on the template.
Is this possible?
Take a look at the com.day.cq.commons.mail.MailTemplate api
if your template is in the JCR repository, you can instantiate it with something like:
String template = values.get(TEMPLATE_PROPERTY, String.class);
Resource templateRsrc = request.getResourceResolver().getResource(template);
final MailTemplate mailTemplate = MailTemplate.create(templateRsrc.getPath(),
templateRsrc.getResourceResolver().adaptTo(Session.class));
final HtmlEmail email = mailTemplate.getEmail(StrLookup.mapLookup(properties), HtmlEmail.class);
Where properties is simply a HashMap of Key:Values for the template's own properties.
Since the MailTemplate returns a HtmlEmail object, you can still set all the settings you set in your own code as well.
#RequestMapping(value = "",method = RequestMethod.GET)
public String printWelcome(ModelMap model) {
model.addAttribute("message", doctorDetails);
return "doctorchannelling/index";
}
I have added this controller in my SpringMVC project now I need to access the element doctorDetails in a java code which is inside a jsp
how can I call this doctorDetails inside <% %> Mark
Something like below
<% String message = (String)request.getAttribute("message"); %>
or
<%
String message = ${message};
%>
You can simply use the EL to print them as,
${message}
If it is a String set in the request. For Model objects use ,
${message.fieldName}
See Also
How to avoid Java code in JSP files?
printing servlet request attributes with expression language
Im new to JSP and I am using a flag in my application like the URL below:
http://localhost/MyApp/result.jsp?params
How do I get that flag in the landing page?
You can use request.getQueryString() to access the raw query string (everything after the ? up to the first #, if there was one) as it was in the original URL.
Enumeration en = request.getParameterNames();
while (en.hasMoreElements()) {
String paramName = (String) en.nextElement();
if (paramName.equals("params")) {
....
}
}
If you do like this you don't have to specify a value for the parameter.
You can check this example
request.getParameter("params") will return you a blank-string.
To set a boolean flag, you can simply do.
boolean flag = request.getParamater("params") != null;
In your result.jsp file, you can get the param value within the scriplet tag <%...%> like this :
<%
String params = request.getParameter("params");
%>
Also, as DnR quoted in the comments, you will have to place '=' after the param flag even if you don't want to associate a value with this flag.
I am trying to make a simple login page to deal with database using JSP, servlet with MVC concept and Data Access Object(DAO) and I am new in this. My problem now that I need to alert a box message in servlet if the user enters invalid name and password and sendRedirect to login.jsp page again. I set flag to be 1 if the user valid then do this if-check
if(validUserFlage == 1)
response.sendRedirect("User_Manipulation_Interface.jsp");
else {
//Here i want to alert message cause user invalid ??
response.sendRedirect("Admin_And_User_Login_Form.jsp");
}
searching for this i find this answer but i can`t understand how can i do it
the answer i found:
(( With send redirect you cant display the message where you want in the code. So as per me there might be two approaches. Display a message here and use include of requestdispatcher instead of send redirect or else pass some message to admin.jsp and display the message there. ))
Set a flag parameter like this,
response.sendRedirect("Admin_And_User_Login_Form.jsp?invalid=true");
on jsp
<c:if test=${invalid eq 'true'}">invalid credentials</c:if>
You can set the Parameters like errormsg in the servlet page and add it to the ri-direct object. Then you can check that variable errormsg and if it is null then the username is correct else the username is incorrect..
In Servlet Code:
if(username.equal(databaseusername))
{
RequestDispatcher rd = request.getRequestDispatcher("NextPage.jsp");
req.setAttribute("errormsg", "");
rd.forward(request, response);
}
else
{
RequestDispatcher rd = request.getRequestDispatcher("login.jsp");
req.setAttribute("errormsg", "Wrong Username or Password");
rd.forward(request, response);
}
In JSP code:
<%
String msg=req.getAttribute("errormsg").toString();
if(!msg.equals(""))
{
// Print here the value of Msg.
}
%>
In servlet
String strExpired = (String) session.getAttribute("Login_Expired");
response.sendRedirect("jsp/page.jsp");
In jsp
<%
String strExpired = (String) session.getAttribute("Login_Expired");
out.print("alert('Password expired, please update your password..');");
%>