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>
Related
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.
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
Hi I am facing two problem
HTTP status 404 (!important)
When I select Run on server on one particular project 'Two different dynamic projects executes' .
HTTP Status 404
message /RealTimeCurValue/RTCurrValue.do
description The requested resource is not available.
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<display-name>Pavan</display-name>
<welcome-file-list>
<welcome-file>RTCurrValue.jsp</welcome-file>
</welcome-file-list>
<servlet>
<servlet-name>RTCV</servlet-name>
<servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class>
<init-param>
<param-name>ContextConfigLocation</param-name>
<param-value>/WEB-INF/classes/Spring/RTCV-servlet.xml</param-value>
</init-param>
<load-on-startup>2</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>RTCV</servlet-name>
<url-pattern>*.to</url-pattern>
</servlet-mapping>
RTCV-servlet.xml
<context:component-scan base-package="com.fact.mvcApp" />
<bean id="RTC"
class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name="prefix" value="/" />
<property name="suffix" value=".jsp" />
</bean>
RealTimeCurrValueController.java
#Component
#RequestMapping("/")
public class RealTimeCurrValueController
{
#Autowired
private RealTimeCurrValueService service;
public RealTimeCurrValueController()
{
System.out.println(this.getClass().getSimpleName()+ "Created");
}
#RequestMapping(value="/RTCurrValue.do", method = RequestMethod.POST)
public ModelAndView realTimeCurrValueController( #ModelAttribute RealTimeCurrValueDTO dto , HttpServletRequest req)
{
System.out.println("RealTimeCurrValue Controller Started ");
CbBtc rtvcDTO = null;
System.out.println(dto);
if(dto!= null)
{
String cValue = dto.getCryptoCurrency();
System.out.println("cValue-----" +cValue);
try
{
rtvcDTO = service.rtcvService(cValue);
}
catch (IOException e)
{
e.printStackTrace();
}
if(rtvcDTO != null)
{
HttpSession session =req.getSession();
System.out.println(" Success");
return new ModelAndView("Welcome.jsp" , "value" , rtvcDTO.getAmount() );
}
}
System.out.println("RealTimeCurrValue Controller Ended ");
return null;
}
}
RTCurrValue.jsp
<form action="RTCurrValue.do" method="post">
Currency: <input type="text" name="currency" />
<input type= "submit" value="OK">
</form>
Your form action is relative to the current page i.e. /RTCurrValue, so the url used to post the form is "/RTCurrValue/RTCurrValue.do" which is giving the 404.
If your web app is running as the ROOT web app then try adding a / to the form action. action="/RTCurrValue.do".
If your web app is running in some other context then add the context to the action. action="/someContext/RTCurrValue.do"
Or better construct the URL using the standard tags.
<c:url var="formAction" value="/RTCurrValue.do"/>
<form action="${formAction}" method="post">
I want to redirect to a another jsp page.in Spring MVC But I get HTTP Status 404 - /registration.jsp error.all i want to do is to open page. register new person page or add new product page from the home page
the path or project hierarchy:
I dont want to use JSTL or tag's. What is the best way to do this?
I tried this on my JSP page:
<ul class="nav child_menu" style="display: none"> <li>User Registartion
</li>
<li><a href="${pageContext.request.contextPath}/grcon?path=usermang">User Management</></li></ul>
And my controller:
#RequestMapping(value ="/grcon/{path}" ,method = RequestMethod.GET)
public ModelAndView getGrcon(#PathParam(value = "path") String path)
{
ModelAndView modegeron = null;
if (path != null && path.equals("register")) {
modegeron = new ModelAndView("registeruser");
} else if (path != null && path.equals("usermang"))
{
modegeron = new ModelAndView("manageuser");
} else {
modegeron = new ModelAndView("index");
}
return modegeron;
}
}
spring-dispatcher-servlet.xml
<context:component-scan base-package="recon.controller" />
<!-- viewResolver tell which viewResolver to use it tell the location of
the view in the project -->
<bean id="viewResolver" class="org.springframework.web.servlet.view.InternalResourceViewResolver" >
<property name="prefix">
<value>/WEB-INF/views/</value>
</property>
<property name="suffix">
<value>.jsp</value>
</property>
</bean>
<mvc:resources location="/resoures/**" mapping="/resoures/"/>
<mvc:default-servlet-handler/>
<mvc:annotation-driven/>
</beans>
web.xml
<servlet>
<servlet-name>spring-dispatcher</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>spring-dispatcher</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>15</session-timeout>
<tracking-mode>COOKIE</tracking-mode>
</session-config>
HTTP Message
HTTP Status 400 - Required String parameter 'path' is not present
type Status report
message Required String parameter 'path' is not present
description The request sent by the client was syntactically incorrect.
Apache Tomcat/7.0.67
You can either pick request parameters or url template variables in your controller or jsp.To use url template variables replace #PathParam(value="path") with #PathVariable(value = "path").
In your jsp replace the link url with
href="${pageContext.request.contextPath}/grcon/register and href="${pageContext.request.contextPath}/grcon/usermang
To use request parameters replace #PathParam(value = "path") with #RequestParam(value = "path"). Then mantain your jsp url links as they already use request parameters
NB. The PathParam annoation is not part of Spring MVC. Its a JAX-RS annotation for use with JEE standard
After lots for reading i notice i was not doing the right thing the below code work for me
Controller
#RequestMapping(value ="/register" ,method = RequestMethod.GET)
public ModelAndView getRegister()
{
ModelAndView modelregister = new ModelAndView();
modelregister.setViewName("registeruser");
modelregister.addObject("Registration", "info");
return modelregister;
}
#RequestMapping(value ="/manageuser" ,method = RequestMethod.GET)
public ModelAndView getManageUser()
{
ModelAndView modelManageUser = new ModelAndView();
modelManageUser.setViewName("manageuser");
modelManageUser.addObject("User Records", "records");
return modelManageUser;
}
JSP
<ul class="nav child_menu" style="display: none">
<li>User Registration</li>
<li>User Management</li>
</ul>
I have a jsp file that provides the login screen, upon submitting the form the control has to go to a servlet. Now, how can i save the values in the form to a model(Bean classs) and get them use in the controller.?
I am not using any frameworks like struts, spring, etc.
I used the following code but getting the error
java.lang.NoClassDefFoundError: bean/LoginBean
My code is:
index.jsp:
<form name="signin" method="post" action="LoginServlet">
<table>
<tr><td><font>USERNAME</font></td><td><input type="text" name="signin_uname" /></td></tr>
<tr><td><font>PASSWORD</font></td><td><input type="password" name="signin_pwd" /></td></tr>
<tr><td><input type="reset" value="RESET" /></td><td><input type="submit" value="LOGIN" /></td></tr>
</table>
</form>
LoginServlet.java
#Override
protected void doPost(HttpServletRequest request, HttpServletResponse response)
throws ServletException, IOException {
processRequest(request, response);
HttpSession session=request.getSession();
System.out.println(session);
try {
LoginBean login=new LoginBean();
login.setSignin_pwd("raviteja");
login.setSignin_uname("raviteja");
System.out.println(login.getSignin_uname());
System.out.println(login.getSignin_pwd());
} finally {
}
response.sendRedirect("");
}
LoginBean.java
public class LoginBean implements Serializable {
String signin_uname,signin_pwd;
public LoginBean() {
}
public String getSignin_pwd() {
return signin_pwd;
}
public void setSignin_pwd(String signin_pwd) {
this.signin_pwd = signin_pwd;
}
public String getSignin_uname() {
return signin_uname;
}
public void setSignin_uname(String signin_uname) {
this.signin_uname = signin_uname;
}
}
web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app version="2.5" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd">
<servlet>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>servlets.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>LoginServlet</servlet-name>
<url-pattern>/LoginServlet</url-pattern>
</servlet-mapping>
<session-config>
<session-timeout>
30
</session-timeout>
</session-config>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
1 Add Spring libraries to your project and map DispatherServlet in web.xml to process /LoginServlet
2 Create bean (same names for form and bean fields):
public class LoginData {
private String signin_uname;
private String signin_pwd;
// Getters and setters
}
3 Create controller:
#Controller
public class LoginController {
#RequestMapping(value = "/LoginServlet", method = RequestMethod.POST)
public String postLoginData(#ModelAttribute LoginData loginData) {
// All data from form will be at your model attribute bean. It will also will
// be putted at request
String userName = logigData.getSignin_uname();
return "loginResult.jsp";
}
}
Your code should run properly. You've a problem with the classpath. JVM isn't able to find the class LoginBean at runtime.
By the way what you want to output to the console? If you want to print the entered data user then correct your code with the following:
LoginBean login = new LoginBean();
String username = request.getParameter("signin_uname");
String password = request.getParameter("signin_pwd");
login.setSignin_uname(username);
login.setSignin_pwd(password);
But error shouldn't be if you correctly have created a project with your code.