Jquery ajax call to invoke spring controller? - java

I have below config in web.xml
<servlet>
<servlet-name>mvc-dispatcher</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value>classpath:spring/mvc-dispatcher-servlet.xml</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>mvc-dispatcher</servlet-name>
<url-pattern>*.do</url-pattern>
</servlet-mapping>
I have controller as below.
#Controller
public class SomeController {
#RequestMapping(value = "/getData", method = RequestMethod.GET)
public ModelAndView showExtendedUi(#RequestParam("geo") String geo, #RequestParam("tab") String tab, #RequestParam("gid") String gid, HttpServletResponse response) {
//logic
}
}
Now how can i specify URL in jquery ajax call?
$.ajax({
type: "GET",
url: "getData.do",
dataType: "json",
success: function(responseJson) {
alert("json"+responseJson);
},
error: function(xhr, status, error) {
alert('Failed to get details: ' + error);
}
});

From looking at the code above, you should just be able to go to the following url (assuming 8080 port as default Tomcat port).
http://localhost:8080/getData.do?geo=1&tab=1&gid=1
This should show you in a browser the JSON you require. If the JSON appears on the page here, just do $.getJSON() from jQuery as it has built in methods for pulling back JSON. You can see the documentation on this method here.

Related

Spring framework custom 404 error specific case

I am able to get the Custom 404 Error Page if I include webApp root directory myweb in the URL path -
http://localhost/myweb/users/david
I added the following entry in web.xml to get custom 404 page -
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/pageNotFound.jsp</location>
</error-page>
However, I am still getting Spring default 404 Error Page when I hit the following URL -
http://localhost/users/david
Why it is not working without webApp root directory in the URL path? Is there any way to get same custom 404 Not Found Page for this as well?
EDIT:
My relevant web.xml code -
<context-param>
<param-name>webAppRootKey</param-name>
<param-value>myweb</param-value>
</context-param>
<context-param>
<param-name>contextClass</param-name>
<param-value>org.springframework.web.context.support.XmlWebApplicationContext</param-value>
</context-param>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext.xml</param-value>
</context-param>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<listener>
<listener-class>org.springframework.web.context.request.RequestContextListener</listener-class>
</listener>
<listener>
<listener-class>com.gridpoint.energy.web.common.servlet.listeners.RequestContextInitializer</listener-class>
</listener>
<listener>
<listener-class>org.springframework.security.web.session.HttpSessionEventPublisher</listener-class>
</listener>
<!-- Dispatch Servlet -->
<servlet>
<servlet-name>services-servlet</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>contextConfigLocation</param-name>
<param-value></param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>services-servlet</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>services-servlet</servlet-name>
<url-pattern>/applications/*</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>services-servlet</servlet-name>
<url-pattern>/healthCheck</url-pattern>
</servlet-mapping>
<error-page>
<error-code>404</error-code>
<location>/WEB-INF/jsp/pageNotFound.jsp</location>
</error-page>
In my case I created customer controller ErrorController using Spring mvc 4.
I set next configuration web.xml.
<error-page>
<location>/errors</location>
</error-page>
Next. I created the controller. I shared the class. (ModelAndView is the path of my .jsp (exception/errorPage)).
#Controller
public class ErrorController {
#RequestMapping(value = "errors", method = RequestMethod.GET)
public ModelAndView renderErrorPage(HttpServletRequest httpRequest, ModelMap model) {
ModelAndView errorPage = new ModelAndView("exception/errorPage");
String errorMsg = "";
String customerMsg = "";
int httpErrorCode = getErrorCode(httpRequest);
switch (httpErrorCode) {
case 400: {
errorMsg = "Http Error Code: 400. Bad Request";
customerMsg = "";
break;
}
case 401: {
errorMsg = "Http Error Code: 401. Unauthorized";
customerMsg = "";
break;
}
case 403: {
errorMsg = "Http Error Code: 403. access denied";
customerMsg = "";
break;
}
case 404: {
errorMsg = "Http Error Code: 404. Resource not found";
customerMsg = "";
break;
}
case 500: {
errorMsg = "Http Error Code: 500. Internal Server Error";
customerMsg = "";
break;
}
}
errorPage.addObject("errorMsg", errorMsg);
errorPage.addObject("customerMsg", customerMsg);
return errorPage;
}
private int getErrorCode(HttpServletRequest httpRequest) {
return (Integer) httpRequest
.getAttribute("javax.servlet.error.status_code");
}
}
Shared the basic errorPage.jsp
<!DOCTYPE html>
<html lang="es">
<head>
<title>Error</title>
</head>
<body>
<table>
<tr>
<td>
<h1>${errorMsg}</h1>
</td>
</tr>
<tr>
<td>
<h1>${customerMsg}</h1>
</td>
</tr>
<tr>
</tr>
</table>
</body>
</html>
I hope this example to help you.

Can't Post a message using Facebook's API, using MVC and Java

I was trying to use the facebook API to post a message to share a page I am making as a project to learn to use APIs.
And I'm running into the following problem.
I tried to post and I was redirected to facebook where I accepted a bunch of permisions and then I was redirected to the url "MyUrl/oauth2callback/Facebook?code=A very large code" and got a 404 Not Found error.
I'm not sure what the problem is and I have been trying to find it for the past 3 days, here is the resource I am using:
import org.restlet.resource.ClientResource;
public class FacebookPostResource {
private String uri = "https://graph.facebook.com/me/feed";
private String access_token = null;
public FacebookPostResource(String access_token) {
this.access_token = access_token;
}
public boolean publishPost(String message){
String normalizedMessage=message.replace(' ', '+');
ClientResource cr=new ClientResource(uri+"?access_token="+access_token);
cr.post("message="+normalizedMessage);
return true;
}
}
Here is the Controller:
public class FacebookPostController extends HttpServlet {
/**
*
*/
private static final long serialVersionUID = -6818025976353856770L;
private static final Logger log =
Logger.getLogger(FacebookPostController.class.getName());
public void doGet(HttpServletRequest req, HttpServletResponse resp) throws
IOException,ServletException {
String accessToken=(String)req.getSession().getAttribute("Facebook-
token");
if(accessToken!=null && !"".equals(accessToken)){
FacebookPostResource fbResource=new
FacebookPostResource(accessToken);
fbResource.publishPost(req.getParameter("message"));
req.getRequestDispatcher("/").forward(req,resp);
}else{
log.info("Trying to acces to Facebook without an acces token,
redirecting to OAuth servlet");
req.getRequestDispatcher("/AuthController/Facebook").forward(req,resp);
}
}
public void doPost(HttpServletRequest req, HttpServletResponse resp) throws
IOException,ServletException {
doGet(req,resp);
}
}
Here is My scope configuration:
{
"Facebook":{
"tokenUrl":"https://graph.facebook.com/v2.8/oauth/access_token",
"clientId":"MyID",
"clientSecret":"MySecret" ,
"authorizationFormUrl":"https://www.facebook.com/v2.8/dialog/oauth",
"scopes":["user_posts", "user_friends"]
}
}
Here is the JSP where I write the post:
<c:if test='${empty sessionScope["Facebook-token"]}'>
<c:redirect url = "/AuthController/Facebook"/>
</c:if>
<h1>Publicar Post en Facebook</h1>
<div class="container">
<p class="message"></p>
<form action="/facebookPostCreation" method="post">
Mensaje: <textarea name="message"></textarea>
<br>
<div class="bottom_links">
<button type="submit" class="button">Publicar en
Facebook</button>
<button type="button"
onClick="javascript:window.location.href='index.html'"
class="button">Cancel</button>
</div>
</form>
</div>
And finally here is my web.xml
...
<servlet>
<servlet-name>FacebookPostCreation</servlet-name>
<servlet-class>aiss.controller.FacebookPostController</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>FacebookPostCreation</servlet-name>
<url-pattern>/facebookPostCreation</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>FacebookAuthController</display-name>
<servlet-name>FacebookAuthController</servlet-name>
<servlet-class>aiss.controller.oauth.GenericAuthController</servlet-class>
<init-param>
<param-name>provider</param-name>
<param-value>Facebook</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FacebookAuthController</servlet-name>
<url-pattern>/AuthController/Facebook</url-pattern>
</servlet-mapping>
<servlet>
<description></description>
<display-name>FacebookOAuth2Callback</display-name>
<servlet-name>FacebookOAuth2Callback</servlet-name>
<servlet-class>aiss.controller.oauth.OAuth2Callback</servlet-class>
<init-param>
<param-name>provider</param-name>
<param-value>Facebook</param-value>
</init-param>
<init-param>
<param-name>onSuccess</param-name>
<param-value>redirect:/facebookFriendsListing</param-value>
</init-param>
</servlet>
<servlet-mapping>
<servlet-name>FacebookOAuth2Callback</servlet-name>
<url-pattern>/OAuth2Callback/Facebook</url-pattern>
</servlet-mapping>
Try using my code
https://github.com/OswaldoRosalesA/FacebookAPIJava.git
Use Debuger.java to Test.
I use the Graph API
https://developers.facebook.com/docs/graph-api

Url changed in spring

I have a from and when the form is filled and submitted I wanted the request to be http://localhost:8080/restroo/admin/adminLog but it gives http://localhost:808/adminLogand getting 404 error. I don't know why I am having this problem and actually I was having problem in using two controllers in spring.
web.xml
<servlet>
<servlet-name>spring</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-
class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
I have spring-servlet.xml
admin.jsp
<form method="post" action="/adminLog" modelAttribute="adminUser">
First Name: <input type = "text" name = "userName">
<br />
password <input type = "password" name = "password" />
<input type = "submit" value = "Submit" />
</form>
AdminPageController.java
#Controller
#RequestMapping("/admin/*")
public class AdminPageController {
#Autowired
AdminUser adminUser;
#Autowired
MenuItems menuItems;
#Autowired
MenuItemsDao menuItemsDao;
#Autowired
AdminLoginDao adminLoginDao;
#RequestMapping(value="", method=RequestMethod.GET)
public ModelAndView addMenuItems(#ModelAttribute MenuItems menuItems){
// if(menuItems != null){
// menuItemsDao.addItems(menuItems);
// }
return new ModelAndView("admin");
}
#RequestMapping(value="/adminLog", method=RequestMethod.POST)
public ModelAndView adminLogin(#ModelAttribute("adminUser") AdminUser ad){
List<AdminUser> adminUser = adminLoginDao.adminLogin();
int len = adminUser.size();
for(int i=1;i<=len;i++){
String userN = adminUser.get(i).getUserName();
String pass = adminUser.get(i).getPassword();
if(userN.equals(ad.getUserName()) && (pass.equals(ad.getPassword()))){
return new ModelAndView("adminLogin");
}
}
return new ModelAndView("admin");
}
}
You are using Internal Resource View Resolver It is not able fetch view Not In Web-INF Floader.
Find This http://www.baeldung.com/spring-mvc-view-resolver-tutorial.
You have to change servlet mapping by adding a prefix for the API of the whole app:
<servlet-mapping>
<servlet-name>spring</servlet-name>
<url-pattern>/restroo</url-pattern>
</servlet-mapping>

Passing value from a jsp button click to a servlet

ininI am bit new to jsp and servlet. I need to pass a value to a servlet on a button click. below I have mentioned my code.
web.xml
<servlet>
<servlet-name>Login</servlet-name>
<servlet-class>org.wso2.carbon.identity.application.authentication.endpoint.oauth2.OAuth2Login</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
test.jsp
function ok() {
$.ajax({
url: "/login",
data: 'test=' +'test',
type: "GET",
async: false,
success: function (data) {
}
});
}
below is my html code in test.jsp
<button id="ok" class="btn btn-primary btn-large" onclick="ok()">OK</button>
The servelet
public class OAuth2Login extends HttpServlet {
protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException,
IOException {
System.out.print("========do get fires===========");
}
}
But when my test.jsp is loading it invokes the doget() of the servlet. But at the button click it does not. I dont need to invoke the servlet at the page load. But I need it on the button click. Help me to solve this out. Sorry for the ignorance. :)
I think in web.xml /test.jsp this is wrong in place of /test.jsp you can give yours servlet name like
<servlet-mapping>
<servlet-name>Login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
and later on button click which is in test.jsp you can call ajax function and call get method of servlet
function ok() {
$.ajax({
url: "/login",
data: 'test=' +'test',
type: "GET",
async: false,
success: function (data) {
}
});
}
Write your servlet mapping url in url attribute:
function myFun() {
var requestPath = "<%=request.getContextPath()%>";
$.ajax({
url: requestPath+"/login";
data: {"data1":"value1", "data2": "value2"}
type: "GET",
async: false,
success: function (data) {
}
});
}

Cannot send ajax post request to Servlet

Here is my code.,
Javascript
$(document).ready(function()
{
$("button").click(function(){
$.post("AjaxpostloginServlet.java",
{
name:"kevin",
pass:"Duckburg"
});
});
});
Java servlet
package com.iappuniverse.ajaxpostlogin;
import java.io.IOException;
import javax.servlet.http.*;
#SuppressWarnings("serial")
public class AjaxpostloginServlet extends HttpServlet
{
public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException
{
String name=req.getParameter("name");
System.out.println(name);
}
}
The name here in the servlet doesn't get printed in the console. Trying to send data to the server using ajax .post(), but cannot make the servlet linked to the ajax .post() call run.
Change your web.xml to something like the below
<?xml version="1.0" encoding="ISO-8859-1" ?>
<web-app xmlns="http://java.sun.com/xml/ns/j2ee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/j2ee http://java.sun.com/xml/ns/j2ee/web-app_2_4.xsd"
version="2.4">
<display-name>Application</display-name>
<description>
Description Example.
</description>
<servlet>
<servlet-name>login</servlet-name>
<servlet-class>AjaxpostloginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>login</servlet-name>
<url-pattern>/login</url-pattern>
</servlet-mapping>
</web-app>
lets take it a step further and change your servlet post method
public void doPost(HttpServletRequest req, HttpServletResponse resp)throws IOException {
String name=req.getParameter("name");
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(name);
}
finally change the url of the ajax call and use a callback function.
$(document).ready(function() {
$("button").click(function() {
$.post("login",{
name:"kevin",
pass:"Duckburg"
}).done(function( data ) {
alert( "name: " + data );
})
});
});
Disclaimer:
I haven't test it!

Categories

Resources