Spring Security 3.1.3 Issues - java

I am using Spring Security 3.1.3.RELEASE in my maven pom because the book am reading is 2013 and that is what they used and have the following code snippets:
// AdminController
#Controller
#RequestMapping("/admin")
public class AdminController {
#RequestMapping(method=RequestMethod.POST, value="/movies")
#ResponseBody
public String createMovie(#RequestBody String movie) {
System.out.println("Adding movie!! "+movie);
return "created";
}
}
// LoginController
#Controller
#RequestMapping("")
public class LoginController {
#RequestMapping(method= {RequestMethod.GET, RequestMethod.POST}, value="/custom_login")
public String showLogin() {
return "login";
}
}
// web.xml
<web-app>
<display-name>Archetype Created Web Application</display-name>
<context-param>
<param-name>contextConfigLocation</param-name>
<param-value>/WEB-INF/applicationContext-security.xml</param-value>
</context-param>
<filter>
<filter-name>springSecurityFilterChain</filter-name>
<filter-class>org.springframework.web.filter.DelegatingFilterProxy</filter-class>
</filter>
<filter-mapping>
<filter-name>springSecurityFilterChain</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<listener>
<listener-class>org.springframework.web.context.ContextLoaderListener</listener-class>
</listener>
<servlet>
<servlet-name>terrormovies</servlet-name>
<servlet-class> org.springframework.web.servlet.DispatcherServlet </servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>terrormovies</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
// Spring security Config :: applicationContext-security.xml
<security:http auto-config="true">
<security:intercept-url pattern="/admin/**/*" access="ROLE_ADMIN" />
<security:form-login login-page="/custom_login" username-parameter="user_param" password-parameter="pass_param"/>
</security:http>
<security:authentication-manager>
<security:authentication-provider>
<security:user-service>
<security:user authorities="ROLE_ADMIN" name="admin" password="admin" />
</security:user-service>
</security:authentication-provider>
</security:authentication-manager>
//login.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1" pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Terror movies</title>
</head>
<body>
<form action="/j_spring_security_check" method="POST">
Username<input type="text" name="user_param"/><br/>
Password<input type="password" name="pass_param"/><br/>
<input type="submit" value="Login"/>
</form>
</body>
<% if(request.getParameter("error") != null){
out.println("ERROR LOGIN");
}
%>
</html>
When I start my application I get the login page with the form alright. I enter admin/admin as username/password respectively. When i click on the login button I get this error page saying:
Problem accessing /admin/movies. Reason:
Request method 'GET' not supported
Powered by Jetty://
instead of going to the method createMovie(#RequestBody String movie) in the
AdminController.
The address of this error page is :: http://localhost:8080/admin/movies
The LoginController and AdminController are in the same package.
What am I missing here?
Updated
In the form action:: <form action="/j_spring_security_check" method="POST">,
where does "/j_spring_security_check"` leads to? I think that is where the problem is. Am beginner in Spring Security so I can't figure it out now. I did a search but not any good answer.

The error response message you are receiving tells you exactly what the problem is:
When i click on the login button i get this error page saying::
Problem accessing /admin/movies. Reason:
Request method 'GET' not supported
Powered by Jetty://
And in your controller you have set this method:
#Controller
#RequestMapping("/admin")
public class AdminController {
#RequestMapping(method=RequestMethod.POST, value="/movies")
#ResponseBody
public String createMovie(#RequestBody String movie) {
System.out.println("Adding movie!! "+movie);
return "created";
}
}
And just as the message says, the /admin/movies method is mapped just for POST requests, so a GET request which is what is generated on redirection from the login success cannot be handled.
So here the trouble is not really the spring-security config, the problem is just that after login you are making a request to a request-mapping annotated method which does not support GET requests.
To solve it you could just configure this method into the existing AdminController:
#RequestMapping(method=RequestMethod.GET, value="/movies")
public String createMovieForm() {
return "createMovieForm";
}
And create a jsp with a form which points to the POST mapped controller method:
<form action="/admin/movies" method="POST">
Movie<input type="text" name="movie"/><br/>
<input type="submit" value="Login"/>
</form>
I would be easier too if you delete the #RequestBody annotation in the POST method, so finally the AdminController should end like this:
#Controller
#RequestMapping("/admin")
public class AdminController {
#RequestMapping(method=RequestMethod.POST, value="/movies")
#ResponseBody
public String createMovie(String movie) {
System.out.println("Adding movie!! "+movie);
return "created";
}
#RequestMapping(method=RequestMethod.GET, value="/movies")
public String createMovieForm() {
return "createMovieForm";
}
}

Related

redirected page is not being displayed with spring-mvc ajax request

In my Spring MVC application, I want to redirect my page from index.jsp page to final.jsp page using AJAX. But the redirected page (final.jsp) is not being displayed when I click the Redirect Page button in my application. I have used System.out.println("inside /redirect"); and System.out.println("inside /finalPage"); inside my Java code to check whether the AJAX GET request is being received at server or not, and only inside /redirect is being printed which which means that the /finalPage is not being called. Moreover, my browser's console does not show any error. So please tell, what can be the problem and where is that problem? I have posted my complete code below:
WebController.java
package com.tutorialspoint;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
#Controller
public class WebController {
#RequestMapping(value = "/index", method = RequestMethod.GET)
public String index() {
return "index";
}
#RequestMapping(value = "/redirect", method = RequestMethod.GET)
public String redirect() {
System.out.println("inside /redirect");
return "redirect:/finalPage";
}
#RequestMapping(value = "/finalPage", method = RequestMethod.GET)
public String finalPage() {
System.out.println("inside /finalPage");
return "final";
}
}
index.jsp
<%#taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring Page Redirection</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
</head>
<body>
<h2>Spring Page Redirection</h2>
<p>Click below button to redirect the result to new page</p>
<button onClick="redFun()">Redirect Page</button>
<script>
function redFun() {
$.ajax({
type : "GET",
url : "/HelloWeb/redirect"
});
}
</script>
</body>
</html>
final.jsp
<%#taglib uri = "http://www.springframework.org/tags/form" prefix = "form"%>
<html>
<head>
<title>Spring Page Redirection</title>
</head>
<body>
<h2>Redirected Page</h2>
</body>
</html>
web.xml:
<web-app id = "WebApp_ID" version = "2.4"
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">
<display-name>Spring MVC Application</display-name>
<servlet>
<servlet-name>HelloWeb</servlet-name>
<servlet-class>
org.springframework.web.servlet.DispatcherServlet
</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>HelloWeb</servlet-name>
<url-pattern>/</url-pattern>
</servlet-mapping>
</web-app>
HelloWeb-servlet.xml
<beans xmlns = "http://www.springframework.org/schema/beans"
xmlns:context = "http://www.springframework.org/schema/context"
xmlns:xsi = "http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation = "
http://www.springframework.org/schema/beans
http://www.springframework.org/schema/beans/spring-beans-3.0.xsd
http://www.springframework.org/schema/context
http://www.springframework.org/schema/context/spring-context-3.0.xsd">
<context:component-scan base-package = "com.tutorialspoint" />
<bean class = "org.springframework.web.servlet.view.InternalResourceViewResolver">
<property name = "prefix" value = "/WEB-INF/jsp/" />
<property name = "suffix" value = ".jsp" />
</bean>
</beans>
Your browser is not following the redirect because you're using ajax to hit your controller's redirect method. You have two options:
Don't use ajax at all, and let your browser respond naturally to the redirect status.
function redFun() {
window.location = "/HelloWeb/redirect";
}
Look for an HTTP 302 response to the XmlHttpRequest, and change window.location to the value of the Location header in the response:
function redFun() {
$.ajax({
type: "GET",
url: "/HelloWeb/redirect"
}).fail(function (jqXHR, status, err) {
if (jqXHR.status === 302) {
window.location = jqXHR.getResponseHeader('Location');
}
});
}

data from jsp to dto is not transvere

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">

Skip Java Filter based on Condition

I have looked in to How to skip a filter in the filter chain in java and followed the solution but this didn't help.
I have three filters in my web.xml. Struts filter, custom filter and IAM Agent filter in this order. I want to skip IAM filter based on some condition. I do not have control on IAM filter its external peace of code. So when ever the front end parameter says that the usertype is internal I need to call IAM agent filter else I need to skip this filter.
Web.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
id="WebApp_ID"
version="2.5">
<display-name>App</display-name>
<!-- Struts2 Filter -->
<filter>
<filter-name>struts2</filter-name>
<filter-class>org.apache.struts2.dispatcher.FilterDispatcher</filter-class>
</filter>
<filter-mapping>
<filter-name>struts2</filter-name>
<url-pattern>*.action</url-pattern>
</filter-mapping>
<!-- Custom App Filter for Handling Internal And External User-->
<filter>
<filter-name>UserType</filter-name>
<filter-class>com.App.web.filter.LoginFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>UserType</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<!-- IAM Filter for Internal Users only-->
<filter>
<filter-name>Agent</filter-name>
<filter-class>com.sun.identity.agents.filter.AmAgentFilter</filter-class>
</filter>
<filter-mapping>
<filter-name>Agent</filter-name>
<url-pattern>/*</url-pattern>
</filter-mapping>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<listener>
<listener-class>org.apache.tiles.web.startup.TilesListener</listener-class>
</listener>
<listener>
<listener-class>com.App.init.InitListener</listener-class>
</listener>
<context-param>
<param-name>org.apache.tiles.impl.BasicTilesContainer.DEFINITIONS_CONFIG</param-name>
<param-value>/WEB-INF/tiles.xml</param-value>
</context-param>
<!-- Web Service -->
<servlet>
<servlet-name>EventManagementWS</servlet-name>
<servlet-class>com.App.eventmanagement.ws.EventManagementWS</servlet-class>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>EventManagementWS</servlet-name>
<url-pattern>/EventManagementWS</url-pattern>
</servlet-mapping>
<resource-ref>
<res-ref-name>url/ConfigProperty</res-ref-name>
<res-type>java.net.URL</res-type>
<res-auth>Container</res-auth>
<res-sharing-scope>Shareable</res-sharing-scope>
</resource-ref>
I am using RequestDispatcher#forward(), but I not getting anything in my index.jsp page output, just a blank page. The css files are giving 404 error. When I was using Struts tag it gave error
Uncaught exception created in one of the service methods of the servlet /index.jsp in application App. Exception created: The Struts dispatcher cannot be found. This is usually caused by using Struts tags without the associated filter. Struts tags are only usable when the request has passed through its servlet filter, which initializes the Struts dispatcher needed for this tag.
So i removed S tag and used hard coding, but now I am getting 404 error in all css which i was trying to include.
I feel as if the forward is not working fine.
Java Filter Code:
package com.App.web.filter;
import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import org.apache.commons.lang.StringUtils;
import com.App.constant.Constant;
import com.App.init.WIMSInitListener;
import com.App.log.WIMSMessageLogger;
public class LoginFilter implements Filter{
FilterConfig _filterConfig = null;
#Override
public void destroy(){
// TODO Auto-generated method stub
}
#Override
public void doFilter(ServletRequest request, ServletResponse response,
FilterChain filterChain) throws IOException, ServletException{
// Check IAM is enabled
if (InitListener.isIAMEnabled()){
HttpSession session = httpRequest.getSession();
String userType = (String) session.getAttribute(Constant.USER_TYPE);
if(userType == null || "".equals(userType)){
MessageLogger.putMessageLog("User type is null : First Request" + userType, getClass());
userType = request.getParameter(Constant.USER_TYPE);
session.setAttribute(Constant.USER_TYPE, userType);
request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() +
StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()))
.forward(request, response);
}
if("external".equals(userType)){
MessageLogger.putMessageLog("External User" + userType, getClass());
request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() +
StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()))
.forward(request, response);
}
else if("internal".equals(userType)){
MessageLogger.putMessageLog("Internal User" + userType, getClass());
//IAM Filter com.sun.identity.agents.filter.AmAgentFilter
filterChain.doFilter(request, response);
}
}
//Its always External User
else{
MessageLogger.putMessageLog("User IAM Not Enabled", getClass());
request.getRequestDispatcher(((HttpServletRequest)request).getServletPath() +
StringUtils.defaultString(((HttpServletRequest)request).getPathInfo()) )
.forward(request, response);
}
}
#Override
public void init(FilterConfig filterConfig) throws ServletException{
this._filterConfig = filterConfig;
}
}
Index.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>App</title>
<link rel="stylesheet" type="text/css" media="screen"
href="/App/css/common.css" />
<link rel="stylesheet" type="text/css" media="screen"
href="/App/css/rcorp.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/style.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/rcorp.css" />
<link rel="stylesheet" type="text/css" media="all"
href="/App/css/default.css" />
<script type="text/javascript">
function selectUserType(){
var frm = document.forms["UserTypeForm"];
if(document.getElementById("userTypeInternal").checked){
//frm.action='<s:url action="loginAction.action?usertype=internal" namespace="" />';
frm.action='/App/loginAction.action?usertype=internal';
}
else{
//frm.action='<s:url action="loginAction.action?usertype=external" namespace="" />';
frm.action='/App/loginAction.action?usertype=external';
}
frm.target='_parent';
frm.submit();
}
function checkUserType(){
//var userType = '<s:property value="#session.usertype" />';
var userType = '<%= session.getAttribute("usertype") %>';
if(userType == 'internal'){
//frm.action='<s:url action="loginAction.action?usertype=internal" namespace="" />';
frm.action='/App/loginAction.action?usertype=internal';
frm.target='_parent';
frm.submit();
}
else if(userType == 'external'){
//frm.action='<s:url action="loginAction.action?usertype=external" namespace="" />';
frm.action='/App/loginAction.action?usertype=external';
frm.target='_parent';
frm.submit();
}
}
</script>
</head>
<body onload="javascript:checkUserType();">
<form method="POST" action="loginAction.action" name="UserTypeForm">
<div id="display_option"
style="DISPLAY: none; position: absolute; top: 40%; width: 100%;"
align="center">
<div class="rcorp-tbl">
<div style="width: 340px;">
<div style="border: 1px solid #6da6fe; padding: 5px;">
<table style="background-color: #f0f8ff;" cellspacing=2 border=0>
<tr>
<td class="t-cellsecnowrap">Select User type:</td>
<td>
<td class="t-cell">
<div id="wwgrp_systemType" class="wwgrp">
<div id="wwctrl_systemType" class="wwctrl">
<input type="radio" name="UserType" id="internal" value="internal" checked/>
<label for="userTypeInternal">Internal User (Sydney Trains Users)</label>
<input type="radio" name="userType" id="external" value="external"/>
<label for="userTypeExternal">External User</label>
<input type="button" name="applyBtn" id="applyBtn" class="btn" value="Go" title="Go" onclick="javascript:selectUserType();"/>
</div>
</div>
</td>
</tr>
</table>
</div>
</div>
</div>
</div>
</form>
</body>
</html>
Instead of trying to control it in your LoginFilter, create a new class that extends com.sun.identity.agents.filter.AmAgentFilter and configure that in your web.xml. You class would look something like this:
public class CustomFilter extends AmAgentFilter {
#Override
public void init(FilterConfig filterConfig) throws ServletException {
super.init(filterConfig);
}
#Override
public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
if (InitListener.isIAMEnabled()) {
HttpSession session = httpRequest.getSession();
String userType = (String) session.getAttribute(Constant.USER_TYPE);
if ("internal".equals(userType)) {
super.doFilter(servletRequest, servletResponse, filterChain);
}
}
filterChain.doFilter(servletRequest, servletResponse);
}
#Override
public void destroy() {
super.destroy();
}
}
The super.doFilter() call will only perform the actions in AmAgentFilter if the criteria in that if-block is met; otherwise, we ignore that filter and move on to the next one in the chain.
You would configure this filter in your web.xml instead of the AmAgentFilter.

Jersey- Rest: 404 not found error

I am doing a simple program , the task is to Get (user id) from html form over Rest and username associated with should be displayed. I am
getting a 404 error when I load the index.html page.
But when i give the values(userid) over the url it works fine.
here's the code
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>Index page</title>
</head>
<body>
<form action="http://localhost:8080/rest/my/first/rest/users" method="GET">
<label for="uid">ID</label>
<input name="uid" />
<input type="submit" value="Submit" />
</form>
</body>
</html>
and here is the resource class
#Path("users") //attach client request to resource: .../users
public class RestResource {
Map<String,User> listUsers;
//initialize some resources
public RestResource(){
listUsers = new HashMap();
listUsers.put("1",new User("1", "John"));
listUsers.put("2",new User("2", "Peter"));
}
//return list of users
#GET
#Produces(MediaType.TEXT_PLAIN)
public String listOfUsersInText(){
String list="";
for (Entry<String,User> u:listUsers.entrySet()){
list += u.getValue().getName() + "\n";
}
return list;
}
//return user information corresponding to the requested uid.
#GET
#Path("{uid}") //attach client request to resource: .../users/<uid>
#Produces(MediaType.TEXT_PLAIN)
public String getUID(#PathParam("uid") String uid){
if (!listUsers.containsKey(uid))
return "User not exist!";
return listUsers.get(uid).getID()+":"+listUsers.get(uid).getName();
}
}
WEB.xml
<display-name>rest</display-name>
<servlet>
<servlet-name>Jersey REST Service</servlet-name>
<servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
<init-param>
<param-name>com.sun.jersey.config.property.packages</param-name>
<param-value>my.first.rest</param-value>
</init-param>
<load-on-startup>1</load-on-startup>
</servlet>
<servlet-mapping>
<servlet-name>Jersey REST Service</servlet-name>
<url-pattern>/*</url-pattern>
</servlet-mapping>
The approach you have followed is wrong we have several rest client api's you can use any of those and can send the request to rest resource
The response data you can display in jsp pages.

JSP getParameters

I have a simple JSP project, which has 3 classes, controllers and DAO's
I can Login but when I click on my buttons, I just can't get the Parameters from the form.
Lemme show the code, and maybe You'll figure it out:
package school.controller;
import java.io.IOException;
import javax.servlet.RequestDispatcher;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import school.dao.StudentDAO;
import school.model.Student;
public class StudentController extends HttpServlet {
private static final long serialVersionUID = 1L;
private static String UPDATE = "/student.jsp";
private static String VIEW_COURSES = "CourseController";
private static String VIEW_GRADES = "GradeController";
private StudentDAO dao;
public StudentController() {
dao = new StudentDAO();
}
protected void doGet(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
String forward = "";
String action = request.getParameter("name");
if (action.equalsIgnoreCase("update")) {
forward = UPDATE;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
} else if (action.equalsIgnoreCase("viewgrades")) {
forward = VIEW_GRADES;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
} else if (action.equalsIgnoreCase("viewcourses")) {
forward = VIEW_COURSES;
Student student = (Student) request.getAttribute("student");
request.setAttribute("student", student);
}
RequestDispatcher view = request.getRequestDispatcher(forward);
view.forward(request, response);
}
protected void doPost(HttpServletRequest request,
HttpServletResponse response) throws ServletException, IOException {
doGet(request, response);
}
}
And here's the WEB.xml
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>School_JSP</display-name>
<welcome-file-list>
<welcome-file>index.jsp</welcome-file>
</welcome-file-list>
<servlet>
<description></description>
<display-name>CourseController</display-name>
<servlet-name>CourseController</servlet-name>
<servlet-class>school.controller.CourseController</servlet-class>
</servlet>
<servlet>
<description></description>
<display-name>StudentController</display-name>
<servlet-name>StudentController</servlet-name>
<servlet-class>school.controller.StudentController</servlet-class>
</servlet>
<servlet>
<description></description>
<display-name>LoginServlet</display-name>
<servlet-name>LoginServlet</servlet-name>
<servlet-class>school.controller.LoginServlet</servlet-class>
</servlet>
<servlet-mapping>
<servlet-name>StudentController</servlet-name>
<url-pattern>/StudentController</url-pattern>
</servlet-mapping>
<servlet-mapping>
<servlet-name>CourseController</servlet-name>
<url-pattern>/CourseController</url-pattern>
</servlet-mapping>
</web-app>
And the mainPage.jsp
<%# page language="java" contentType="text/html; charset=ISO-8859-1"
pageEncoding="ISO-8859-1"%>
<%# taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Main Page</title>
</head>
<body>
<h3>
Welcome,
<c:out value="${student.firstName}" />
</br>
<h1>My Personal Information</h1>
<center>
<form method="POST" action='StudentController' name="viewgrades">
<input type="submit" value="View My Grades" />
</form>
<form method="POST" action='StudentController' name="viewcourses">
<input type="submit" id="hidden" value="View My Courses" />
</form>
<form method="POST" action='StudentController' name="update">
<input type="submit" id="hidden" value="Update Personal Information" />
</form>
</center>
</h3>
</body>
</html>
You're confusing attributes and parameters.
Parameters are String values sent by the browser. They're accessed using the getParameterXxx() family of methods.
Attributes are data that you can add to a request (or session, or servlet context), or any type, in order to get them backlater. You typically add an attribute to the request in a servlet (for example, the information about the logged in user) in order to get back this attribute in the JSP and display the information.
In your code, the only place where you get a parameter is commented out. And you're trying to get a parameter named "hidden", although none of the form has an input field with than name. It's the name attribute of an input field that is submitted by the browser, and not its id attribute.
Also, you should use GET rather than POST for actions which consist in getting or reading things.
The reason you don't get any values is that the attribute "name" in the form, indeed is just the name of the form and isn't sent at all.
To actually send data, you need to provide some in the innerHTML of the form. Like this (not the best solution, but should you get running):
<form method="GET" action="StudentController" name="formName">
<input type="hidden" name="viewgrades" value="show" />
<input type="submit" value="View My Grades" />
</form>
After this you can read the sent data "viewgrades=show" (parameter=value) in your Java-class.
Also, btw, you shouldn't use "h3" as a paragraph ("p") or section. It is intended to be a headline.

Categories

Resources