JSP function error - function

I'm new to JSP and I'm trying to write a function that executes a query and then returns the metadata. I'm getting an error that reads:
Generated servlet error:
Syntax error on token ")", Block expected after this token
Here is my code:
<%! ResultSetMetaData test(ResultSet rs, Statement s){
try{
rs = s.executeQuery("SELECT * FROM students WHERE name = 'Alice Wood'");
}
catch(SQLException e);
return rs.getMetaData();
}
%>

Firstly you should not write your Java code in JSP file, especially SQL queries, you should do it in your Servlet.
Secondly you used declaration tag: <%! %> which is suitable only for declarations, you need Scriptlet tag here: <% your code here %>, but as I said it is not good too, at least you should transfer your code into Servlet.
Here is good tutorial for JSP tags and overall about JSP: http://www.tutorialspoint.com/jsp/jsp_syntax.htm

Related

Why do I need [Class.forName("org.mariadb.jdbc.Driver");]?

https://mariadb.com/kb/en/about-mariadb-connector-j/
https://docs.oracle.com/javase/8/docs/api/java/sql/DriverManager.html
In that site, Class.forName is no longer needed.
(that file based Java11, JavaEE8 with gradle)
but In my case.
If I didn't use this.
Class.forName("org.mariadb.jdbc.Driver")
HTTP:500 error occurred and that error message is
java.lang.RuntimeException: java.sql.SQLException: No suitable driver found for jdbc:mariadb://localhost:3306/mydb
Otherwise when I use that code, It work well.
Class.forName("org.mariadb.jdbc.Driver")
Why do they need [Class.forName]?
<%# page import="java.sql.Connection" %>
<%# page import="java.sql.DriverManager" %>
<%# page import="java.sql.SQLException" %>
<%# page contentType="text/html;charset=UTF-8" language="java" pageEncoding="UTF-8" %>
<%
Connection conn = null;
Class.forName("org.mariadb.jdbc.Driver");
try {
conn = DriverManager.getConnection("jdbc:mariadb://localhost:3306/mydb", "root", "1234");
} catch (SQLException e) {
throw new RuntimeException(e);
}
conn.setAutoCommit(false);
%>
The JDBC 4 standard introduced automatic registration of JDBC drivers. Earlier drivers had to manually be registered by forcing the classloader to load them, e.g., by calling Class.forName.
It seems you're using an older version of the driver that still requires the Class.forName call.

How to Include and Use GSON library in Eclipse project

I'm from the PHP background, so pardon my noobness. I'm required to use JSON in one of my projects and I cannot, for the life of me, determine how to import and use the GSON library.
I followed Adding library to Eclipse and Using GSON threads but for some reason my code isn't working.
The aim is to pass an ArrayList object back as a JSON array so that I can use Jquery (inside Ajax success function) to iterate over it.
But when I use the following (This is not a class, simply a jsp file which connects to database, pulls some info, and stores it in an ArrayList):
<%# page import="java.sql.*"%>
<%# page import="java.util.*"%>
<%
String kw = request.getParameter("key");
try {
java.sql.Connection con;
Class.forName("com.mysql.jdbc.Driver");
con = DriverManager.getConnection("jdbc:mysql://localhost:3306/abcd", "root", "pass");
st = con.createStatement();
rs = st.executeQuery("SELECT DISTINCT t.tckid FROM ticket t WHERE t.tckid LIKE '%"+kw+"%'");
ArrayList<String> tickets = new ArrayList<String>();
while(rs.next()) {
String TCKTID = rs.getString(1);
tickets.add(TCKTID);
}
rs.close();
st.close();
con.close();
Gson gson = new Gson(); // this is giving me Gson cannot be resolved to a type
So of what I can gather, the Gson class didn't get imported at all. Is there a way to verify the successful import of the library? Or do I also need to use some import *** code on the top of the file?
The problem is that you are not importing the Gson package in your current JSP.
<%
Gson gson=new Gson();
%>
importing in JSP
<%# page import="com.google.gson.Gson" %>
but please keep in mind to avoid using scriptlets in your JSPMVC pattern to separate the server side with the client side actions/purpose. if you want to display values coming from the database you could always use JSTL and using different scopes(request scope,session scope, etc).

HTTP Status 500 - An exception occurred processing JSP page /webtech/login.jsp at line 6

Its basicaly a simple project to check login and password...
i did all the things possible to figure out the error...but i cannot somehow get over it...can anyone please help and provide solution for me.
i have a html file name Login.html and a jsp file named login.jsp
mysql port no. is 3306 with username and password sait
my tomcat port no. is 8801.
Login.html
<html>
<head></head>
<body>
<form action="login.jsp" method="post">
User name :<input type="text" name="usr" />
password :<input type="password" name="pwd" />
<input type="submit" />
</form>
</body>
</html>
login.jsp
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<%
String userid=request.getParameter("usr");
String pswd=request.getParameter("pwd");
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sait","root","root");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from login where username='"+userid+"'");
if(rs.next())
{
if(rs.getString("password").equals(pswd))
{
out.println("welcome"+userid);
}
else
{
out.println("Invalid password try again");
}
}
%>
i created a folder in C:\program files\apache software foundation\tomcat 7.0\webapps\ROOT\webtech**
and placed this 2 files **\webetech\Login.html and \webtech\login.jsp
i opened mysql and created a database named "sait"..then changed the database to "sait" using the command "use sait;" in mysql.
then i executed the following code
mysql>create table login(username varchar(10),password varchar(10));
>insert into login values("sait","sait");
>select * from login;
all executed successfully..
then i placed mysql-connector-java-5.1.26-bin in d destination C:\program files\apache software foundation\tomcat 7.0\lib\mysql-connector-java-5.1.26-bin.jar
now if i go to
http://localhost:8081/webtech/Login.html
i get the login page..but after i submit i get HTTP Status 500 - An exception occurred processing JSP page /webtech/login.jsp at line 6
Plssss help
I guess you might get NullpointerException . so just print the values of
String userid=request.getParameter("usr");
String pswd=request.getParameter("pwd");
out.print(userid + "" + pswd);
and check it out . Also its highly discourged to use the java codes in jsp pages . try using a servlet to establish JDBC
You should also add try/catch block your code to catch any exception if thrown ,
<%# page import ="java.sql.*" %>
<%# page import ="javax.sql.*" %>
<%
String userid=request.getParameter("usr");
String pswd=request.getParameter("pwd");
out.print(userid + "" + pswd);
try
{
Class.forName("com.mysql.jdbc.Driver");
java.sql.Connection con = DriverManager.getConnection("jdbc:mysql://localhost:3306/sait","root","root");
Statement st= con.createStatement();
ResultSet rs=st.executeQuery("select * from login where username='"+userid+"'");
while(rs.next())
{
if(rs.getString("password").equals(pswd))
{
out.println("welcome"+userid);
}
else
{
out.println("Invalid password try again");
}
}}
catch(Exception e)
{
out.print("Exception is " + e);
}
%>
If this didnt solve your issue . please post us the exception you are getting
Hope this helps !!

How to include external HTML in my .aspx page from a JSP+JSTL equivalent

I have this code in JSP+JSTL (Java) to insert some HTML into the page:
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<c:set var="caasPath" value="http://wwww.MyExampleSite.com/header/default"/>
<c:import url="${caasPath}/header?contentType=html"/>
I need to do the same but in ASP.NET Web Forms (.aspx file). I have tried with an .ascx but I don't know how to insert html directly in the page without using an iframe.
Here is an example from MSDN about how to convert the Java code and use Web Form Controls http://msdn.microsoft.com/en-us/library/aa478990.aspx
What is the Asp.Net (.aspx) equivalent to this code?
I have tried something like this, but it doesn't work (http://msdn.microsoft.com/en-us/library/sbz9etab%28v=vs.85%29.aspx)
<%# Register Src="http://wwww.MyExampleSite.com/header/default/header?contentType=html" TagName="header" Tagprefix="cta" %>
<cta:header ID="headerSection" runat="server"/>
Thanks a lot.
As far as I know there is not a nice 1-liner available to you. But you can create a method (lets call it 'dotnetImport') that makes a web request and call it like so:
<%= dotnetImport("http://wwww.ExampleSite.com/header/default/header?contentType=html"); %>
where dotnetImport is defined:
public string dotnetImport(string address) {
WebRequest request = WebRequest.Create (address);
request.Credentials = CredentialCache.DefaultCredentials;
HttpWebResponse response = (HttpWebResponse)request.GetResponse ();
Stream dataStream = response.GetResponseStream ();
StreamReader reader = new StreamReader (dataStream);
string responseFromServer = reader.ReadToEnd ();
// dispose the above... use best practices to avoid memory leaks.
return responseFromServer;
}
Disclaimer, I didn't test this, it is meant to be a starting point, not a ready-to-go-paste-in solution.
Enjoy

Spring MVC Request URLs in JSP

I am writing a web application using Spring MVC. I am using annotations for the controllers, etc. Everything is working fine, except when it comes to actual links in the application (form actions, <a> tags, etc.) Current, I have this (obviously abbreviated):
//In the controller
#RequestMapping(value="/admin/listPeople", method=RequestMethod.GET)
//In the JSP
Go to People List
When I directly enter the URL like "http://localhost:8080/MyApp/admin/listPeople", the page loads correctly. However, the link above does not work. It looses the application name "MyApp".
Does anyone know if there is a way to configure Spring to throw on the application name on there?
Let me know if you need to see any of my Spring configuration. I am using the standard dispatcher servlet with a view resolver, etc.
You need to prepend context path to your links.
// somewhere on the top of your JSP
<c:set var="contextPath" value="${pageContext.request.contextPath}"/>
...
Go to People List
The c:url tag will append the context path to your URL. For example:
<c:url value="/admin/listPeople"/>
Alternately, I prefer to use relative URLs as much as possible in my Spring MVC apps as well. So if the page is at /MyApp/index, the link <a href="admin/listPeople"> will take me to the listPeople page.
This also works if you are deeper in the URL hierarchy. You can use the .. to traverse back up a level. So on the page at/MyApp/admin/people/aPerson, using <a href="../listPeople"> will like back to the list page
I prefer to use BASE tag:
<base href="${pageContext.request.scheme}://${pageContext.request.serverName}:${pageContext.request.serverPort}${pageContext.request.contextPath}/" />
Then, all your links can be like:
Go to People List
As i have just been trying to find the answer to this question and this is the first google result.
This can be done now using the MvcUriComponentsBuilder
This is part of the 4.0 version of Spring MVC
http://docs.spring.io/spring/docs/current/javadoc-api/org/springframework/web/servlet/mvc/method/annotation/MvcUriComponentsBuilder.html
The method needed is fromMappingName
From the documentation :
Create a URL from the name of a Spring MVC controller method's request mapping.
The configured HandlerMethodMappingNamingStrategy determines the names of controller method request mappings at startup. By default all mappings are assigned a name based on the capital letters of the class name, followed by "#" as separator, and then the method name. For example "PC#getPerson" for a class named PersonController with method getPerson. In case the naming convention does not produce unique results, an explicit name may be assigned through the name attribute of the #RequestMapping annotation.
This is aimed primarily for use in view rendering technologies and EL expressions. The Spring URL tag library registers this method as a function called "mvcUrl".
For example, given this controller:
#RequestMapping("/people")
class PersonController {
#RequestMapping("/{id}")
public HttpEntity getPerson(#PathVariable String id) { ... }
}
A JSP can prepare a URL to the controller method as follows:
<%# taglib uri="http://www.springframework.org/tags" prefix="s" %>
Get Person
I usually configure tomcat to use context root of "/" or deploy the war as ROOT.war. Either way the war name does not become part of the URL.
You could use a servletRelativeAction. I'm not sure what versions this is available in (I'm using 4.0.x currently) and I haven't seen much documentation on this, but if you look at the code backing the spring form you can probably guess. Just make sure the path you pass it starts with a "/".
Example:
<form:form class="form-horizontal" name="form" servletRelativeAction="/j_spring_security_check" method="POST">
See org.springframework.web.servlet.tags.form.FormTag:
protected String resolveAction() throws JspException {
String action = getAction();
String servletRelativeAction = getServletRelativeAction();
if (StringUtils.hasText(action)) {
action = getDisplayString(evaluate(ACTION_ATTRIBUTE, action));
return processAction(action);
}
else if (StringUtils.hasText(servletRelativeAction)) {
String pathToServlet = getRequestContext().getPathToServlet();
if (servletRelativeAction.startsWith("/") && !servletRelativeAction.startsWith(getRequestContext().getContextPath())) {
servletRelativeAction = pathToServlet + servletRelativeAction;
}
servletRelativeAction = getDisplayString(evaluate(ACTION_ATTRIBUTE, servletRelativeAction));
return processAction(servletRelativeAction);
}
else {
String requestUri = getRequestContext().getRequestUri();
ServletResponse response = this.pageContext.getResponse();
if (response instanceof HttpServletResponse) {
requestUri = ((HttpServletResponse) response).encodeURL(requestUri);
String queryString = getRequestContext().getQueryString();
if (StringUtils.hasText(queryString)) {
requestUri += "?" + HtmlUtils.htmlEscape(queryString);
}
}
if (StringUtils.hasText(requestUri)) {
return processAction(requestUri);
}
else {
throw new IllegalArgumentException("Attribute 'action' is required. " +
"Attempted to resolve against current request URI but request URI was null.");
}
}
}
Since it's been some years I thought I'd chip in for others looking for this. If you are using annotations and have a controller action like this for instance:
#RequestMapping("/new") //<--- relative url
public ModelAndView newConsultant() {
ModelAndView mv = new ModelAndView("new_consultant");
try {
List<Consultant> list = ConsultantDAO.getConsultants();
mv.addObject("consultants", list);
} catch (Exception e) {
e.printStackTrace();
}
return mv;
}
in your .jsp (view) you add this directive
<%#taglib uri="http://www.springframework.org/tags" prefix="spring"%>
and simply use
<spring:url value="/new" var="url" htmlEscape="true"/>
New consultant
where
value's value should match #RequestMapping's argument in the controller action and
var's value is the name of the variable you use for href
HIH