Menu
  • HOME
  • TAGS

Initialize class with constructor in

Tag: jsp,servlets,usebean

I am trying to initialize a class by passing a parameter to the constructor. I need the scope to be "page". I know I have one argument in my constructor, but how do I have one that accepts parameter using <jsp:useBean>, and can be called from a JSP page?

 public class A extends B {
    A(ServletRequest req) {
       super(req);
}

If there are no-arg constructor, We can use < jsp:useBean id="someId" class="mypackage.A" scope="page" /> tag. But in a useBean JSP tag, you can't invoke any constructor.

Is there any way initialize class with constructor?

Best How To :

No.

Either use <jsp:setProperty>,

<jsp:useBean id="someId" class="mypackage.A" scope="page">
    <jsp:setProperty name="someId" property="request" value="${pageContext.request}" />
</jsp:useBean>

or use a normal servlet:

request.setAttribute("someId", new A(request));

It's by the way surprising that you tagged [servlets] on the question while that's usually not to be used together with <jsp:useBean> as those two approaches of managing beans are conflicting (one is MVC level 1 and other is MVC level 2). For detail, see also our servlets wiki page.

Nonetheless, having a bean property of HttpServletRequest type is fishy. There are undoubtedly better ways to achieve the concrete functional requirement for which you incorrectly thought that this all would be the right solution.

Open a properties file from a class in a Dynamic Web Project

java,eclipse,jsp,properties-file

You can put this propertie file within your java package for example com/test and use following: getClass().getResourceAsStream( "com/test/myfile.propertie"); Hope it helps....

Java Servlet - get parameters with same name

java,java-ee,servlets,post

Close. It's String[] lines = request.getParameterValues("line"); but the name is line, not line[]...

CQ5 SlingServlet and resourceTypes not working for specific resource paths

servlets,cq5,aem,sling

The problem with pages is that the resourceType is stored on the jcr:content node below the cq:Page node. If you would call [path-to-page]/_jcr_content.bob it should work. Note: _jcr_content is an url save version of jcr:content. Why your last example is actually working, I cannot tell....

Downloading file from Java servlet gives null

java,file,servlets,stream

This solution is a modified solution from BalusC File Servlet blog. The reason I use this solution is because it reset() the HttpServletResponse response before writing data. @WebServlet(urlPatterns = { "/Routing/*" }) @MultipartConfig(location = "/tmp", fileSizeThreshold = 1024 * 1024, maxFileSize = 1024 * 1024 * 5, maxRequestSize = 1024...

How to open a new page when button is clicked on

java,html,jsp,servlets,web-applications

You can send the request from one jsp to another. Lets say after the index.jsp you want to go to login.jsp when the button is pressed.Then create a form like this: <form action="login.jsp"> <input name="username" type="text"><br> <input name="password" type="password"> <input type="Submit" value="Login"> </form> Now in the login.jsp you can get...

How to Get The Parameters Name From The Http request

java,servlets

You can use. Enumeration<String> parameterNames = request.getParameterNames(); while (parameterNames.hasMoreElements()) { String paramName = parameterNames.nextElement(); out.write(paramName); } You can visit following link for more details. http://examples.javacodegeeks.com/enterprise-java/servlet/get-all-request-parameters-in-servlet/...

SSL Handshake in Java Servlet (HttpsURLConnection)

java,servlets,ssl

So, whenever SSL connection is established it tries to verify the server name with the host name in certificate. In this case, since it is self signed it may not be having any server name mostly. What you need to do is write a implementation of javax.net.ssl.HostnameVerifier and assign to...

Need to add elements of an array to a variable of JavaScript in JSP

javascript,arrays,jsp,jstl

First of all, in your code for two arrays you don't want to have square brackets enclosed in the quotation marks. This will make your whole arrays result and result2 to be a Strings. Second, closing bracket is missing for results, opening bracket is missing for results2. Third, you cannot...

Sending text file to client through Spring MVC web application

java,spring,jsp,spring-mvc,servlets

It is not possible to redirect to another page when returning file as file itself is http response. Very good explanation is here: Spring - download file and redirect

Radio button group name

java,jsp

The simplest way is to save the number of items in a hidden input say itemsNumber and use a for loop to get the actual values of the parameters: int itemsNumber=Integer.parseInt(request.getParameter("itemsNumber")); for(int i=1;i<=itemsNumber;i++){ String cat=request.getParameter("rdCat_"+i); //then you can do processing with the above value } ...

Can't insert or update record to database jsp

java,jsp,jdbc

Problem for the below part PreparedStatement preparedStatement = connection.prepareStatement("update survey_data_27 set uname=?, p1q1=?, p1q2=?" + "where survey_id=?"); there are total 4 variables but your code is setting 6 variables(below is your code) // Parameters start with 1 preparedStatement.setString(1, first.getuname()); preparedStatement.setString(2, first.getp1q1()); preparedStatement.setString(3, first.getp1q2()); preparedStatement.setString(4, first.getp1q3()); preparedStatement.setString(5, first.getp1q4());...

JSP - issue with custom Taglib

java,jsp

Hi all inbuilt tag already handles the expression language. Just change your code as mentioned below and it will work fine. public class TestTaglib extends TagSupport { private String testCode; public int doStartTag() throws JspException { try { JspWriter out = pageContext.getOut(); //doing some conversion with testCode String value =...

Initialize class with constructor in

jsp,servlets,usebean

No. Either use <jsp:setProperty>, <jsp:useBean id="someId" class="mypackage.A" scope="page"> <jsp:setProperty name="someId" property="request" value="${pageContext.request}" /> </jsp:useBean> or use a normal servlet: request.setAttribute("someId", new A(request)); It's by the way surprising that you tagged [servlets] on the question while that's usually not to be used together with <jsp:useBean> as those two approaches of managing...

Jsp list output [email protected]?

jsp,spring-mvc,spring-boot

There are two things I see wrong. First if your code is really as posted and not a typo, than you should note that you don't print anything inside a loop as you just iterate and never do anything with the user variable The following <c:forEach items = "${tweets}" var="user"...

Form submit portlet with Spring MVC

java,jsp,spring-mvc,liferay,portlet

Which version of Liferay you are using? if it is > 6.2 GA1 Then in your liferay-portlet.xml file, please add this attribute and recompile and test again. <requires-namespaced-parameters>false</requires-namespaced-parameters> Liferay adds namespace to the request parameters by default. You need to disable it. ...

html form action not working when using eclipse

java,eclipse,jsp,servlets

Try to delete the comment // @WebServlet("/hello"), and put @WebServlet("/hello"). Stop the server, refresh and if its necessary clean it. And re - launch again. And take a look if the web.xml the welcome file list is correctly, because is the file which launch always.

Java Struts2 (Action class not found)

java,xml,jsp,struts2

Struts2 XML configuration provider cannot load the action class. This class com.tutorialspoint.struts2.HelloWorldAction is not available on the classpath or corrupted. The version are you using is too old, and you need to recreate the project and update version information in xml configuration files struts.xml, web.xml. See How To Create A...

How to send automatic mail from java Servlet using gmail id?

java,email,servlets

check out the spam folder as well and it might take a minute or 2 to get there in your inbox. I wrote a blog post on sending email via java. You may look it for the reference http://javadocx.blogspot.com/2013/06/sending-email-with-java.html...

MySQLSyntaxErrorException in SQL syntax

java,mysql,jsp,mysql-connector

Change ResultSet rs = selectUser.executeQuery(query); to ResultSet rs = selectUser.executeQuery(); when you already prepared the statement in connection.prepareStatement(query); then why to pass the query again in selectUser.executeQuery(query);...

How to compile and run a JSP Beans project using Eclipse

java,html,eclipse,jsp

The problem is the difference between you input name and the setter of UserData, please try to modify the index.html as: <form action="saveName.jsp" method="post"> What is your name? <input type="text" name="userName" size="20"> <br> What is your email address? <input type="text" name="userEmail" size="20"> <br> What is your age? <input type="text" name="userAge"...

Why ${!blabla.blibli} returns true in JSTL even if blabla doesn't exist?

java,jsp,jstl

JSP EL is NULL friendly, if given attribute is not found or expression returns null, it doesn’t throw any exception. For arithmetic operations, EL treats null as 0 and for logical operations, EL treats null as false. So when you are trying "!" for the variable which is not found...

Trying to setup tomcat to use servlets

java,tomcat,servlets,invokerequired

I've just take a quick look up to the book and on page 407, there are the lines that you have to decomment or/else if not exist, add. From the book; <!-- <servlet> <servlet-name>invoker</servlet-name> <servlet-class> org.apache.catalina.servlets.InvokerServlet </servlet-class> <init-param> <param-name>debug</param-name> <param-value>0</param-value> </init-param> <load-on-startup>2</load-on-startup> </servlet> --> Anything located in between the "<!--"...

set focus to next input element after jsf's change value listener

javascript,jsp,jsf

finally i found the solution. in my Value Change Listener. i added this statement at the end. if(event.getComponent().getId().equalsIgnoreCase("COMPONENT ID FIRST")){ String jsStatement = "document.getElementById(\'" + ("COMPONENT ID SECOND")+ "\').focus();"; SESSIONCLASS.setBodyOnload(jsStatement); } in the above code "COMPONENT ID FIRST" is the current component where your value change listener is triggered and...

Print and println aren't executed in the same time

java,jsp,servlets,printing,println

This is related to the fact you never terminate the line. This is either something to do with java not flushing, or to do with the log handler waiting until the end of line before writing to the log. Add a final System.out.println() or System.out.print('\n') at the end to fix...

How to trigger a doGet before displaying a jsp page

jsp,java-ee,web.xml

You cannot do that, at least without Javascript. A ServletResponse can do only one thing : either return csv data, or return an HTML page. You absolutely need 2 different requests (be them simple normal requests or javascript one) : first to download a csv file, second to display the...

Set default value for struts 2 autocompleter

jquery,jsp,struts2,struts2-jquery,struts2-jquery-plugin

You should use the value attribute as suggested by @Choatech: value false false String "Preset the value of input element." The value specified, however, should be one of the keys listed in your cityList, not some random value. If the value you want to use is an header one, like...

How to display text in browsers tab bar in a javaserver page [closed]

html,jsp,browser,text,tabs

Browser tabs display the FavIcon and the <title> of the page. You can't really display multiple lines in a browser tab, though you could separate information you want to display in it with a -, which is pretty common practice. For example: <html> <head> <title>My Title - Awesome Web Page</title>...

Servlet to jsp on button click - whats the error?

java,jsp,servlets

Tried out the code in a separate jsp, picking up sections and pasting them, removing extra div's. Seemed to make it work.

viewResolver with more folders inside of WEB-INF/jsp is not working in spring

java,spring,jsp,spring-mvc

Say you have a jsp test.jsp under /WEB-INF/jsp/reports From your controller return @RequestMapping("/helloWorld") public String helloWorld(Model model) { model.addAttribute("message", "Hello World!"); return "reports/test"; } ...

Session Object is returning Null

java,servlets

You are setting attribute UserName but retrieving attribute userName. It is case-sensitive.

shall I use Spring framework for a performance-critical proxy application? [closed]

java,spring,authentication,servlets

Before re-writing your code first thing you should analyze is why do you require Spring framework? What problem are you facing in your current architecture? Just because size of the response data stokes up shouldn't be the only reason to re-write your code. You can better design your existing code...

How to transform $.post to $.ajax?

javascript,jquery,ajax,json,servlets

$.post("../admin-login", { dataName:JSON.stringify({ username:uname, password:pass, }) }, function(data,status){ console.log("Data:"+data); answer = data; } ); becomes function getResult(data) { // do something with data // you can result = data here return data; } $.ajax({ url: "../admin-login", type: 'post', contentType: "application/x-www-form-urlencoded", data: { dataName:JSON.stringify({ username:uname, password:pass, }) }, success: function (data,...

Login page filter problems

jsp,servlets,servlet-filters

In web.xml you can make entry which will accept a URL-mapping and whenever you will call that URL your filter will intercept that and you can navigate your request to any page.

Clicking Refresh Servlet Page Shows Repetitive Content

java,mysql,servlets

Delete string after printing string.delete(0,string.length()); ...

How to use two port numbers for a single java web application?

java,eclipse,tomcat,servlets,port

Find out which tomcat installation eclipse is using. Under your tomcat installation there is a conf/server.xml file. You add a new HTTP connector for the port you desire there and restart tomcat. Now you have tomcat listening to the extra port you added. <Connector port="4121" protocol="HTTP/1.1" connectionTimeout="20000" redirectPort="8443" URIEncoding="UTF-8" />...

Store sensitive using Java Servlet API

java,servlets

What kind: configuration data like database user+password, or mass data like member accounts? Configuration data can be stored outside the application (war), as JNDI data source and such. This would mean that the developers need no access to deployment configuration, and the deployment configuration can have its passwords updated regularly....

Show and hide select input which is created dynamically

jquery,jsp,show-hide

One option is to use next. Since next refers to next sibling just get the parents sibling like so: if($(this).is(":checked")) { $(this).parent().parent().next().show(); } else { $(this).parent().parent().next().hide(); } ...

Tomcat servlet the requested resource is unavailable

java,tomcat,servlets

Your web.xml file needs to be inside the WEB-INF folder instead of next to it. If it's not in the right location, Tomcat won't parse it and your URL patterns will not be correctly configured. If you're using the Servlet 3.0 (or higher) API, you could also configure your servlet...

download jasper report to a specific location in the server

java,servlets,jasper-reports

You can use JasperExportManager to save the generated pdf to a specific location in server JasperExportManager.exportReportToPdfFile(jasperPrint, exportPath); eg: String exportDir = System.getProperty("jboss.server.config.dir") +"/jasperreport/export"; String exportPath = exportDir + "/reportName.pdf"; JasperReport jasperReport = CompileManager.compileReport(jrxmlFilePath, mainReportName); JasperPrint jasperPrint =JasperFillManager.fillReport(jasperReport, parameters, jsonDataSource);...

PropertyNotFoundException in jsp

java,jsp

The name of your getter & setter is wrong. By convention it must be: public Integer getSurvey_id() { return survey_id; } public void setSurvey_id(Integer survey_id) { this.survey_id=survey_id; } ...

JSP form sending data including files in servlet

java,jsp,servlets,post,get

Form: <form id="uploadForm" name="uploadForm" action="UploadServlet" method="post" enctype="multipart/form-data"> user:<input type="text" name="user"/> img<input type="file" name="image"/> </form> You can still get both with a post request: protected void doPost(HttpServletRequest request, HttpServletResponse response) { List<FileItem> items = new ServletFileUpload(new DiskFileItemFactory()).parseRequest(request); InputStream fileContent = null; String user = ""; for (FileItem item : items) {...

How to get current jsp file path in war?

java,jsp

This will be implementation dependent, but since many implementation use Jasper, it may well be more portable than you think. Of course, portability may not be an issue. But the simple case is that you take the full qualified class name of "this" from within the JSP, and from that...

how to manage multiple war application in tomcat server?

java,maven,tomcat,servlets

Use same tomcat server, but copy and rename your web application to something different. For eg, original application name app, copy and rename as following. webapp -> app1 app2 app3 Running tomcat server per each war application need to maintain many server. This is a bad idea....